text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Multiple statements in a for loop (1084 error) I'm trying to do a binary search in a for loop. However, flash does not like the following for loop.
for(var select:int = Math.floor((min + max / 2)), var turns:int = 0; turns < input.length / 2 + 1; turns++, select= Math.floor((min + max / 2))){
if(input[select] > want){
max = select;
} else if (input[select] < want){
min = select;
} else {
return select;
}
}
On the first line I get 1084: Syntax error: expecting identifier before var. I think I know why (I'm using , to separate the different statements), but how do I fix it? ; won't work since it's what the for loop uses.
( var select:int = Math.floor((min + max / 2)) ; var turns:int = 0); turns < input.length / 2 + 1; //etc
does not work either.
A: Simply ditching the second var (after the comma) should work I believe will do it:
for(var select:int = Math.floor((min + max / 2)), turns:int = 0; turns < input.length / 2 + 1; turns++, select= Math.floor((min + max / 2))){
if(input[select] > want){
max = select;
} else if (input[select] < want){
min = select;
} else {
return select;
}
}
A: Do you have to do this as a for loop? This would work much better as a recursive function.
Here it is as a for loop. Try pulling the select variable outside the scope of the for loop.
var select: int = Math.floor((min+max/2));
for(var turns:int = 0; turns < input.length / 2 + 1; turns++){
if(input[select] > want){
max = select;
select= Math.floor((min + max / 2))
} else if (input[select] < want){
min = select;
select= Math.floor((min + max / 2))
} else {
return select;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Interface with different parameter types and number I wanted to create a generic interface with a method I could use to convert objects ...
Let me explain.
In GWT, using GWT-Platform, the presenters have an inner interface that extends View. This interface is implemented by the class that builds the screen (the presenters have the button actions, etc.).
So, assuming I have a presenter for user account, for example. It "represents" my User bean.
I wish I could create a class implementing an interface, I could call a method passing the instance of the implementation of view, and he returned the bean populated ... I do not know if I could be clear enough ..
OK. So far so good.
I created an interface like this:
public interface ViewBeanConverter<T, U extends View>
{
public T convert(U u);
}
It works for simple views, but the problem is that sometimes I need to pass parameters that are not in the interface view, but only in the presenter class, things that does not make sense being in view.
For example, suppose the bean to build user, I need a list of belongings (the first thing that came to mind right now). And then, on another screen, a bean car for example, need an owner and a parts list for the concert... How I can handle that?
I can not explain it right, sorry about that, but the real problem is I need different amounts of different types of parameters ... and was wondering if there is a elegant way to do this.
thanks in advance.
A: for different amounts of different types of parameters, use var args
public interface ViewBeanConverter<T, V extends View>
{
public T convert(V v,Object... objects);
}
or simply a Map
public T convert(V v, Map<Object, Object> objects);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSString out of scope I used the codes below to set a NSString
#import <Foundation/Foundation.h>
@interface AppController : NSObject
{
NSString *myString;
}
@property (nonatomic, retain) NSString *myString;
@end
#import "AppController.h"
@implementation AppController
@synthesize myString;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSString *zs0= [[NSString alloc] initWithFormat: @"abc"];
myString =[zs0 retain];
[zs0 release];//breakpoint
}
- (void)dealloc {
[myString release];
[super dealloc];
}
@end
when I check the value of myString at the breakpoint
it always said 'out of scope'
Welcome any comment
A: Why are you using initWithFormat if you aren't using a format?Next, why even allocate zs0 if you aren't going to use it? Just set myString to what you want it to be.
Thus, your code should look like this:
myString = [[NSString alloc] initWithString: @"abc"];
Try that and everything should work.
A: *
*You don't need the temp variable zs0 - just assign it to the property
*You don't need initWithFormat since you're not formatting.
*You don't need to alloc the string - if you call [NSString stringWithString] it will autorelease it and then when you assign it to a (retain) property, it will retain it.
*You're over retaining. You alloc the string which gives it a retain count of 1, then you retain it which gives it 2, then you assign it to a retained property which retains it again.
One simple way is:
self.myString = [NSString stringWithString:@"abc"];
That will create a string that's autoreleased (not created with alloc, copy by convention) and then the property will retain it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to determine the remaining wait time of thread in Java I understand that there is no specific method in the Thread class that allows a program to check how many remaining time a thread has before it wakes up. But in case you need such feature, how would you implement it?
For example I have:
Thread A - at a certain condition it waits for an amount of time.
Thread B - doesn't know that thread A is set to wait for an amount of time.
Questions:
1. Is there a way for thead B to determine how many millis the thread A is set to wait?
2. How about determining how much time is remaining before the wait expires?
3. Another Thread C found that the System clock has changed, is there a way for it to determine the remaining time based on the new system clock?
Thanks
------- Edit -----
What I actually want to accomplish is to have a process scheduled to run at a specific time. I do not want to use the TimerTask for some reason so I created a Thread that will wait by (FutureDate - CurrentDate). I want to interrupt this waiting IF the system's date and time has changed (New.System.Date). Now if the (FutureDate - New.System.Date) is not so much different with (FutureDate - OldSystemDate) say just a few seconds, I wouldn't want to interrup the waiting. But if huge like a few minutes then I will have to reset the waiting to another (FutureDate - New.System.Date).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find and replace with regular expression in Visual Studio 10 For example I have the following strings :
abc Edit worksheet xyz
abc Edit contract xyz
abc Edit xyz
Now I want to replace only string "Edit" into "Detail", "Edit worksheet" "Edit contract" still remain the same. The result should be:
abc Edit worksheet xyz
abc Edit contract xyz
abc Detail xyz
I would appreciate if you can make an explain.
A: To match "Edit" only if it's not followed by the word "worksheet" or "contract", you can use this:
<Edit>~(:b+(worksheet|contract))
*
*< and > match the beginning and end of a word, respectively.
*~(...) is what most regex flavors call a negative lookahead.
*:b+ matches one or more spaces or tabs in any combination.
These constructs are available in many regex flavors, but Visual Studio uses its own, extremely unusual syntax.
A: Assuming it's the only word on the line, search for:
^Edit$
and replace with
Detail
^ matches the start of a line.
$ matches the end of a line.
A: In Visual Studio Find and Replace dialog:
Find what: Edit ~(worksheet|contract)
Replace with: Detail
A: You can do a trick like this:
*
*replace in all your code "Edit worksheet" with "ABC123"
*replace in all your code "Edit contract" with "DEF456"
*replace in all your code "Edit" with "Detail"
*replace in all your code "ABC123" with "Edit worksheet" (restore old strings)
*replace in all your code "DEF456" with "Edit contract" (restore old strings)
in other words you hide "Edit worksheet" and "Edit contract" with 2 fantasy and unique strings, then make your requested replace and finally restore your original text.
A: I don't think you need regex?
Can't you just replace "abc Edit xyz" with "abc Detail xyz"
Or is abc and xyz not always the same?
A: I would not use regular expression, but just simple string methods.
I would do a loop through all the lines looking for "Edit" and when I found it, then check if the following word is "worksheet" or "contract": in this last case I do not replace the word.
I write an example in a meta-language:
While not EnfOfLine
if "'Edit' is found" then
if not "next word is 'worksheet' or 'contract'"
then replace ("Edit", "Detail")
end if
end if
go next line
end while
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Saving a photo from photo library I have some part of application that save user data like name, address and photo. I have solve problem to take a photo from photo library.
Because that's only small database, I use NSUserDefaults to save data.
But I don't know how to save photo from photo library that I put in UIImageView...
Please give me some help..
Is it possible to use NSUserDefaults to save that photo??
A: I would consider using NSUserDefaults to store the image name rather than the data. You should be able to retrieve the image from the photo library no problem as long as you have the filename you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: (PHP) specific array sort I hope anyone can help me to fix a little problem. After getting a clear mind I still stuck and can't find a solution. I guess it is something obviously simple.
I stuck to an array structure and need to sort them. Here is a small example of the array:
$brand["BRAND_1"]["name"] = 'Brand Name 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['name'] = 'Headline Subbrand 2';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['text'] = 'text for Subbrand 2';
$brand["BRAND_2"]["name"] = 'Brand Name 2';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
There could be n amount of BRAND_N and n amount of SUB_BRAND_N.
I have an order ID which stucks to a flexible order:
0 = out as in (dont worry about this, catch it at an earlier stage)
1 = BRAND_1.SUB_BRAND_1
2 = BRAND_1.SUB_BRAND_2
3 = BRAND_2.SUB_BRAND_1
This gets extended if there are more as these four cases and the order itself could change. So I have to work with the IDs.
The order should change the position in the array and push the value of the Id to the top in the array, for example:
order id = 2:
$brand["BRAND_1"]["name"] = 'Brand Name 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['name'] = 'Headline Subbrand 2';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['text'] = 'text for Subbrand 2';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
$brand["BRAND_2"]["name"] = 'Brand Name 2';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
order id = 3:
$brand["BRAND_2"]["name"] = 'Brand Name 2';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
$brand["BRAND_1"]["name"] = 'Brand Name 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['name'] = 'Headline Subbrand 2';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['text'] = 'text for Subbrand 2';
I have tried this so far:
<?php
$order[1] = 'BRAND_1::SUB_BRAND_1';
$order[2] = 'BRAND_1::SUB_BRAND_2';
$order[3] = 'BRAND_2::SUB_BRAND_1';
// for testing
$orderId = 2;
// get the brand and sub_brand
$part = explode("::", $order[$orderId]);
// set the new brand list
$newBrand[$part[0]]['name'] = $brand[$part[0]]['name'];
$newBrand[$part[0]]['list'][$part[1]] = $brand[$part[0]]['list'][$part[1]];
// unset the brand which should be first of the main brand array
unset($brand[$part[0]]['list'][$part[1]]);
// if there was only one list unset the whole brand part
if( count($brand[$part[0]]['list']) < 1 ) {
unset( $brand[$part[0]] );
}
Now I have two arrays:
$brand includes the whole brands except this one which should be the first
$newBrand includes only this brand which should be at the top
Now I just need to add $brand to $newBrand but there is my problem :)
Tried a lot of different ways from rebuilding the array to push the content, replace or merge... but I always run in circles.
Any other idea, shorter code, better approach..?
I wrote the whole code into codepad.org for better testing:
Codepad example
Any help or suggestion appreciated.
Cheers!
EDIT:
Sorry for the misunderstanding:
The order is a specification outside the code. The aim is to set one element depending on the orderId to the top in the $brand array. The $orderId will get passed by POST, GET or a class call.
The $order array is just an array which helps me to make the specification accessible in the code.
So the $orderId match one element of the $order array and will return this element which should be on the top of the $brand array. Due to the fact that there is no numeric keys I decide to use the "brand::sub_brand" syntax to access on both depth level.
Hope this explains it a litte better.
Thanks
A: Here is one possible solution (test it here):
<?php
function getOrderingRules()
{
return array(
1 => 'BRAND_1.SUB_BRAND_1',
2 => 'BRAND_1.SUB_BRAND_2',
3 => 'BRAND_2.SUB_BRAND_1',
);
}
function getOrderedBrands($brands, $orderId)
{
$rules = getOrderingRules();
if (!isset($rules[$orderId])) {
throw new RuntimeException("Rule for order id '$orderId' is not specified");
}
$result = array();
// Push the first element
list($key, $subkey) = explode('.', $rules[$orderId]);
$result[$key] = array(
'name' => $brands[$key]['name'],
'list' => array(
$subkey => $brands[$key]['list'][$subkey],
),
);
// Push remaining elements in the order they appear in $rules
foreach ($rules as $oid => $rule) {
// Skip order id of the first element
if ($oid == $orderId) {
continue;
}
list($key, $subkey) = explode('.', $rules[$oid]);
if (!isset($result[$key])) {
$result[$key] = array(
'name' => $brands[$key]['name'],
'list' => array(),
);
}
$result[$key]['list'][$subkey] = $brands[$key]['list'][$subkey];
}
return $result;
}
// Loading all brands (could be external source, like database)
$brand["BRAND_1"]["name"] = 'Brand Name 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['name'] = 'Headline Subbrand 2';
$brand["BRAND_1"]["list"]['SUB_BRAND_2']['text'] = 'text for Subbrand 2';
$brand["BRAND_2"]["name"] = 'Brand Name 2';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['name'] = 'Headline Subbrand 1';
$brand["BRAND_2"]["list"]['SUB_BRAND_1']['text'] = 'text for Subbrand 1';
// Sort and output
print_r(getOrderedBrands($brand, 1));
print_r(getOrderedBrands($brand, 2));
print_r(getOrderedBrands($brand, 3));
You should be aware that with this array structure ($brands) you won't be able to set ordering rules like this:
1 = BRAND_1.SUB_BRAND_1
2 = BRAND_2.SUB_BRAND_1
3 = BRAND_1.SUB_BRAND_2
because once you met element keyed by BRAND_1, you have to iterate over all of it's sub-brands. If you don't have such rules, everything is fine. Otherwise you have to store sorted array structured like this (because actually you are sorting sub-brands, not brands):
$subBrands = array(
array(
'name' => 'Headline Subbrand 1',
'text' => 'Text for it',
'parent' => 'BRAND_1',
'key' => 'SUB_BRAND_1',
),
array(
'name' => 'Headline Subbrand 2',
'text' => 'Text for it',
'parent' => 'BRAND_1',
'key' => 'SUB_BRAND_2',
),
);
$parentBrands = array(
'BRAND_1' => 'Brand Name 1',
'BRAND_2' => 'Brand Name 2',
);
Then you can sort $subBrands and iterate over it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Build Error:Undefined symbols for architecture x86_64: I am completely new in programming with c++ using the Xcode IDE. What I do is I created a Hashtable myself, and clicked the build button, and I got compilation errors as such. Does anyone have ideas about what is going wrong?
This is the error:
Undefined symbols for architecture x86_64:
"MyHashtable<std::string, int>::MyHashtable(int)", referenced from:
_main in main.o
"MyHashtable<std::string, int>::Insert(std::string, int)", referenced from:
_main in main.o
"MyHashtable<std::string, int>::GetKeys()", referenced from:
_main in main.o
"MyHashtable<std::string, int>::GetLength()", referenced from:
_main in main.o
"MyHashtable<std::string, int>::GetValue(std::string)", referenced from:
_main in main.o
"MyHashtable<std::string, int>::~MyHashtable()", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
The cpp file of hashtable is as such:
#include <iostream>
#include "Hashtable.h"
#include <string>
template<typename T1,typename T2>
MyHashtable<T1,T2>::MyHashtable(int iSlots)
{
if(iSlots<5) iSlots = 5;
m_hashSlots = new HashElement<T1,T2>*[iSlots];
m_hashSlots = iSlots;
m_Length = 0;
}
template<typename T1,typename T2>
MyHashtable<T1,T2>::~MyHashtable()
{
if(m_hashSlots)
{
HashElement<T1, T2> * phead;
for(int i = 0;i<m_NumSlots;i++)
{
phead = m_hashSlots[i];
while(phead!=0)
{
HashElement<T1, T2>* pNext = phead->next;
delete phead;
phead = pNext;
}
}
delete m_hashSlots;
m_hashSlots = 0;
}
}
template<typename T1,typename T2>
int MyHashtable<T1,T2>::HashKey(T1 key)
{
char* keyString = (char*)key;
int keyNum = 0;
for(int i = 0;i<strlen(keyString);i++)
{
int ascK = keyString[i];
keyNum += ascK;
}
return keyNum%m_NumSlots;
}
template<typename T1,typename T2>
T1* MyHashtable<T1,T2>::GetKeys()
{
T1* keys = new T1[m_Length];
int index = 0;
for(int i = 0;i<m_NumSlots;i++)
{
HashElement<T1,T2> *phead = m_hashSlots[i];
while(phead!=0)
{
keys[index] = phead->key;
index++;
phead = phead->next;
}
}
return keys;
}
template<typename T1,typename T2>
T2 MyHashtable<T1,T2>::GetValue(T1 key)
{
int index = HashKey(key);
HashElement<T1,T2> *phead = m_hashSlots[index];
while(phead)
{
if(phead->key==key)
return phead->value;
else
phead = phead->next;
}
return NULL;
}
template<typename T1,typename T2>
int MyHashtable<T1,T2>::GetLength()
{
return m_Length;
}
template<typename T1,typename T2>
bool MyHashtable<T1,T2>::Insert(T1 key, T2 value)
{
int index = HashKey(key);
HashElement<T1,T2> *phead = m_hashSlots[index];
while(phead)
{
if(phead->key == key) {
int newValue = (int)(phead->value);
newValue += int(value);
return true;
} else {
phead = phead->next;
}
}
HashElement<T1,T2>* newNode = new HashElement<T1,T2>();
newNode->key = key;
newNode->value = value;
phead->next = newNode;
return true;
}
A: Template definition inside of cpp file? Try putting it inside of the header file. The compiler will create a new instance of the class when you declare the instance (MyHashTable<int,int> myVar;), and so during include the entire class definition needs to be present. Hence, the h file instead of the cpp file.
I'm not sure if this is the entire problem, as I don't use XCode, but it sounds like the issue to me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I use CSS to vertically center the text in an anchor, within a LI? Variations on this question have been asked many times. Vertical centering with CSS is a challenge.
I have a particular scenario, dealing with a list displayed horizontally. The markup is like this:
<ul id='ul1' class='c'>
<li><a href='javascript:void(0)'>Fribble Fromme</a></li>
<li><a href='javascript:void(0)'>Fobble</a></li>
<li><a href='javascript:void(0)'>Foo Fickle Pickle</a></li>
</ul>
The style is like this:
ul.c {
height:52px;
text-align:center;
}
ul li a {
float:left;
text-decoration:none;
border: 1px solid Maroon;
padding:2px 12px;
background:#FFEF8A;
line-height:1em;
width:100px;
}
ul li a:hover {
background: #CCC;
}
ul li {
height:52px;
display:inline-block;
}
The resulting list looks like this:
But I want all the boxes to be the same height, and I want the text to be vertically centered in each box. I can set the box-height by adding a height style for the A elements. The result looks like this:
...which is close to what I want, but the vertical-centering isn't happening.
I can set line-height for the text, as suggested in this post, to do the vertical centering. I can even pick different values of line-height for different A elements, if I know which of the elements will get multiple lines of text. But I don't know which ones will require multiple lines.
How can I get it to center when some of the A elements have text that wraps?
A: Old question, but the answer can now be updated with Flexbox.
a {
height: 60px;
display: flex;
align-items: center;
justify-content: center;
}
A: You could use display:table, etc. along with vertical-align:middle
ul.c {
text-align:center;
display:table;
}
ul li {
float:left;
}
ul li a {
text-decoration:none;
border: 1px solid Maroon;
padding:2px 12px;
background:#FFEF8A;
width:100px;
height:52px;
display:table-cell;
vertical-align:middle;
}
ul li a:hover {
background: #CCC;
}
Example: http://jsfiddle.net/kf52n/2/
A: I could not figure a way to do this in CSS. I found that I could do what I needed with Javascript, setting the padding-top and padding-bottom to appropriate values at runtime. The technique is to measure the "natural" height of the A element, then set the padding so that the A element is vertically centered.
here is the necessary js code:
function setHeightIntelligently(ulElement) {
var items, L1, i, anchor, availableHeight = ulElement.clientHeight,
naturalHeight, pad;
items = ulElement.children;
for(i=0, L1 = items.length;i<L1;i++){
if (items[i].tagName.toUpperCase() == 'LI') {
anchor = items[i].children[0];
naturalHeight = anchor.clientHeight;
pad = (availableHeight - naturalHeight)/2;
anchor.style.paddingTop= pad+'px';
anchor.style.paddingBottom= pad+'px';
}
}
}
function init() {
var element = document.getElementById('ul1');
setHeightIntelligently(element);
}
In the CSS, one must not explicitly set height or padding for the A elements. Doing that would cause the "natural" height to not be what we need it to be.
The result is like this:
To see it in action, go here.
A: in the css you have set the height and line-height to the same. Then you will get a rectangular box.
But still you are seeing space in the bottom the reason is due to padding
adding two values in padding adds top and bottom padding
padding: top bottom;
since it is 2 and 12 you are seeing huge space.
try this
height: 52px;
line-height:52px;
padding: 6px 6px; // here you have to tweak and see the output
vertical-align:center;
let me know it is working
A: line-height:250%; worked for me
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Passing a generic definition of a collection as a type parameter - or how to use "List<>" as a type parameter I'll try to be as straight-forward as possible.
I want to be able to do something like this:
var mylookup = new ModifiableLookup<MyClass, int, List<> >();
var myhashlookup = new ModifiableLookup<MyClass, int, HashSet<> >();
While having a generic class along this lines:
class ModifiableLookup<TKey, TElement, TElementCollection<> > : ILookup<TKey, TElement>
where TElementCollection<> : ICollection<TElement>, new()
{
private Dictionary<TKey, TElementCollection<TElement> > data;
/// ... so on and so forth
}
But Alas, this does not work...
The work-around is to repeat the type parameter:
var mylookup = new ModifiableLookup<MyClass, int, List<int> >();
///...
class ModifiableLookup<TKey, TElement, TElementCollection> : ILookup<TKey, TElement>
where TElementCollection : ICollection<TElement>, new()
Is there a way to accomplish something like this without repeating the collection element type parameter and without using reflection?
A: No, it's not possible within your constraints. Open generic types can only appear as parameters to the typeof operator. They are not permitted anywhere else in your source.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Array As Grid, How to Move Diagonally? I have an array of size n^2 representing a square grid of size nxn.
I want to get from any square (0 to (n^2)-1) to the top-right most square you can get to moving diagonally in a straight line.
I already figured out that to get to the top-left most square is to take the current square x and the top-left most square is x%(n+1).
Does anyone know a similar method for top-right most square? Thanks!
A: If I understood at all what you're trying to achieve, all you need to do is connect the two points with a straight line and using the line formulas calculate the coordinates of the cells that it goes through. You may use for this the Bresenham's line drawing algorithm.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: NSCountedSet - get count of items in set I have a array of info that has multiple Names that I want to match and count then move to a table view such as you would see on a messages app.
I have reached to this point. Where I can log and see what I want but simply can not find any solution pulling that info from the set and placing into a tableview accordingly.
example
- (void)directMessagesReceived:(NSArray *)messages forRequest:(NSString
*)connectionIdentifier{
for(NSDictionary *d in messages) {
// NSLog(@"See Direct Messageges Parsing Info: %@", d);
Tweet *tweetDic = [[Tweet alloc] initWithTweetDictionary:d];
//[directMessages addObject:tweetDic];
[tweetDic autorelease];
}
//[arayToScan addObject:[messages valueForKey:@"sender_screen_name"]];
[arayToScan addObjectsFromArray:messages];
[self checkForDuplicateIDs];
// NSLog(@"Same ScreenName Received: %@", arayToScan);
//[self.mainTableView reloadData];
NSLog(@"DM COUNT = %i",[directMessages count]);
[DSBezelActivityView removeViewAnimated:YES];
}
- (NSSet *)checkForDuplicateIDs {
//CHECK FOR DUPLICATES IN ARRAY
NSArray *allIDs = [arayToScan valueForKeyPath:@"sender_screen_name"];
NSArray *sortedIDs = [allIDs sortedArrayUsingSelector:@selector(compare:)];
NSString *previousID = nil;
duplicateIDs = [NSMutableSet set];
for (NSString *anID in sortedIDs) {
if ([previousID isEqualToString:anID]) {
[duplicateIDs addObject:anID];
}
previousID = anID;
}
//THEN REMOVE ANY DUPLICATES IN NEW ARRAY
NSCountedSet *countedSet = [NSCountedSet setWithArray:sortedIDs];
NSMutableArray *oneMess = [NSMutableArray arrayWithCapacity:[sortedIDs count]];
NSMutableArray *multipleMess = [NSMutableArray arrayWithCapacity:[sortedIDs count]];
for(id obj in countedSet) {
if([countedSet countForObject:obj] == 1) {
[oneMess addObject:obj];
}
for(id duplicatenames in countedSet) {
if ([countedSet countForObject:duplicatenames]>1) {
[multipleMess addObject:duplicatenames];
[countedSet countForObject:duplicatenames];
}
}
}
//NSLog(@"NSCountedSet = %@",[countedSet allObjects]);
//NSLog(@"NSCountedSet = %@",countedSet);
//NSLog(@"One Message = %@",oneMess);
// NSLog(@"Multiple Messages = %@",multipleMess);
//HERE I HAVE ORIGINAL ARRAY IN ALBETICAL ORDER
// NSLog(@"Messages Containing more then 1 = %@",sortedIDs);
//HERE I HAVE DUPLICATES IN ALBETICAL ORDER
// NSLog(@"Messages Containing more then 1 = %@",duplicateIDs);
//HERE I HAVE THE MESSAGES ONLY CONTAING 1
//NSLog(@"Messages Containing only 1 = %@",oneMess);
//NOW I WANT TO COUNT THE DUPLICATES TO PLACE AS A STRING IN CELL FOR # OF MESSAGES & #
OF ROW IN TBLVIEW
//NSLog(@"Duplicates count = %i",[duplicateIDs count]);
// NSLog(@"Messages Containing only count = %i",[oneMess count]);
//HERE I WOULD ADD BOTH ARRAYS AND SEND TO MY ARRAY BELOW WHICH IS USED FOR MY TBLVIEW
THIS INFO IS RETRIEVABLE WHAT I NEED IS THE # OF EACH DUPLICATE AS SEEN
//ARRAY *NEWARRAY INIT WITH OBJECTS ,ONEMESS, MULTIPLEMESS,
//ARRAY CUSTOM # OF EACH MULTIPLE MESSAGE TO SHOW IN TBLVIEW???
//THEN I CAN CONTINUE WITH THE BELOW METHOD TO RELOD THE TABLEVIEW
//[directMessages addObject:NEWARRAY];
//[self.mainTableView reloadData];
return [[duplicateIDs copy] autorelease];
}
This is the log... this happens as many times as it counts but I just logged it to see if it was working which its is. Any help would be greatly appreciated
Counted = <NSCountedSet: 0x6d8cb80> (Nkapoor124 [33], iphonetechtips [3], jima6636 [4], pro1995 [2], iphone266 [2], eenofonn [1], iphoneMaster323 [3], FreeAppl3 [2], Bababooey13 [7], _CL1CK_ [5], _ToyVan_ [4], Nucleiosis [26], dracossaint [6], AlexInHouston [1], FlybriTn [7], iOSGraphix [1], deckedsg [5], 19est80 [3], JHackstar [2], barsoverbeats [7], anonomys209 [5], 87whitestallion [1], bAdGigabit [55], Sgt_Impacto [3], Nazaroth [2], K_Nitsua [1], MannyIphone [6], iphoneman76 [3])
A: In your clarification, you asked for the amount (number?) of each duplicate. You can get at the count below. If you're looking for the number of times each is duplicated (instead of total count of each) then that's count - 1 for each. If it's count - 1 is 0, there's no duplicates.
I think you're looking for NSCountedSet countForObject method.
The sample below ...
NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];
for (id item in set)
{
NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
}
Will output:
2011-09-30 01:00:50.665 Craplet[7854:707] Name=Jane, Count=1
2011-09-30 01:00:50.679 Craplet[7854:707] Name=John, Count=2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What is the right way to initialize an object that invoke an instance method of its mother? The question is as of the title. Say I have a simple example below:
class Vehicle
attr_accessor :wheels
end
class Car < Vehicle
def initialize
self.wheels = 4
end
end
class Truck < Vehicle
def initialize
@wheels = 16
end
end
I am curious which way is considered correct or better to invoke
wheels writer method of mother Vehicle?
A: self.wheels = 4 is more flexible because under the hood it is calling a setter method: self.wheels=(4)
So if you ever wanted to do something with the value before it is placed into @wheels, you could define that function:
def wheels=(val)
# do something
@wheels = new_val
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: branching team project I have the following at Source Control Explorer
TFSServer/teamCollection
+ teamproject
Is is possible to branch /teamproject to /teamproject-dev? The output should be
TFSServer/teamCollection/
+ teamproject-dev
I tried and it gave me error:
TF10175: The team project folder $/teamproject-dev does not exist. Contact your Team Foundation Server Administrator and ask that it be created.
A: Top level folders in source control are reserved for team projects. If you create a new "teamproject-dev" project you could branch the code from the existing "teamproject" into the new -dev project via the wizard.
Alternatively set up a proper branching structure inside teamproject. Read the TFS Branching Guide for more information.
A: Yes, you can convert team project into branch.
The above error is saying that you don't have access to create branch. First you create branch by getting help from TFS admin then try what you mentioned that should work fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Spring properties file -Conditional Properties true/false I have a properties file with a boolean key say trueFlag.
dev.properties
trueflag=true
I want it to be used in my application context in two places
<property name="autoStartup" value="${trueflag}"></property>
and another
Note: the negation
<property name="autoStartup" value="!${trueflag}"></property>
Is this possible? How can I achieve this. Code snippets will be helpful as I am new to Spring
A: The ${...} syntax only represents a placeholder. It's not an EL syntax. For that, you'd want to look into Spring EL.
A: Try this #{!${trueflag}} using the SpEL
A: Finally resolved from the previous hint,
One can give it this way
<property name="autoStartup" value="#{!${trueflag}}"></property>
Thanks stivlo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ClassNotFoundException: Main Class in JAR file via ANT build Basically I'm attempting to run a JAR file which I've created using an ANT buildfile. The program needs to use an external jar in order to compile correctly. I've included it in the class-path of the JAR manifest. Upon running it spits out a stack trace letting me know it cant find the main class.
The stack trace is as follows:
[java] java.lang.NoClassDefFoundError: $edu/gatech/oad/antlab/pkg1/AntLabMain
[java] Caused by: java.lang.ClassNotFoundException: $edu.gatech.oad.antlab.pkg1.AntLabMain
[java] at java.net.URLClassLoader$1.run(Unknown Source)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClass(Unknown Source)
[java] at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClass(Unknown Source)
[java] Could not find the main class: $edu.gatech.oad.antlab.pkg1.AntLabMain. Program will exit.
[java] Exception in thread "main"
[java] Java Result: 1
But when I check the jar file under\edu\gatech\oad\antlab\pkg1, AntLabMain.class is there. Strange.
I'll include the XML source code below, to be honest I'm not sure what is causing the problem. My best guess is its something wrong with the way I JAR the files but I've been at it for hours with no end in sight.
<project name="My Buildfile" default="all" basedir=".">
<target name="init" depends="prepare" description="Initialize and set up properties">
<property name="src.dir" location="./src/" />
<property name="build.dir" location="build" />
<property name="library.dir" location="lib" />
<property name="apidoc.dir" location="apidoc" />
</target>
<target name="prepare" description="Making required directories">
<mkdir dir="build" />
<mkdir dir="apidoc" />
</target>
<target name="compile" depends="init" description="Compiling necessary files">
<javac destdir="${build.dir}" includeantruntime="first">
<src path="${src.dir}" />
<classpath>
<pathelement path="${build.dir}" />
<fileset dir="${library.dir}" includes="**/*.jar" />
</classpath>
</javac>
</target>
<target name="javadoc" depends="init" description="Generating useful javadocs">
<javadoc sourcepath="${src.dir}" access="public" destdir="${apidoc.dir}">
<fileset dir="${src.dir}">
<include name="**/*.java" />
</fileset>
<classpath>
<fileset dir="${library.dir}" includes="**/*.jar" />
</classpath>
</javadoc>
</target>
<target name="jar" depends="compile" description="JARing files for distribution">
<jar destfile="${build.dir}/AntLabRun_Test.jar" basedir="${build.dir}" excludes="**/*.jar">
<manifest>
<attribute name="Main-Class" value="edu.gatech.oad.antlab.pkg1.AntLabMain" />
<attribute name="Class-Path" value="${library.dir}\resources.jar" />
</manifest>
</jar>
</target>
<target name="run" depends="jar" description="Now running the program">
<java jar="${build.dir}/AntLabRun_Test.jar" fork="true">
<classpath>
<fileset dir="${library.dir}" includes="**/*.jar" />
</classpath>
</java>
</target>
<target name="all" depends="run" description="Doing EVERYTHING!">
</target>
<target name="clean" depends="init" description="Cleaning Directories">
<delete dir="${build.dir}" />
<delete dir="${apidoc.dir}" />
</target>
Lastly, I'll include the manifest that gets zipped up with the JAR
This is my first stab at Ant buildfiles, so I am not well versed in them. Hopefully I've provided enough information to get the ball rolling.
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.2
Created-By: 1.6.0_21-b07 (Sun Microsystems Inc.)
Main-Class: edu.gatech.oad.antlab.pkg1.AntLabMain
Class-Path: C:\Users\Mike Sandt\workspace\M4\lib/resources.jar
A: Looking at your manifest file, it appears that the Main-Class attribute has an extra $ in front of the class name. Try removing that, recompiling the jar, and executing it again.
Also, if you are planning on running this jar on other computers, you might consider changing the Class-Path attribute in your manifest file to a relative path..
A: It turns out the answer was simple. I needed to edit my init target to set the properties as values as opposed to locations.
i.e.
<target name="init" depends="prepare" description="Initialize and set up properties">
<property name="src.dir" location="./src/" />
<property name="build.dir" value="build" />
<property name="library.dir" value="lib" />
<property name="apidoc.dir" value="apidoc" />
</target>
Thank you all for your responses.
A: As a last resort you can extract resources.jar in your build folder(instead of including it in class path) and generate your jar file again(with files extracted from resources.jar included in it).
A: Others already pointed out the $ issue on the class name.
Question, does your AntLabMain class have any static initializers that run when the class is loaded? If so, and if one of those initializers fails, then the JVM will report that the AntLabMain class is not found, because it failed to load it. It is really the wrong error but what you will see.
So if you do have statics initialization in the class, then check to ensure all of that is working correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to select form elements under a using jquery? There are form elements under a div, I do not know the type. It might be checkboxes or radios or select. how to select form elements without specifying the element type under a using jquery?
A: Use the :input selector:
$(':input')
Which is basically short hand for:
$('input, select, textarea, button')
A: In many case you want to select all form elements but exclude buttons , for that case use
$(":input[type!='submit'][type!='reset']")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Ruby mixin: extend or include? I have following code:
module CarHelper
def call_helpline
puts "Calling helpline..."
end
end
class Car
extend CarHelper
end
class Truck
class << self
include CarHelper
end
end
# Test code
Car.call_helpline
Truck.call_helpline
In fact both 2 lines of test codes works. So is there any difference
between the way I use 'extend' and 'include' (inside a singleton class
of self)?
A: No , It's the same thing but the first way is cleaner .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How get touchs size In android is possible get size and pressure of a touch. In iOS I know that isn't possible get pressure. But, at least the touch size, some how?
A: I search a little more and I conclude:
There is no support for that according to this another Q&A
I little more and even private API couldn't help. What make me believe the touchscreen controller doesn't send the low-level detailed touch, but direct the calculated point. Who knows?!
Now I should rethink about my app interaction. I hope it helps others in the same problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: read, highlight, save PDF programmatically I'd like to write a small script (which will run on a headless Linux server) that reads a PDF, highlights text that matches anything in an array of strings that I pass, then saves the modified PDF. I imagine I'll end up using something like the python bindings to poppler but unfortunately there's next to zero documentation and I have next to zero experience in python.
If anyone could point me to a tutorial, example, or some helpful documentation to get me started it would be greatly appreciated!
A: Yes, it is possible with a combination of pdfminer (pip install pdfminer.six) and PyPDF2.
First, find the coordinates (e.g. like this). Then highlight it:
#!/usr/bin/env python
"""Create sample highlight in a PDF file."""
from PyPDF2 import PdfFileWriter, PdfFileReader
from PyPDF2.generic import (
DictionaryObject,
NumberObject,
FloatObject,
NameObject,
TextStringObject,
ArrayObject
)
def create_highlight(x1, y1, x2, y2, meta, color=[0, 1, 0]):
"""
Create a highlight for a PDF.
Parameters
----------
x1, y1 : float
bottom left corner
x2, y2 : float
top right corner
meta : dict
keys are "author" and "contents"
color : iterable
Three elements, (r,g,b)
"""
new_highlight = DictionaryObject()
new_highlight.update({
NameObject("/F"): NumberObject(4),
NameObject("/Type"): NameObject("/Annot"),
NameObject("/Subtype"): NameObject("/Highlight"),
NameObject("/T"): TextStringObject(meta["author"]),
NameObject("/Contents"): TextStringObject(meta["contents"]),
NameObject("/C"): ArrayObject([FloatObject(c) for c in color]),
NameObject("/Rect"): ArrayObject([
FloatObject(x1),
FloatObject(y1),
FloatObject(x2),
FloatObject(y2)
]),
NameObject("/QuadPoints"): ArrayObject([
FloatObject(x1),
FloatObject(y2),
FloatObject(x2),
FloatObject(y2),
FloatObject(x1),
FloatObject(y1),
FloatObject(x2),
FloatObject(y1)
]),
})
return new_highlight
def add_highlight_to_page(highlight, page, output):
"""
Add a highlight to a PDF page.
Parameters
----------
highlight : Highlight object
page : PDF page object
output : PdfFileWriter object
"""
highlight_ref = output._addObject(highlight)
if "/Annots" in page:
page[NameObject("/Annots")].append(highlight_ref)
else:
page[NameObject("/Annots")] = ArrayObject([highlight_ref])
def main():
pdf_input = PdfFileReader(open("samples/test3.pdf", "rb"))
pdf_output = PdfFileWriter()
page1 = pdf_input.getPage(0)
highlight = create_highlight(89.9206, 573.1283, 376.849, 591.3563, {
"author": "John Doe",
"contents": "Lorem ipsum"
})
add_highlight_to_page(highlight, page1, pdf_output)
pdf_output.addPage(page1)
output_stream = open("output.pdf", "wb")
pdf_output.write(output_stream)
if __name__ == '__main__':
main()
A: Have you tried looking at PDFMiner? It sounds like it does what you want.
A: PDFlib has Python bindings and supports these operations. You will want with PDI if you want to open a PDF. http://www.pdflib.com/products/pdflib-family/pdflib-pdi/ and TET.
Unfortunately, it is a commercial product. I have used this library in production in the past and it works great. The bindings are very functional and not so Python. I have seen some attempts to make them more Pythonic: https://github.com/alexhayes/pythonic-pdflib You will want to use: open_pdi_document().
It sounds like you will want to do search highlighting of some sort:
http://www.pdflib.com/tet-cookbook/tet-and-pdflib/highlight-search-terms/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: HTML and CSS works fine in Chrome and Firefox but not IE7 I am developing a site at the moment for Google Sites, and am looking to embed the HTML below as a gadget to display my own custom menu bar.
I'm not a HTML or CSS expert so I took this sample code from a tutorial and attempted to use it myself.
The problem is that it works fine in Firefox and Chrome but not in IE7.
What is the best way to troubleshoot these types of issues? Is there any tool that can perform an analysis within IE and let me know the issue?
Thanks
<style type="text/css">
body {background-color:transparent}
.outer {display:block}
.outer img {width:100%; height:100%; border:0}
html>body .outer img {display:block}
.outer a:hover {visibility:visible}
.outer a:hover img {visibility:hidden}
#home {background-image:url(https://lh4.googleusercontent.com/-SM4Zlc_m4sE/ToUeELn6dYI/AAAAAAAAAA4/srLee9XEP5s/HomeOnHoverMenuTile.png)}
#news {background-image:url(https://lh4.googleusercontent.com/-UKhdMKoFs1o/ToUryay5cbI/AAAAAAAAACk/Fq4BprNrKYQ/NewsOnHoverMenuTile.png)}
#history {background-image:url(https://lh3.googleusercontent.com/-b41VthyFbjM/ToUeEYy8PQI/AAAAAAAAAA8/zTlQLkQaxrQ/HistoryOnHoverMenuTile.png)}
#clubgear {background-image:url(https://lh4.googleusercontent.com/-ihsPwNu_f6s/ToUeEPSC2XI/AAAAAAAAAA0/G-B6SVXR2DY/ClubGearOnHoverMenuTile.png)}
</style>
<base target="_parent">
<table align="center" style="background-color:#FFFFFF" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td><div class="outer" id="home"><a href="http://www.google.ie"><img src="https://lh5.googleusercontent.com/-p2m5ub3oghM/ToUqR7X0x-I/AAAAAAAAABo/5YYOpHVrN5E/HomeMenuTile.png"></a></div></td>
<td><div class="outer" id="news"><a href="http://www.google.ie"><img src="https://lh5.googleusercontent.com/-gZbD2wwe3no/ToUqRzW8KcI/AAAAAAAAABk/wErW3cRYDT0/NewsMenuTile.png"></a></div></td>
<td><div class="outer" id="history"><a href="http://www.google.ie"><img src="https://lh6.googleusercontent.com/-iRj10FazPSs/ToUqR82toZI/AAAAAAAAABg/3zOlviqH_ig/HistoryMenuTile.png"></a></div></td>
<td><div class="outer" id="clubgear"><a href="http://www.google.ie"><img src="https://lh4.googleusercontent.com/-4hwFSaBOUh4/ToUeE1XbIYI/AAAAAAAAABI/ngtqhT5gcIE/ClubGearMenuTile.png"></a></div></td>
</tr>
</tbody>
</table>
A: IE7 and below has some problems with visibility.
So, these styles may be causing the errors for you:
.outer a:hover {visibility:visible}
.outer a:hover img {visibility:hidden}
You can read more here: http://reference.sitepoint.com/css/visibility
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create base dn on Open ds Im using OPEN ds 2.2 as my LDAP server currently i want a create a base dn like dc=esamurdhiint,dc=lk
i create following ldif file and run and i, having error on that
my ldif file
dn: dc=esamurdhiint,dc=lk
objectClass: domain
objectClass: top
dc: esamurdhiint
my command id
ldapmodify -h 10.136.78.27 -p 1389 -D "cn=admin,ou=system" -w changeit -a -f /tmp/ldap.ldif
" adding new entry "dc=esamurdhiint,dc=lk"
ldap_add: No such object (32)
additional info: The provided entry dc=esamurdhiint,dc=lk cannot be added because its suffix is not defined as one of the suffixes within the Directory Server ".
A: ./dsconfig set-backend-prop --backend-name userRoot --add base-dn:dc=<<esamurdhiint,dc=lk>>
--hostname localhost --port 4444 --bindDN cn=admin,ou=system --bindPassword changeit
--trustAll --noPropertiesFile --no-prompt
A: As Roshan indicated, you need to configure the suffix (base-dn) first and specify which database backend it will be in.
You may choose to add the suffix to the default backend (userRoot) or to a new backend.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Using schemaextender to extend the ATEvent class I have used schemaextender to extend ATEvents so that they include a checkbox for toggling the time and iCal display for events.
It works fine on an existing site but when I try and create a new site i get an error "ValueError: nextPreviousEnabled.default_method is neither a method of nor a callable"
Any ideas? The extension code:
from Products.Archetypes.public import BooleanField
from archetypes.schemaextender.field import ExtensionField
class DisplayEventTimeField(ExtensionField, BooleanField):
"""A toggle to indicate whether the view should display the time or just the date of this community event"""
from zope.component import adapts
from zope.interface import implements
from archetypes.schemaextender.interfaces import ISchemaExtender
from Products.Archetypes.public import BooleanWidget
from Products.ATContentTypes.interface import IATEvent
class EventExtender(object):
adapts(IATEvent)
implements(ISchemaExtender)
fields = [
DisplayEventTimeField("display_event_time",
widget = BooleanWidget(
label="Display event time",
description="Turn this off to show only the event date (also disables iCal/vCal)",
defult=True)),
]
def __init__(self, context):
self.context = context
def getFields(self):
return self.fields
and the full traceback:
Traceback (innermost last):
Module ZPublisher.Publish, line 127, in publish
Module ZPublisher.mapply, line 77, in mapply
Module Products.PDBDebugMode.runcall, line 70, in pdb_runcall
Module ZPublisher.Publish, line 47, in call_object
Module Products.CMFPlone.browser.admin, line 201, in __call__
Module Products.CMFPlone.factory, line 83, in addPloneSite
Module Products.GenericSetup.tool, line 330, in runAllImportStepsFromProfile
- __traceback_info__: profile-Products.CMFPlone:plone-content
Module Products.GenericSetup.tool, line 1085, in _runImportStepsFromContext
Module Products.GenericSetup.tool, line 999, in _doRunImportStep
- __traceback_info__: plone-content
Module Products.CMFPlone.setuphandlers, line 486, in importContent
Module Products.CMFPlone.setuphandlers, line 234, in setupPortalContent
Module Products.CMFPlone.utils, line 306, in _createObjectByType
Module Products.CMFCore.TypesTool, line 554, in _constructInstance
Module Products.ATContentTypes.content.topic, line 6, in addATTopic
Module Products.Archetypes.BaseFolder, line 96, in manage_afterAdd
Module Products.Archetypes.BaseObject, line 159, in manage_afterAdd
- __traceback_info__: (<ATTopic at /Plone/news/aggregator>, <ATTopic at /Plone/news/aggregator>, <App.ProductContext.__FactoryDispatcher__ object at 0x1071bfd50>)
Module Products.Archetypes.BaseObject, line 174, in initializeLayers
Module Products.Archetypes.Schema, line 338, in initializeLayers
Module Products.Archetypes.Storage, line 161, in initializeField
Module Products.Archetypes.Field, line 591, in getDefault
ValueError: nextPreviousEnabled.default_method is neither a method of <class 'Products.ATContentTypes.content.topic.ATTopic'> nor a callable
A: Try to use a browserlayer and to implement IBrowserLayerAwareExtender intead of ISchemaExtender:
...
from archetypes.schemaextender.interfaces import IBrowserLayerAwareExtender
from my.product.browser.interfaces.IMyProductLayer
class EventExtender(object):
adapts(IATEvent)
implements(IBrowserLayerAwareExtender)
layer = IMyProductLayer
...
This ensure that the schema is extended only when your product is installed. Generally speaking it's always recommended to maintain the isolation of customizations to the actual plone instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I migrate facebook comments from my old site A to site B? I have an iFrame Facebook Tab application that uses the fb:comments module. I am migrating to a new domain name.
How do I get my old comments on where the new domain will be?
So I want to move my comments from domainA.com to domainB.com
A: There is no way to migrate comments from one domain to another. If you wanted, your new domainB could still use the existing domainA comments by setting the data-href or href property of the comments plugin to the old domainA url.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting number as Int from a key press I'm trying to get an integer from the number keys on the keyboard. For example, I want to press 5 and get the int 5.
I am using the KeyDown event and have the following:
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
int rating = (int)e.KeyValue;
}
And the output that I am getting are integers from the 50-60 range. I have tried also using e.KeyData and e.KeyCode without any luck.
Any help with this would be appreciated, I get the feeling it's something simple that I am overlooking or not understanding.
A: e.KeyValue returns the character code of the key pressed.
To get the actual digit you could do some character subtractions i.e.
int value = 0;
if (e.KeyValue >= 48 && e.KeyValue <= 57)
value = e.KeyValue - 48;
NB: If you're wondering where 48 and 57 come from then you may want to check out the ASCII table: http://www.asciitable.com/index/asciifull.gif
A: This works.... kinda hacky...
Convert.ToInt32(e.KeyData.ToString()).Replace("D",""));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Really Slow Performance Reading from Access 2007 (accdb) file from C# I am writing an application on Visual Studio 2008 with C#. The application reads data from an access file and then generates a txt file. I was doing some tests with a mdb file with 1.000.000 records and almost 1GB size.
The code is like this and the overall process was taking between 8 - 10 minutes to complete.
var connStr = string.Format("Provider =Microsoft.Jet.OLEDB.4.0; Data Source={0};Persist Security Info=False", this.dbPath);
using (var conn = new OleDbConnection(connStr))
{
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT * from Registros r, FOIDS f where r.TICKET = f.TICKET";
command.CommandType = System.Data.CommandType.Text;
conn.Open();
int i = 0;
string ticket = string.Empty;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
i++;
if (!reader.IsDBNull(reader.GetOrdinal("r.TICKET")))
{
ticket=reader.GetString(reader.GetOrdinal("r.TICKET"));
// Some process
}
}
}
}
}
}
Today I received an accdb file (Access 2007), so I've changed my connection string to this one:
connStr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False", this.dbPath);
But after that change, reading the new file is taking about 4-5 seconds per record !!! So, my overall process would take a lot of DAYS to complete!
I've tried converting the accdb file to an old mdb file and after that reading again with the previous connection string, but the problem remains. I think is a problem with the database itself but I don't know what to do, in internet i didn't found any information with this kind of problem.
Any ideas? Suggestions?
A: In my experience, 5 years ago.
One of the access database exceeded 20000 records and the size was around 150 MB. It started to slow down and performance plummeted. So moved to SQL.
You may consider using SQL compact edition, or sql lite
thanks
A: In addition to switching to one of the suggested databases, you should change the object type of ticket from string to StringBuilder.
Remember that...
The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
With that in mind, consider the overhead that you are creating in your while loop each time you set your ticket variable. - You mentioned that you have 1 million records, which means that your code is creating 1 million string objects.
Using a StringBuilder type in place of a string type, your code may look like this...
....
StringBuilder ticket = new StringBuilder();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
i++;
if (!reader.IsDBNull(reader.GetOrdinal("r.TICKET")))
{
ticket.Append(reader.GetString(reader.GetOrdinal("r.TICKET")));
// Some process
}
}
}
// Write the ticket content to a file
using(StreamWriter sw = new StreamWriter("ticket.txt"))
{
sw.WriteLine(ticket.ToString());
}
}
A: My experience converting data structure FROM MDB TO ACCDB file format is:
*
*After creating a new accdb file with exactly the same objetcs and data and after compacting it the accdb increases almost 40% file size extra than the old mdb file.
*It is slower. Data process using Query and/or VB code takes AT LEAST 3x more time to reach the end.
*It reaches 2Gb (database size limit) faster than the previous format reaches 1GB.
And I realize that when you compact an accdb file it first generates a mdb file and after rename it for accdb extension. This is really awful!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Java HTTP request message In Java, how can I construct an HTTP request message to get a resource specified by a request URI that a user inputs after I've opened up a socket to connect with a server?
If anyone could just point me to an article with the general tools I would need, that would be cool too. Thank you!
A: You can use Apache HttpClient, in particular HttpGet:
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> handler = new BasicResponseHandler();
responseBody = httpClient.execute(httpGet, handler);
A: The best low-level reference is the HTTP/1.1 Specification, which describes in detail all possible aspects of an HTTP request message.
If you're not actually interested in building the request yourself, the java.net.URL class contains everything you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MySQL insert once for each subquery result I want to execute a MYSQL query:
INSERT INTO taskattempts (taskID) VALUES (_);
which I want to execute multiple times, once for each result of the query:
SELECT id FROM tasks WHERE stageID = 1;
using the resultant id from the second query as the value of taskID in the first.
Is there any way to do this using a single MySQL query? A PHP loop running multiple queries seems dreadfully inefficient.
*EDIT *
I actually need to fill in multiple columns, two static and one with the subquery. I found that INSERT INTO taskattempts (stageAttemptID, taskID, complete) SELECT 0, id, 5 FROM tasks WHERE stageID = 5; works, but wonder whether this is kosher. Also, in the interest of knowledge, can you fill in different columns with different queries?
A: INSERT INTO taskattempts (taskID) SELECT id FROM tasks WHERE stageID = 1;
(This is universally supported standard SQL).
In response to the second part of the question, you can freely mix constants and columns in the SELECT clause:
INSERT INTO taskattempts (stateAttemptID, taskID, complete)
SELECT 0, id, 5 FROM tasks WHERE stageID = 1;
If your constants are strings, don't forget to quote them. And remember, you can include a complex SELECT statement with JOINs and aggregation if required.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Warning: mysqli_error() expects exactly 1 parameter, 0 given error I get the following error
Warning: mysqli_error() expects exactly 1 parameter, 0 given
The problem is with this line of the code:
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
The whole code is
session_start();
require_once "scripts/connect_to_mysql2.php";
//Build Main Navigation menu and gather page data here
$sqlCommand = "SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$menuDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$linklabel = $row["linklabel"];
$menuDisplay .= '<a href="index.php?pid=' . $pid . '">' . $linklabel . '</a><br />';
}
mysqli_free_result($query);
The included file has the following line
$myConnection = mysqli_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql"); with reference to $myConnection, why do I get this error?
A: mysqli_error function requires $myConnection as parameters, that's why you get the warning
A: Change
die (mysqli_error());
to
die('Error: ' . mysqli_error($myConnection));
in the query
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
A: mysqli_error() needs you to pass the connection to the database as a parameter. Documentation here has some helpful examples:
http://php.net/manual/en/mysqli.error.php
Try altering your problem line like so and you should be in good shape:
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error($myConnection));
A: At first, the problem is because you didn't put any parameter for mysqli_error. I can see that it has been solved based on the post here. Most probably, the next problem is caused by the wrong file path for the included file...
Are you sure the following code is in the 'scripts' folder and your main code file is on the same level as the script folder?
$myConnection = mysqli_connect($db_host,$db_username,$db_pass,$db_name) or die ("could not connect to mysql");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: How to have colors in the output of SQL result In SQL Developer can I get the result of a SQL query in color?
For example:
Select * from Employee;
If EmployeeID = 100 I want the name column to be displayed in green color. If EmployeeID = 200 I want the name column to be displayed in red color.
All other fields (gender, salary) should be in normal colors.
The reason I am asking for this:
SELECT * FROM table_A
MINUS
SELECT * FROM table_B;
For this query, I want o/p to be in color for the columns where it is different from table A.
Requirement may see a bit strange. But I just want to know if this can be done.
A: In SQLDeveloper, we use Java swing which allows for some minimal rendering of html. In the grids, this can be done if the value of the cell starts with <html>. This means you could use a case/decode statement to prefix the html tag and a font to change the color of the cells when they are printed.
select
case empno
when 7839 then '<html><font size="5" color="red">'||empno
when 7698 then '<html><font size="5" color="green">'||empno
else empno||''
end empnpo,
ENAME ,
JOB ,
MGR ,
HIREDATE ,
SAL ,
COMM ,
DEPTNO from emp
A: You can use user defined reports as per this blog post by Vadim Tropashko
On the other hand, you can highlight values in the results grid using the standard Edit/Find dialog.
A: CASE
WHEN EMPLOYEEID = 100 THEN 'GREEN'
WHEN EMPLOYEEID = 200 THEN 'RED'
END EMPLOYEEID
should be put after select but before from
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I uninstall xdebug on Debian? I have to use the Zend Optimizer. After 3 days I figured it doesn't get along with xdebug and now I want to uninstall it. How do I do that on Debian?
My server:
PHP 5.2.6-1+lenny9 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 4
2010 03:25:57)
A: I removed the binary (search for xdebug.so) and then removed all
zend_extension= lines from php.ini regarding Xdebug and now everything works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Cookie syntax for django 1.0 I m using the fllowing code to set cookie in django 1.1 But the cookie get deleted every time the page refresh or during post in Ie 7 , Ie 8 and safari.For Firefox and chrome It works fine.
expiry_date=datetime.date.today()+datetime.timedelta(days=1)
resp.set_cookie('appl_keyVal', 40, max_age=24*60*60, expires=expiry_date)
Is the cookie syntax correct for django 1.0?
A: expires should be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT".
https://docs.djangoproject.com/en/1.1/ref/request-response/#django.http.HttpResponse.set_cookie
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Cocos2d-iPhone or Sparrow for first time 2D iOS game development? I've just gotten basic UIKit down. I've made several personal apps and such, but now I'm ready to move on to a game with some other developers. Both of these frameworks look powerful and have tons of bells and whistles.
Does anyone have a preference? Are there pros and cons when compared to each other? They both seem to have similar syntax and performance.
A: while working as a game developer specifically for ios, cocos2d is best suitable.Some of the reason are as:
1.Open source and objective-c language
2.free of cost
3.you learn a lot means u have to compromise with development time.
4.it supports PVRTC texture which reduce memory usage. PVRTC is an image format. When it is loaded into RAM, it consumes less memory at the expense of image quality. PVRTC is not yet supported in the current version of Sparrow.
for sparrow:
it's still inits development phase
It is highly similar to the framework in Flash/Flex. If you are a Actionscript 3 developer, you will be highly familiar with Sparrow.
no support for PVRTC, No integrated Physics engine and particle system.
below is the list of resources which i found as a beginner for development.
You can jump to some of the links
http://www.raywenderlich.com/352/how-to-make-a-simple-iphone-game-with-cocos2d-tutorial
https://github.com/cocos2d/cocos2d-iphone
http://www.iphonedevsdk.com/forum/iphone-sdk-game-development/42419-how-integrate-cocos2d-doxygen-xcode.html
what is chipmunk/physics engine
http://www.alexandre-gomes.com/articles/chipmunk/
list of all frameworks
http://www.tonylea.com/2011/best-iphone-game-frameworks/
http://talkbinary.com/iphone-development/9-game-engines-for-iphone-development/
hope it help u!!
A: I find the Sparrow Framework API to be much cleaner and more consistent than Cocos2D's. You'll also get much better official documentation to get started with Sparrow development, and the developer is very responsive on the forum. Cocos2D's Wiki is quite incomplete and partially out of date, and the forum is so crowded and chatty that it's hard to find the buried gems.
However, Cocos2D is extremely popular and there are way more tutorials available online (check out http://www.raywenderlich.com) and books (like mine: http://www.learn-cocos2d.com/store/book-learn-cocos2d/). You'll also find more developers to ask for help.
Then there's Kobold2D which (but I'm biased) is an exciting alternative to Cocos2D with 15+ example projects, important source code integrated (cocos3d, cocos2d extensions, Lua), the entire API references available online, offline and as Xcode Help, and better cross-platform (iOS & Mac OS) support.
A: The definite answer is cocos2d since it is easy to learn, have a strong community and well documented and more rich in feature comparing to Sparrow. I haven't used Sparrow but i heard it is also easy , but it lacks of active developer and forum. And Cocos2d is achieving more and more attention to developer for 2d game development in iOS. So it's better to use cocos2d.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I build an instance of a Subclass knowing some property value of that subclass I have a hierarchy of so named Attribute classes, that represents single properties of my Domain Model. Each of this Attribute classes has a unique String id property.
I Also have an AttributeFactory that has a method to retrieve instances of Attribute based on id.
public class Attribute {
private String id;
private AttributeType type;
.......
.......
public Attribute(String id){
this.id=id;
}
public void setID(String id){
this.id=id;
}
public String getID(){
return this.id;
}
.......
.......
}
The interface of the Factory looks like
public interface IAttributeFactory {
Attribute getAttributeByID(String id);
}
One implementation of this interface could have for example a HashMap as a repository of all the defined Attributes.
An example of Attribute subclass is:
public class ClientCode extends Attribute {
public ClientCode(){
super("clientCode");
this.setType(AttributeType.CHAR_TYPE);
}
........
........
}
The question is, can we using reflection or any other thing build new instances of subclasses of attributes only knowing the id of that subclasses, so implement the interface defined above, without the need to define the HashMap an add each new defined subclass to the HashMap?
Thank you in advance
Daniel
A: If IDs are arbitrarily chosen by the client code, then it wouldn't be possible to know which ID belongs to which Attribute subclass. However, if you can somehow enforce a pattern, then yes it would be possible to instantiate subclasses by only knowing the ID. You can do that through reflection.
The sample code below how to create a new instance via reflection:
public void createInstanceOfSubclass(String id) {
try {
Class cls = Class.forName(convertIDToClassName(id));
Class parameterTypes[] = new Class[1];
parameterTypes[0] = String.TYPE;
Constructor ct = cls.getConstructor(parameterTypes);
Object arglist[] = new Object[1];
arglist[0] = id;
Object subclassInstance = ct.newInstance(arglist);
}
catch (Throwable e) {
System.err.println(e);
}
}
[It is just sample code; for example the error handling can be improved in the actual implementation.]
Basically, you will have to write the convertIDToClassName(String) method to convert an ID to the class name. Without such association, it wouldn't be possible to link the two.
Another idea is that the ID of an attribute is calculated by you; meaning that the Attribute class sets its own ID field. As a result, you directly link the subclass name and the ID field together. Therefore, it would be possible instantiate subclasses via the ID.
In any case, a personal comment would be avoid reflection and stick to creating the classes in the code (probably take out the instantiation code somewhere like in a factory class, so that your main code gets closed for modification).
A: You need a factory to create an instance of specific subclass of Attribute, right? Let's do this using a typical factory pattern.
//TODO make this a singleton
public final class ClientFactory implements IAttributeFactory {
public static final String CLIENT_CODE = "clientCode"; //TODO use enum
/** This can return a null */
public final Attribute getAttributeByID(String id) { //TODO rename this getter to something like create
if (null == id) return null;
if(id == CLIENT+CODE)
return new ClientCode(CLIENT_CODE);
return null;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regex negative lookbehind in Ruby doesn't seem to work Making an argument parser. I want to split a string into an array where the delimiter is ", " except when preceded by "|". That means string
"foo, ba|, r, arg"
should result in
`["foo", "ba|, r", "arg"]`
I'm trying to use this regex: (?<!\|), which works in http://regexhero.net/tester/ but when I try
args.split(/(?<!\|), /)
in ruby, I get an error: undefined (?...) sequence: /(?<!\|), /
A: Ruby's regex engine doesn't support lookbehind (yet).
You'd need to switch to 1.9 or use Oniguruma.
If that's not an option, you can search for |, and replace it with some sort of marker. After all is said and done, put the |, back.
You can also try a regex like:
/(?:[^|]), /
But obviously the (?:[^|]) is not zero-width, which means you'll need to do some extra work afterwards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to clear django modules caching? When running via local Apache+wsgi got something like:
ImportError at /link/to/new-app
No module named views
/usr/lib/python2.6/dist-packages/django/utils/importlib.py in import_module
35. __import__(name)
/usr/lib/python2.6/dist-packages/site/apps/new-app/urls.py in <module>
2. import views
The views module does exist, you can import it in the python shell, and it runs OK in django dev web server. So I guess it's a caching issue.
Tried to restart Apache, remove all pyc files + touch all files (both in django dir and the code), and even restart the machine, nothing helps.
Django ver: 1.2.4
Any idea?
Thanks
A: Your web server is out of file descriptors. Use ulimit to increase the number available before starting httpd.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cmp and je not working when comparing equal values [Homework disclaimer]
I'm working on the binary bomb lab. Basically, I have to use the objdump of a "bomb" executable to find the right input strings to disarm the "bomb." Currently I've solved 5/7 phases and am working on the 6th phase which contains this assembly:
8048eb0: 39 18 cmp %ebx,(%eax)
8048eb2: 74 05 je 8048eb9 <phase_6+0x49>
8048eb4: e8 d0 0a 00 00 call 8049989 <explode_bomb>
To not explode the bomb, I need to set ebx and eax to same value so that je is called instead of the explode_bomb function. So, I found an input string that gives the same value of ebx and eax. However, when I reach this point in the program's execution, the je isn't called even though ebx and eax are the same value. In GDB:
Good work! On to the next...
134530284
Breakpoint 2, 0x08048e74 in phase_6 ()
Current language: auto; currently asm
(gdb) break *0x8048eb0
Breakpoint 3 at 0x8048eb0
(gdb) c
Continuing.
Breakpoint 3, 0x08048eb0 in phase_6 ()
(gdb) print $ebx
$1 = 134530284
(gdb) print $eax
$2 = 134530284
(gdb) si
0x08048eb2 in phase_6 ()
(gdb) si
0x08048eb4 in phase_6 ()
(gdb) si
0x08049989 in explode_bomb ()
(gdb)
Why is this not working? This is the first time this assignment where this issue has come up.
A: (%eax) is not the same as %eax.
(%eax) means load the value pointed to by eax, not eax itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: inputing hex and reading hex with C++ I'm trying to read and write hex but I'm having trouble inputting hex and reading hex back as hex not ascii. Whats getting me is printing the addresses, and values correctly I'm not quite sure I'm doing it right. any hints as to what I'm doing wrong? ok its working so far now just to fix read to print the actual address instead of entered address +1.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc,char ** argv) {
if(argc <= 1) {
cout<<"Enter a file name please";
exit(0);
} else {
fstream in;
in.open(argv[1],fstream::in | fstream::out | fstream::binary);
string input;
unsigned int v;
unsigned int print;
unsigned int g;
int iter;
for(iter = 0; input!="save";){
cout<<"Hex Edit("<<argv[1]<<"): ";
cin>>input;
if(input == "read"){
cout<<"Enter Offset: ";
cin>>hex>>v;
in.seekg(v);
print=in.get();
g=in.tellg();
cout<<"Value at offset("<<hex<<g<<"): "<<hex<<print;
cout<<endl;
}
if(input == "write"){
cout<<"Enter Offset: ";
cin>>hex>>v;
in.seekp(v);
cout<<"Enter Value: ";
cin>>hex>>v;
in.put(v);
}
} else if(input == "save") {
in.close();
}
cout<<endl;
}
}
return 0;
}
A: You seem to be intending to read and write one character at a time - cin and cout are both capable of working with integral values and this would be ideal here. Keep in mind that hexadecimal strings do represent numbers! Streams are capable of interpreting them as such. Simply changing the variables v and print to type int will allow you to read in an entire hexadecimal value at once.
For an example:
int value;
cin >> hex >> value;
cout << hex << value;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ProgressBar not updating correctly after return to Activity MyBookshelf extends Activity and implements an Interface called by asynchronous download and unzip processes.
The asynchronous download process periodically calls onBookDownloadPercent(float) from the Interface. My Activity definition includes:
public class MyBookshelf extends Activity implements BookDownloadListener {
private ProgressBar mProgress;
// .......
// .......
@Override
public void onBookDownloadPercent(float _percent_finished) {
final float final_percent = _percent_finished;
runOnUiThread(new Runnable() {
public void run()
{
DebugLog.d(TAG, "onBookDownloadPercent " + Float.toString(final_percent));
mProgress.setProgress((int) final_percent);
}
});
}
}
In LogCat, my function DebugLog.d assures me that the UI thread is calling mProgress.setProgress():
09-30 11:37:06.698: DEBUG/MyBookshelf(2069): onBookDownloadPercent 0.0014221431; thread 1
09-30 11:37:07.288: DEBUG/MyBookshelf(2069): onBookDownloadPercent 1.0004596; thread 1
09-30 11:37:07.838: DEBUG/MyBookshelf(2069): onBookDownloadPercent 2.0001705; thread 1
09-30 11:37:08.318: DEBUG/MyBookshelf(2069): onBookDownloadPercent 3.0014038; thread 1
09-30 11:37:09.098: DEBUG/MyBookshelf(2069): onBookDownloadPercent 4.0002813; thread 1
09-30 11:37:09.468: DEBUG/MyBookshelf(2069): onBookDownloadPercent 5.0003366; thread 1
09-30 11:37:09.818: DEBUG/MyBookshelf(2069): onBookDownloadPercent 6.0003924; thread 1
09-30 11:37:10.158: DEBUG/MyBookshelf(2069): onBookDownloadPercent 7.0004926; thread 1
09-30 11:37:10.588: DEBUG/MyBookshelf(2069): onBookDownloadPercent 8.000748; thread 1
09-30 11:37:10.938: DEBUG/MyBookshelf(2069): onBookDownloadPercent 9.000215; thread 1
09-30 11:37:11.368: DEBUG/MyBookshelf(2069): onBookDownloadPercent 10.00017; thread 1
I have a similar Interface for the asynchronous unzip task:
@Override
public void onBookUnzipPercent(float _percent_finished) {
final float final_percent = _percent_finished;
runOnUiThread(new Runnable() {
public void run()
{
DebugLog.d(TAG, "onBookUnzipPercent " + Float.toString(final_percent));
mProgress.setProgress((int) final_percent);
}
});
}
First, MyBookshelf calls the asynchronous task which downloads the first book, and the progress bar updates correctly (0 to 100%).
Second, MyBookshelf calls the asynchronous task which unzips the first book, and the progress bar updates correctly (0 to 100%).
Third, MyBookshelf calls startActivity(nextIntent) to read the book and calls finish() on itself.
Fourth, I come back to MyBookshelf after reading the book:
nextIntent = new Intent(getBaseContext(), MyBookshelf.class);
The Problem occurs when I download the next book: the download occurs, and LogCat logs the updates, but the progress bar is only visible as blank gray and does not update when downloading nor when unzipping the next book. I have confirmed with LogCat that thread 1 is indeed running via the onBookDownloadPerecent Runnable
Do I need to do something interesting to mProgress when coming back to MyBookshelf so it will display when it's updated?
A: My solution was to make mProgressBar static:
public class MyBookshelf extends Activity implements BookDownloadListener {
static private ProgressBar mProgress;
// .......
// .......
@Override
public void onBookDownloadPercent(float _percent_finished) {
final float final_percent = _percent_finished;
runOnUiThread(new Runnable() {
public void run()
{
DebugLog.d(TAG, "onBookDownloadPercent " + Float.toString(final_percent));
mProgress.setProgress((int) final_percent);
}
});
}
}
A: WHy dont you use the finish() when going back to the myBookShelf after reading the book?
It seems everything is ok, but I have a little doubt about this line of code
nextIntent = new Intent(getBaseContext(), MyBookshelf.class);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to do the same feature/function in jquery from mootools //new tmp element that contains the new div
var tmpDiv = new Element('div',{html:'<div id="video"><iframe title="YouTube video player" width="370" height="208" src="'+video+'" frameborder="0" allowfullscreen></iframe></div>'});
//new div (first child of my tmp div) replaces the old 'myDiv' (that can be grabbed from the DOM by $)
tmpDiv.getFirst().replaces($('video'));
$$('.showing').removeClass('showing');
$('thumb-' + id).addClass('showing');
How could I convert this to jquery? I believe it is using the mootools dynamic library.
Thanks,
A: If I am reading this right, I think this is what you are looking for:
$("#video").replaceWith('<div id="video"><iframe title="YouTube video player" width="370" height="208" src="'+video+'" frameborder="0" allowfullscreen></iframe></div>');
$('.showing').removeClass('showing');
$('#thumb-' + id).addClass('showing');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the best approach to dynamically display a single product from the database? I am trying to practice programming and I have decide to place some effect on the login page. Since I am working on an online store I would want to display some random products somewhere in the login page that changes after every few seconds.
Now, I am stuck on how will I be able to extract a single product that will be displayed after an ajax call. I was thinking of getting the minimum and maximum product id on the database then randomly generate a number between the minimum and maximum product id then get the product with that ID but I thought that what if the ID that is randomly generated doesn't match any product. It will just display nothing on the login page for seconds which I don't want to happen.
Is there a way that I can have an ID that will surely be in the product table? Your help will be greatly appreciated. Thanks in advance.
PS:
I am using MySQL and PHP.
UPDATE:
I have came across a page stating that I can use:
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
Will this be a good solution for it?
A: If you are using MSSql you can order by the newId() function to randomly get a row of data. You still need a service/page on the server side to run this code for you.
select top 1 productName, sku
from products
order by newid()
for MySql this would suffice
SELECT productName, sku
FROM products
ORDER BY Rand()
LIMIT 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Passing a List to Python From Command Line I would like to make my python script run from the command line when supplies with some arguments. However, one of the arguments should be a list of options specific to one segment of the script. Would string parsing be the only way to do this by actually constructing the list after the "command line list" string is split from commas? If so, how would you go about that?
Example: -details=['name', 'title', 'address']
A: Yes, argparse is your best bet, and if you want to provide a list of values to one of your named arguments, it looks like this (the nargs parameter is the key to this):
>>> import argparse
>>> arg_parser = argparse.ArgumentParser()
>>> arg_parser.add_argument('--details',
nargs='*',
type=str,
default=[],
help='a list of the details')
# your args on the command line like this example
>>> the_args = arg_parser.parse_args("--details 'name' 'title' 'address'".split())
>>> print the_args.details
["'name'", "'title'", "'address'"])
A: Program:
import sys, ast, getopt, types
def main(argv):
arg_dict={}
switches={'li':list,'di':dict,'tu':tuple}
singles=''.join([x[0]+':' for x in switches])
long_form=[x+'=' for x in switches]
d={x[0]+':':'--'+x for x in switches}
try:
opts, args = getopt.getopt(argv, singles, long_form)
except getopt.GetoptError:
print "bad arg"
sys.exit(2)
for opt, arg in opts:
if opt[1]+':' in d: o=d[opt[1]+':'][2:]
elif opt in d.values(): o=opt[2:]
else: o =''
print opt, arg,o
if o and arg:
arg_dict[o]=ast.literal_eval(arg)
if not o or not isinstance(arg_dict[o], switches[o]):
print opt, arg, " Error: bad arg"
sys.exit(2)
for e in arg_dict:
print e, arg_dict[e], type(arg_dict[e])
if __name__ == '__main__':
main(sys.argv[1:])
Command line:
python py.py --l='[1,2,3,[1,2,3]]' -d "{1:'one',2:'two',3:'three'}" --tu='(1,2,3)'
Output:
args: ['--l=[1,2,3,[1,2,3]]', '-d', "{1:'one',2:'two',3:'three'}", '--tu=(1,2,3)']
tu (1, 2, 3) <type 'tuple'>
di {1: 'one', 2: 'two', 3: 'three'} <type 'dict'>
li [1, 2, 3, [1, 2, 3]] <type 'list'>
This code snippet will take short or long command switches like -l or --li= and parse the text after the switch into a Python data structure like a list, tuple or a dict. The parsed data structure ends up in a dictionary with the long-form switch key.
Using ast.literal_eval is relatively safe. It can only parse python data definitions.
A: argparse is nice for this, it's in the standard library as of 2.7 and 3.2 but otherwise a pip install away.
Your main concern of specifying a variable-length list can be addressed by making the list interpreted as a single argument in the shell by using quotes (could depend on your shell I suppose):
% python prog.py 'name title address' spam
where prog.py contains
import sys
my_list = sys.argv[1].split()
# my_list is ['name', 'title', 'address']
if 'name' in my_list:
do_something()
or similar. Use an argument with split to delimit your list:
% python prog.py "you're a foo, lift the bar"
my_list = [x.strip() for x in sys.argv[1].split(',')]
# my_list is ["you're a foo", "lift the bar"]
But please use argparse instead; especially if you want to use use -c style flags.
One way to interpret your question is:
"I'm already using argparse, since that's the sensible way to interpret command line arguments in Python. How do I specify that some options are within a specific category?"
In your question you've shown an example of something the shells I use of would choke on;
% python prog.py -v -details=['name', 'title', 'address'] --quickly -t 4
wouldn't make it to python to be parsed because they'd use spaces to separate arguments and might use [ and ] as shell syntax.
I suggest the following instead
% python prog.py -v --details name title address --quickly -t 4
where a prog.py file of
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', action='store_true')
parser.add_argument('--details', nargs='*')
parser.add_argument('--quickly', action='store_true')
parser.add_argument('-t')
args = parser.parse_args()
#args is Namespace(details=['asdf', 'a', 'a'], quickly=False, t='4', v=True)
details = args.details
#details is ['asdf', 'a', 'a']
Now, as per your question, you didn't have to do the string parsing yourself.
A: I really like the-wolf's approach using variable length collections as explicit string arguments.
In my opinion, nargs='*' has noteworthy drawbacks: when attempting to collect strings as positional arguments (at least one string must be present), or if you are trying to use subparsers, you will find that nargs='*' and nargs='+' use greedy completion, and they don't seem to stop consuming for any good reasons. Even if syntax for an optional argument or a number comes up, the string() type will keep consuming. (This gets harder to anticipate with subparsers).
Best case, arguments placed after (positional and optional) are being ignored, and worse, you are likely passing corrupt data types to the argparse array.
We should be able to define a custom ActionType that is looking for a quoted string. If it finds one, then we adapt the-wolf's examples (nearly verbatim it seems).
This keep things clean in argparse and makes general use of variable collections much less bitchy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: Why some ARM instructions do not use barrel shifter? I am curious about why there are some ARM instuctions (like MUL and QADD) does not use barrel shifter. I would like to know the rational behind the limit. Thanks!
A: It's not that the barrel shifter isn't used; it's that you aren't able to specify how it's used in all but very specific instructions (data processing and load/store). If you look at the instruction encoding you'll see that there is just no room to specify it.
In the case of instructions like MUL or SWP, they were not in the first version of the architecture. They were squeezed into the instruction set by making use of otherwise invalid combinations of values for the specification of the barrel shifter. Since the barrel shifter specification bits had to be repurposed for storing things like what instruction to execute and what register to use as the multiplier, there was simply no way to specify how much to shift/rotate the operand.
A: A barrel shifter is used for fast shifting.
As you know if you multiply a number with another number which is a power of two then you just have to shift it left. In these kind of special situations you can use a shift register. But in general multiplications its efficient to follow normal multiplier designs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Rakismet duplicate posts not being flagged as spam? I'm currently using the Rakismet gem for anti spam in my app and it's doing a great job filtering out certain buzz words like "viagra" and "porn", but it's not flagging duplicate comments no matter how many times I submit them.
My Post model has the line "include Rakismet::Model" and it's getting info from the author_email and content db columns. How can I get this to work? Code examples would be greatly appreciated. Ideally I'd like to filter the comment even if they change a few characters. Thanks!
Edit
I was able to solve exact duplicates with the following in my create action, but I'd still like to solve the problem of few character changes (where it would not be an exact duplicate and therefore still be posted)
if @post.spam? == true
redirect_to :back
return
else
if current_user.posts.last.content == @post.content
redirect_to :back
return
else
@post.save
redirect_to :back
return
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Unable to parse JSON with jQuery, returning [object Object] I suspect my problem is due to the structure of my JSON string. It seem to have a JSON object within a JSON object.
This is the format of my JSON:
[
{"subject":{"title":"java","id":"1","desc":"Basic java programming"},
{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}
}
This is my jquery code:
var items = [];
$.getJSON('theurl', function(data) {
$.each(data, function(key, subject) {
alert(subject); //returning me "[object Object]"
$('#tempresult').append('<p>'+ subject +'</p>'); //returning me "[object Object]"
});
});
A: You have posted some malformed JSON. I'm going on the assumption that your elements are closed properly as:
[
{"subject":{"title":"java","id":"1","desc":"Basic java programming"}},
{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}}
]
It looks like you want $('#tempresult').append('<p>'+ subject.subject.desc +'</p>');
data[0] is this object:
{"subject":{"title":"java","id":"1","desc":"Basic java programming"}}
data[1] is this object:
{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}}
data[0].subject is this object:
{"title":"java","id":"1","desc":"Basic java programming"}
data[0].subject.desc is this:
"Basic java programming"
A: Your example JSON is a bit poorly formed (missing a }).
Otherwise, try this:
$.each(data, function(key, subject) {
alert(subject.subject.title);
});
http://jsfiddle.net/7xMJP/
A: Your subject variable is a json object.
You have to specify the subject properties to get the value
alert(subject.subject.id);
alert(subject.subject.title);
Alert(subject.subject.desc);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replace iteration's fetch to BULK COLLECT There is an object type and table consists of that objects.
So here we go:
create or replace type lpu.someobj_o as object
(
name VARCHAR2(75),
enroll_date DATE,
id NUMBER(12)
)
CREATE OR REPLACE TYPE lpu."SOMEOBJ_T" IS TABLE OF someobj_o;
There's also PL/SQL function that works in common ETL principle. Here is piece of code function:
for some_cursor_rec in some_cursor(startTime, recordInterval) loop
open some_cur2(some_cursor_rec.name, some_cursor_rec.id);
fetch some_cur2 into some_cursor_rec2;
if some_cur2%rowcount > 0 then
loop
pipe row (
lpu.someobj_o(
id => some_cursor_rec2.id,
name => some_cursor_rec2.name,
enroll_date => some_cursor_rec2.enroll_date
)
);
fetch some_cur2 into some_cursor_rec2;
exit when some_cur2%notfound;
end loop;
end if;
close some_cur2;
end loop;
Ok, so the issue is small performance. How can I increase speed of completing of this function? I have read that BULK COLLECT should improve performance. But how can I use it in my case? I have tried BULK COLLECT but it gave me error that type of collection is wrong.
Thanks in advance! Really hope for your help!
A: If performance is your concern, then you should start looking at combining your two cursors.
Current you are executing the query in the some_cursor once, and you are executing the query in cursor some_cur2 as many times as there are rows selected in the first query. And that's highly likely your performance bottleneck.
If you combine the two queries to one query and do a cursor for loop (which executes the query only once), then you'll automatically be bulk fetching 100 rows at a time, so there probably won't be a real need to manually convert it to do bulk fetching.
Regards,
Rob.
A: Here is a basic example how to use bulk collect into with an object type.
create or replace type someobj_o as object
(
name varchar2(75),
enroll_date date,
id number(12)
);
/
create or replace type someobj_t is table of someobj_o;
/
create table someobj_table of someobj_o;
insert into someobj_table values(someobj_o('Joe', current_date, 100));
insert into someobj_table values(someobj_o('Jack', current_date, 101));
insert into someobj_table values(someobj_o('John', current_date, 102));
declare
v_objs someobj_t;
begin
select someobj_o(name, enroll_date, id)
bulk collect into v_objs
from someobj_table;
dbms_output.put_line('number of objects in a collection = ' || v_objs.count);
end;
/
Update
The same than above with a cursor:
declare
type objcur_t is ref cursor;
v_objcur objcur_t;
v_objs someobj_t;
begin
open v_objcur for
select someobj_o(name, enroll_date, id)
from someobj_table;
fetch v_objcur bulk collect into v_objs;
close v_objcur;
dbms_output.put_line('number of objects in a collection = ' || v_objs.count);
end;
/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Constant item width in horizontal ItemControl I need a horizontally-organized ItemsControl that constrains all of its items to the same width. The items I'm using are UserControls and builds an auto-sized TextBlock showing an int value (contained in a dependency property) with a Border around it. The trouble is that smaller values result in a narrower item, and I need all of the items to be the same. I've considered a few solutions, but I can't seem to make any work.
The first is by setting the ItemsPanel template to a Grid. This way I can use the code-behind to generate the number of columns required based on the data source and set all of the column widths to *. The puzzle was figuring out how to set the grid column attached property for each item.
The second solution is by setting the ItemsPanel template to a StackPanel. This automatically arranges the items correctly, but I can't set the width of each item to that of the widest item.
The last solution is by setting the ItemsPanel template to a UniformGrid with code-behind to set the number of columns whenever the data source changes. This would automatically arrange the items correctly and provide uniform width. My problem here is that I can't get any items to show at all. I've tried manually adding buttons, and they show fine. My UserControl won't appear. I've listed this solution below.
<Window x:Class="Learning_WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Learning_WPF"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="DateTape" Height="176" Width="500">
<Window.Resources>
<my:DateList x:Key="dateList" CollectionChanged="DateList_CollectionChanged" />
</Window.Resources>
<ItemsControl x:Name="itemsControl1" ItemsSource="{Binding Source={StaticResource dateList}, Path=/}" Grid.Row="1">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid x:Name="daysGrid" Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Window>
public partial class MainWindow : Window
{
UniformGrid daysGrid;
DateList dateList;
public MainWindow()
{
InitializeComponent();
daysGrid = (UniformGrid)itemsControl1.ItemsPanel.LoadContent();
dateList = (DateList)FindResource("dateList");
dateList.Fill(DateTime.Today, DateTime.Today.AddDays(10));
}
private void DateList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
daysGrid.Columns = dateList.Count;
}
}
public class DateList : ObservableCollection<Date>
{
public void Fill(DateTime first, DateTime last)
{
// implementation fills the array with all of the days between first and last, inclusively
}
}
Maybe there's a better way to do what I want to achieve (perhaps a bit more graphically than with controls)...
A: If the UniformGrid won't cut it for your solution, you can always try to get by with setting the ItemContainerStyle for the ItemsControl (assuming you can use a ListBox with ListBoxItem children), like so:
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ContentPresenter Width="75" ... />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
A: I finally got it to work using a Grid. I had to do some significant code-behind and the interface is noticeably sluggish due to the triple layout, but it works. Suggestions on improving this are welcome. When inserting this control into a window, change the StartDate property from its default value BEFORE the EndDate property; otherwise the VS will lock up.
XAML
<UserControl x:Class="MyProject.DateTape"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:my="clr-namespace:MyProject"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
d:DesignHeight="45" d:DesignWidth="188">
<UserControl.Resources>
<Thickness x:Key="bottomThickness" Bottom="1" Top="1" Left="0.5" Right="0.5" />
<Thickness x:Key="topThickness" Bottom="0" Top="1" Left="0.5" Right="0.5" />
<Style TargetType="Border">
<Setter Property="BorderBrush" Value="#FFBEBEBE"/>
</Style>
<Style TargetType="TextBlock">
<Setter Property="TextAlignment" Value="Center"/>
<Setter Property="Margin" Value="6,0"/>
</Style>
</UserControl.Resources>
<Grid x:Name="mainGrid"/>
</UserControl>
C#
public partial class DateTape : UserControl
{
public static readonly DependencyProperty StartDateProperty =
DependencyProperty.Register("StartDate", typeof(DateTime), typeof(DateTape),
new PropertyMetadata(new PropertyChangedCallback(OnDatesChanged)));
public static readonly DependencyProperty EndDateProperty =
DependencyProperty.Register("EndDate", typeof(DateTime), typeof(DateTape),
new PropertyMetadata(new PropertyChangedCallback(OnDatesChanged)));
[Category("Common"),
TypeConverter(typeof(DateConverter))]
public DateTime StartDate
{
get { return (DateTime)GetValue(StartDateProperty); }
set { SetValue(StartDateProperty, value); }
}
[Category("Common"),
TypeConverter(typeof(DateConverter))]
public DateTime EndDate
{
get { return (DateTime)GetValue(EndDateProperty); }
set { SetValue(EndDateProperty, value); }
}
public DateTape()
{
InitializeComponent();
}
private void Layout()
{
int dayCount = (EndDate - StartDate).Days;
double max = 0;
DateTime current = StartDate;
ColumnDefinition columnDefinition;
Border border;
TextBlock textBlock;
Binding binding;
Size infinity = new Size(double.PositiveInfinity, double.PositiveInfinity);
Thickness bottomThickness = (Thickness)Resources["bottomThickness"],
topThickness = (Thickness)Resources["topThickness"];
mainGrid.ColumnDefinitions.Clear();
for (int i = 0; i <= dayCount; i++, current += TimeSpan.FromDays(1))
{
mainGrid.ColumnDefinitions.Add(columnDefinition = new ColumnDefinition());
// Add a day
border = new Border();
textBlock = new TextBlock();
textBlock.Text = current.Day.ToString();
border.Child = textBlock;
binding = new Binding();
binding.Source = bottomThickness;
border.SetBinding(Border.BorderThicknessProperty, binding);
mainGrid.Children.Add(border);
border.Measure(infinity);
max = Math.Max(max, border.DesiredSize.Width);
Grid.SetRow(border, 2);
Grid.SetColumn(border, i);
}
foreach (ColumnDefinition cd in mainGrid.ColumnDefinitions)
{
cd.MinWidth = max;
}
}
private static void OnDatesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
(d as DateTape).Layout();
}
Edit:
I found a way to do it without using multiple layout passes by querying the DesiredSize of each Border item as I add them to the Grid and keeping track of the maximum width.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to assure that websocket was opened from my webpage So, the question is:
Is there a way to be sure that the client who is trying to connect to my websocket server, is doing this from the webpage that I provide, and not from any other page, or script?
A: A malicious user/program can connect to this websocket and there is nothing you can do about it (Period end of story). However, the same-origin policy for WebSockets should be very similar to that of XHR. JavaScript on another domain cannot access a WebSocket on your domain unless you explicitly allow it. So this means if someone where to redistribute your content, they would have to use a cross-domain proxy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQUERY, Dynamically text box id assign to focusout function $(document).ready(function(){
var CurrentTextBoxID = "";
var shifton = false;
var IsCapsLockOn = false;
// toggles the keyboard to show or hide when link is clicked
$(":text").focus(function(e) {
CurrentTextBoxID = this.id;
var top = ($(window).height() - $('#keyboard').height()) - 25;
var left = ($(window).width() - $('#keyboard').width()) / 2;
alert(CurrentTextBoxID + " focus In");
$('#keyboard').css(
{
"left": left+"px",
"top": top+"px"
}
).toggle();
});
$('#'+CurrentTextBoxID).blur(function() {
alert("**");
});
$('#'+CurrentTextBoxID).focusout(function() {
alert(this.id + " focus out");
});
At this upper code, blur function and focusout function did not work.
When I change code like that it work.
$('#txtTest1').blur(function() {
alert("**");
});
$('#txtTest1').focusout(function() {
alert(this.id + " focus out");
});
But by changing code like that, I cannot give text box ID dynamically.
So, Please let me know how could i make like that.
$( DYNAMIC ID ).focusout(function() { .... });
A: Move the blur() and focusout() inside focus() where CurrentTextBoxID is defined.
This seems kind of hacky to me.
The best thing to do would be to bind the event to the textbox when its added dynamically. I would use live() way of binding your events in this case. The below would work but it binds and event everytime the textbox gets focus.
CurrentTextBoxID is undefined the way you are doing it, you could do this but better examples follow.
$(":text").focus(function(e) {
CurrentTextBoxID = this.id;
var top = ($(window).height() - $('#keyboard').height()) - 25;
var left = ($(window).width() - $('#keyboard').width()) / 2;
alert(CurrentTextBoxID + " focus In");
$('#keyboard').css(
{
"left": left+"px",
"top": top+"px"
}
).toggle();
$('#'+CurrentTextBoxID).blur(function() {
alert("**");
});
$('#'+CurrentTextBoxID).focusout(function() {
alert(this.id + " focus out");
});
});
Alternatively you could use live() to bind the textboxes
$('.dynamicTextBox').live('blur', function(){
alert("**");
});
Or even...
$(':text').blur(function(){
alert("**" + $(this).attr('id'));
});
$(':text').focusout(function(){
alert("**" + $(this).attr('id'));
});
A: As I feel you need to bind those blur and focusout function for all text boxes. If you do it one by one in focus (as in the answer of @Gabe)function you will be binding that function again when some next focus event happens.
I think you need to do like this,
$(":text").blur(function() {
alert("**");
var element=$(this); // you can get the element here
});
$(":text").focusout(function() {
alert(this.id + " focus out");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "???" symbols when saving unicode files in C# I'm having some issues, when saving configuration - unicode text is saved as "???". But problem appears only on Windows 2003 with .Net Framework v 2 . When I test my code on WinXP with .Net 4 it works fine, despite it's targeted on .Net Framework v2 in settings.
I tried doing different conversions like
Encoding.ASCII.GetString(
Encoding.Convert(Encoding.ASCII,
Encoding.Unicode,
Encoding.Unicode.GetBytes(backupPathTextBox.Text)));
But it always return "???" or some unreadable symbols. I googled this question and found out that all C# strings represented in UTF16 codepage, but there is no UTF16 decoder buitl-in in C#.
Could anyone guide me to the right direction?
A: Encoding.ASCII.GetString(
Encoding.Convert(Encoding.ASCII,
Encoding.Unicode,
Encoding.Unicode.GetBytes(backupPathTextBox.Text)));
Encoding.Unicode is actually the UTF-16LE encoding, where each code unit is stored using two bytes (and so ASCII characters end up with zero bytes between each one). Microsoft call this “Unicode” because it's what they expected to be used as the most common encoding of Unicode back in the very early days, but it didn't work out like that and now the name is completely misleading.
What your code does is:
*
*converts your text string to UTF-16LE bytes;
*then converts them from ASCII bytes (which they're not) to UTF-16LE bytes, which means an extra zero byte is added between each byte;
*then converts those bytes back to a string as if they were ASCII, which means you'll get basically the same string as you had to begin with, but with three more zero bytes per one character, and non-ASCII characters turned into two.
What exactly were you trying to do with this? If you want to put Unicode string in an ASCII-compatible text file, the encoding you want is generally UTF-8 and never UTF-16. Converting a string to UTF-8 bytes is as simple as:
new UTF8Encoding(false).GetBytes(backupPathTextBox.Text)
or just use a UTF-8 TextWriter to write the string directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Firebird SQL: StoredProc return null instead of assigned values I have a Firebird StoredProc run from a trigger before Insert and before update and also return 3 values. Those 3 values update 3 fields directly in the same table
I put a check at the SP beginning if the check is true I want to skip that SP so I used "suspend" and "Exit" but when I did that I found the 3 fields updates with null value. why is that ?
The trigger:
CREATE OR ALTER trigger trig1 for table1
active before insert or update position 2
AS
begin
execute procedure my_proc1 new.f1, new.f2
RETURNING_VALUES new.f3, new.f4, new.f5;
end
the StoredProc (it is very big I put only first lines):
begin
if (COALESCE(Param1,0) = 1) then begin
output1 = 0;
output2 = 0;
output3 = 0;
exit;
end
Even if I removed the IF block and kept everything else I dont get zeros in the 3 fields but NULL !!!. Please advise
Thanks
A: As you haven't posted enough of the stored procedure, it is hard to tell, but it looks like you're mixing selectable and executable procedures which is not recommended. Ie if you call the SP via EXECUTE PROCEDURE you should not have SUSPEND in it, if you have, then call it via SELECT ... FROM SP. FireBird is stricter in that regard in recent versions, althought I think it doesn't raise exception if you use "wrong calling mechanism"...
Anyway, if you call EXIT in selectable SP then it sets SQLCODE to 100 (end of record stream), IOW it doesn't set output values. So my suggestion is that you "clean up" your SP, either make it selectable (have SUSPEND in places where you want to return values and call it via SELECT statement) or make it executable (get rid of SUSPEND statements in it and call it via EXECUTE).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Distinct DateTime field without Time in HQL I'm trying to select Distinct DateTime field in HQL.
select distinct CreatedDate from ClaimFile order by CreatedDate DESC
Any Idea how can I get distinct dates without time. right now it can't be distinct with time.
Thanks
A: I can only think of a couple of options:
*
*Register a CustomSQLFunction in your dialect and use that to format
the DateTime into a Date.
*Create a ComputedColumn (sql server) which just strips off the Time. Add it to the mapping as a read only and use that.
*Just fall back to plain SQL since you only seem to need a list of Dates and not objects.
*Use a formula in a property mapping. Property Mapping Element Explained
<property name="CreateDate" formula="cast(convert(varchar(10),CreateDate,103) as datetime)" />.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Format CURRENT_TIMESTAMP to AM & PM Today im working with PHP and MySQL and i store Dates in an Timestamp Field into MySQL, But by default is in 24/h Format, If anyone Know how can i Determine this hour to AM or PM Example:
14:05 -> 2:05PM
02:05 -> 2:05AM
Many Thanks for your time.
A: You can use DATE_FORMAT()
SELECT DATE_FORMAT(hour_column, '%r');
A: No, no, no. A "timestamp" value might mean "11:00am" (if you're in New York), but the SAME value would ALSO mean "4:00pm" (if you're in Greenwich, England).
A timestamp VALUE is independent of the TIME ZONE you're located in.
Having said that, you want to convert a date time STRING (in 24/h format), into a DIFFERENT date time string (convert to 12/meridian format).
Easily done from either MySQL or PHP: whichever you prefer.
Here are the PHP date/time format functions and corresponding format strings:
http://php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/datetime.formats.time.php
And here are the MySQL reference pages:
http://dev.mysql.com/doc/refman/5.5/en/datetime.html
http://www.w3schools.com/sql/func_date_format.asp
A: DateTime would be your friend.
First, if your php config dosen't already set it up for you, set your default timezone by:
date_default_timezone_set('XXXX');
XXXX stand for a value out of the List of supported timezones
initialize your date by:
$date = new DateTime();
To get your timestamp you can use now:
$timestamp = $date->getTimestamp();
As earlier said the output (format) depends on your timezone. You set your default timezone earlier but you can change it all the time, as you need.
To format the date you can use this:
$12h = $date->format( 'h:i:s a' );
$24h = $date->format( 'H:i:s a' );
To read more about DateTime look at the DateTime class manual.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can't stop a service started with alarmManager I'm having problems to cancel an alarm and a service started with it.
I set the alarm in a activity:
public class AlarmStarter extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent locationPollerIntent = new Intent(this, LocationPoller.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(getApplicationContext(), REQUEST_CODE, locationPollerIntent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 6000, pendingIntent);
}
}
The LocationPoller intent will start a service to obtain the location of the device.
So I use an alarmManager to repeat this search in certain frequency.
After that when I get my location on a BroadcastReceiver, I call another Activity to show the location and fire a notification.
At this time, I would like to stop searching for the location.
So I try to cancel the alarmManager.
public class Notifier extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_notifier);
findViewById(R.id.btTurnOffAlarm).
setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intentToStop = new Intent(this, LocationPoller.class);
PendingIntent pendingIntentToStop = PendingIntent.getBroadcast
(getApplicationContext(), REQUEST_CODE, intentToStop, 0);
AlarmManager alarmManager = (AlarmManager)
getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntentToStop);
}
});
}
}
But this is not working, it continues to search for the location.
Any clues?
Thanks.
A: You have to make the intent unique.
sth similar to:
locationPollerIntent.setData((Uri.parse("YOUR UNIQUE ID FOR THIS INTENT")));
AlarmManager will check the data field of an intent when getting back the right alarm for you.
just set a unique Uri to the data of the intent.
so when you get back your alarm, do sth like:
intentToStop.setData((Uri.parse("YOUR SAME UNIQUE ID FOR THIS INTENT")));
the alarm should be cancelled after.
A: REQUEST_CODE needs to be the same in both places; you do not show where that is defined in your code listings.
Also, you do not need getApplicationContext() here -- this will work just fine.
A: You have to pass the same instance.
public static final Uri MYURI = Uri.parse("Some_Uri");
[...]
locationPollerIntent.setData(MyClass.MYURI);
[...]
intentToStop.setData(MyClass.MYURI);
If you have two different references each time you create the Intent, it won't work.
More detailed example here:
http://malubu.wordpress.com/2012/06/05/take-your-time-widgets-and-alarmmanager/
A: I had the same issue, its not about having the same instance of the Intent "locationPollerIntent" and "intentToStop" but you must have the same instance for the PendingIntent.
After stoping the AlarmManager, the service stops too.
static PendingIntent instance;
public static PendingIntent getInstance(Context context) {
if (instance == null)
{
Intent intent = new Intent(context, LocationPoller.class);
instance = PendingIntent.getService(context, REQUEST_CODE, intent, 0);
}
return instance;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to clone an instance of oneself , like Chromium does? When i launch chromium again when it's already started , i can see the following:
%> chromium-browser
Created new window in existing browser session.
Is there any general way in C++ to do a similar thing ? Or is it like just "new" function in C++ , simply clone another object ? I'm confused.
A: It is nothing at all like "new" in C++: it's at a vastly higher level. When the new process is started, it looks for an existing process, and if it finds one, it sends it a command to create a new window, then exits. The syntax and nature of that command is specific to the application (or application framework), as is the mechanism by which an existing instance is found.
A: One way could be to use fork() system call to create a new process identical to the parent process. The new process would have a different process id(PID). In the case of Chrome browser also, if you look at task manager (Windows) or the output of 'ps' command (Linux), you can see that once you open a new tab, it is a new process with new PID.
The following link would be useful for understanding fork()
http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android (get current speed) after getting my distance (using GPS, lat and long), is there any method that I can also get my current speed (using distance and time) , accelerometer are not advised. Thank you :)
A: Given a start position and an end position and time dt which is the time it took to move between the two positions:
float[] distance = new float[2];
Location.distanceBetween(startLatitude, startLongitude,
endLatitude, endLongitude, vectorDistance);
float speed = distance[0]/dt;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Clustered vs Non-Clustered My lower level knowledge of SQL (Server 2008) is limited, and is now being challanged by our DBAs. Let me explain (I have mentioned obvious statements in the hope that I am right, but if you see something wrong, please tell me) the scenario:
We have a table which holds 'Court Orders' for people. When I created the table, (Name: CourtOrder), I created it like:
CREATE TABLE dbo.CourtOrder
(
CourtOrderID INT NOT NULL IDENTITY(1,1), (Primary Key)
PersonId INT NOT NULL,
+ around 20 other fields of different types.
)
I then applied a non-clustered index to the primary key (for efficiency). My reasons is that it is a unique field (primary key), and should be indexed, mainly for selection purposes, as we often Select from table where primary key = ...
I then applied a CLUSTERED index on PersonId. The reason was to group orders for a particular person physically, as the vast majority of work is getting orders for a person. So, select from mytable where personId = ...
I have been pulled up on this now. I have been told that we should put the clustered index on the primary key, and the normal index on the personId. That seems very strange to me. First off, why would you put a clustered index on a unique column? what is it clustering? Surely that's a waste of the clustered index? I'd have believed a normal index would be used on a unique column. Also, clustering the index would mean we can't cluster a different column (One per table, right?).
The reasoning for me being told I have made a mistake is that they believe putting a clustered index on the PersonId would make inserts slow. For the 5% gain in speed of a select, we would be getting a 95% degradation in speed on inserts and updates. Is that correct and valid?
They say that because we cluster the personId, SQL Server has to rearrange data when ever we insert or make a change to the PersonId.
So then I have asked, why would SQL have the concept of a CLUSTERED INDEX, if it's so slow? Is it as slow as they're saying? How should I have setup my indexes to achieve optimum performance? I'd have thought SELECT is used more than INSERT... but they say that we're having locking issues on INSERTS...
Hope someone can help me.
A: Some authors do suggest not "wasting" the CI on an identity column if there is an alternative that would benefit range queries.
From MSDN Clustered Index Design Guidelines the key should be chosen according to the following criteria
*
*Can be used for frequently used queries.
*Provide a high degree of uniqueness.
*Can be used in range queries.
Your CourtOrderID column meets 2. Your PersonId meets 1 and 3. As most rows will end up with the uniqueifier added anyway you might as well just declare it as unique and use PersonId,CourtOrderID as this will be the same width but be more useful as the clustered index key is added to all NCIs as the row locator and this will allow them to cover more queries.
The main issue with using PersonId,CourtOrderID as the CI is that logical fragmentation will likely ensue (and this particularly affects the range queries you are trying to help) so you would need to monitor fill factor, and fragmentation levels and perform index maintenance more often.
A: It's explained in the following link: https://msdn.microsoft.com/en-us/ms190457.aspx
Clustered
*
*Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
*The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
Nonclustered
*
*Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
*The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
*You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, 900 bytes and 16 key columns, and execute fully covered, indexed, queries.
A: I am by no means a SQL Expert...so take this as a developer's view rather than a DBA view..
Inserts on clustered (physically ordered) indexes that aren't in sequential order cause extra work for inserts/updates. Also, if you have many inserts happening at once and they are all occurring in the same location, you end up with contention. Your specific performance varies based on your data and how you access it. The general rule of thumb is to build your clustered index on the most unique narrow value in your table (typically the PK)
I'm assuming your PersonId won't be changing, so Updates don't come into play here. But consider a snapshot of a few rows with PersonId of
1
2
3
3
4
5
6
7
8
8
Now insert 20 new rows for PersonId of 3. First, since this is not a unique key, the server adds some extra bytes to your value (behind the scenes) to make it unique (which also adds extra space) and then the location where these will reside has to be altered. Compare that to inserting an auto-incrementing PK where the inserts happen at the end. The non technical explanation would likely come down to this: there is less 'leaf-shuffling' work to do if it's naturally progressing higher values at the end of the table versus reworking location of the existing items at that location while inserting your items.
Now, if you are having issues with Inserts then you are likely inserting a bunch of the same (or similar) PersonId values at once which is causing this extra work in various places throughout the table and the fragmentation is killing you. The downside of switching to the PK being clustered in your case, is if you are having insert issues today on PersonIds that vary in value spread throughout the table, if you switch your clustered index to the PK and all of the inserts now happen in one location then your problem may actually get worse due to increased contention concentration. (On the flip side, if your inserts today are not spread out all over, but are all typically bunched in similar areas, then your problem will likely ease by switching your clustered index away from PersonId to your PK because you'll be minimizing the fragmentation.)
Your performance problems should be analyzed to your unique situation and take these types of answers as general guidelines only. Your best bet is to rely on a DBA that can validate exactly where your problems lie. It sounds like you have resource contention issues that may be beyond a simple index tweak. This could be a symptom of a much larger problem. (Likely design issues...otherwise resource limitations.)
In any case, good luck!
A: The distinction between a clustered vs. non-clustered index is that the clustered index determines the physical order of the rows in the database. In other words, applying the clustered index to PersonId means that the rows will be physically sorted by PersonId in the table, allowing an index search on this to go straight to the row (rather than a non-clustered index, which would direct you to the row's location, adding an extra step).
That said, it's unusual for the primary key not to be the clustered index, but not unheard of. The issue with your scenario is actually the opposite of what you're assuming: you want unique values in a clustered index, not duplicates. Because the clustered index determines the physical order of the row, if the index is on a non-unique column, then the server has to add a background value to rows who have a duplicate key value (in your case, any rows with the same PersonId) so that the combined value (key + background value) is unique.
The only thing I would suggest is not using a surrogate key (your CourtOrderId) column as the primary key, but instead use a compound primary key of the PersonId and some other uniquely-identifying column or set of columns. If that's not possible (or not practical), though, then put the clustered index on CourtOrderId.
A: Some db with some nasty selects, joins in a stored procedure - only diffrence is the index
INDEXES - clustered vs nonclustered
891 rows
10 sec
NONCLUSTERED
OR
891 rows
14 sec
CLUSTERED
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "100"
}
|
Q: Eclipse + Java - SplashWindow I would like develop a basic application with splashWindow.
this should stay for 5 seconds, when user press any key, the time is need reset, and redefine the time() for 5 seconds again.
If user dont press any key, the splashWindow close.
public class SplashWindow extends JWindow implements WindowListener, KeyListener
{
private Container c;
SplashWindow()
{
frase1.setText("test");
Font font12 = new Font ("Courier New", Font.BOLD, 18);
frase1.setFont(font12);
frase1.setForeground(Color.WHITE);
frase2.setText("test2");
frase2.setFont(font12);
frase2.setForeground(Color.WHITE);
}
public void open( int tempo )
{
c = getContentPane();
c.setLayout(null);
c.setBackground(Color.black);
Insets in = Toolkit.getDefaultToolkit().getScreenInsets(this.getGraphicsConfiguration());
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int width = d.width-(in.left + in.top);
int height = d.height-(in.top + in.bottom);
this.setSize(width,height);
this.setLocation(in.left,in.top);
BorderLayout layout = new BorderLayout();
c.setLayout(layout);
c.add(BorderLayout.CENTER, frase1);
c.add(BorderLayout.PAGE_END, frase2);
frase1.setHorizontalAlignment(SwingConstants.CENTER);
frase2.setHorizontalAlignment(SwingConstants.CENTER);
this.setVisible( true );
this.addKeyListener(this);
sleep( tempo );
}
/**
* Aguarda um tempo em milisegundos
* @param tempo int que representa o tempo, em milisegundos, que ser�aguardado.
* @exception InterruptedException
* @exception Exception
* @return void
*/
private void sleep( int tempo )
{
try {
Thread.sleep( tempo );
}
catch( InterruptedException ie ) {
ie.printStackTrace();
JOptionPane.showMessageDialog( null, " Erro 00 - Falha no sleep do Splash ", " Erro ", JOptionPane.ERROR_MESSAGE );
}
catch( Exception e ) {
e.printStackTrace();
JOptionPane.showMessageDialog( null, " Erro 00 - Falha no sleep do Splash ", " Erro ", JOptionPane.ERROR_MESSAGE );
}
}
/**
* Fecha a janela de splash
* @return void
*/
public void close()
{
dispose();
}
/**
* @param windowevent
* @return void
*/
public void windowOpened( WindowEvent windowevent )
{
Graphics2D graphics2d = (Graphics2D)getGlassPane().getGraphics();
graphics2d.setColor( new Color( 51, 102, 153 ) );
graphics2d.setFont( new Font( "SansSerif", 0, 16 ) );
}
/**
* @param windowevent
* @return void
*/
public void windowActivated( WindowEvent windowevent )
{
}
/**
* @param windowevent
* @return coid
*/
public void windowClosed( WindowEvent windowevent )
{
}
/**
* @param windowevent
* @return void
*/
public void windowClosing( WindowEvent windowevent )
{
}
/**
* @param windowevent
* @return void
*/
public void windowDeactivated( WindowEvent windowevent )
{
}
/**
* @param windowevent
* @return void
*/
public void windowDeiconified( WindowEvent windowevent )
{
}
/**
* @param windowevent
* @return void
*/
public void windowIconified( WindowEvent windowevent )
{
}
}
A: Use SplashScreen Functionality. Here is a tutorial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python: Optimal algorithm to avoid downloading unchanged pages while crawling I am writing a crawler which regularly inspects a list of news websites for new articles.
I have read about different approaches for avoiding unnecessary pages downloads, basically identified 5 header elements that could be useful to determine if the page has changed or not:
*
*HTTP Status
*ETAG
*Last_modified (to combine with If-Modified-Since request)
*Expires
*Content-Length.
The excellent FeedParser.org seems to implement some of these approaches.
I am looking for an optimal code in Python (or any similar language) that makes this kind of decision.
Keep in mind that header info is always provided by the server.
That could be something like :
def shouldDonwload(url,prev_etag,prev_lastmod,prev_expires, prev_content_length):
#retrieve the headers, do the magic here and return the decision
return decision
A: The only thing you need to check before making the request is Expires. If-Modified-Since is not something the server sends you, but something you send the server.
What you want to do is an HTTP GET with an If-Modified-Since header indicating when you last retrieved the resource. If you get back status code 304 rather than the usual 200, the resource has not been modified since then, and you should use your stored copy (a new copy will not be sent).
Additionally, you should retain the Expires header from the last time you retrieved the document, and not issue the GET at all if your stored copy of the document has not expired.
Translating this into Python is left as an exercise, but it should be straightforward to add an If-Modified-Since header to a request, to store the Expires header from the response, and to check the status code from the response.
A: You would need to pass in a dict of headers to shouldDownload (or the result of urlopen):
def shouldDownload(url, headers, prev_etag, prev_lastmod, prev_expires, prev_content_length):
return (prev_content_length != headers.get("content-length") || prev_lastmod != headers.get("If-Modified-Since") || prev_expires != headers.get("Expires") || prev_etag != headers.get("ETAG"))
# or the optimistic way:
# return prev_content_length == headers.get("content-length") and prev_lastmod == headers.get("If-Modified-Since") and prev_expires = headers.get("Expires") and prev_etag = headers.get("ETAG")
Do that when you open the URL:
# my urllib2 is a little fuzzy but I believe `urlopen()` doesn't
# read the whole file until `.read()` is called, and you can still
# get the headers with `.headers`. Worst case is you may have to
# `read(50)` or so to get them.
s = urllib2.urlopen(MYURL)
try:
if shouldDownload(s.headers):
source = s.read()
# do stuff with source
else:
continue
# except HTTPError, etc if you need to
finally:
s.close()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create a WCF REST/JSON service in IIS without svc file? This page (MSDN) says in the first step:
Alternatively, you can also use configuration to add an AJAX endpoint.
I'm unable to access my service endpoint following their example exactly. (VS2010, .NET 4.0, Win7) I always come back with 404-not found when I try to access it.
A: You can define the endpoint using configuration, but you need the .svc file to host the file in IIS.
If you really don't want an .svc file, you can also use the the ASP.NET Routes integration (more info in http://blogs.msdn.com/b/endpoint/archive/2010/01/25/using-routes-to-compose-wcf-webhttp-services.aspx or http://msdn.microsoft.com/en-us/library/ee662952(VS.100).aspx) - in that case you'll specify the factory when you're setting up your route.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Query Needed ( based on the column value, row value should be loaded ) My Sql query is,
Select CustomerName,ProjectID,ProjectDesc from dbo.projects
The Output is:
CustomerName ProjectID ProjectDesc
A3 Consulting FZ, LLC. 277 A3
A3 Consulting FZ, LLC. 278 A3 - Chef
Anesthesia Business Consultant 279 Astra
ARI Network Services, Inc. 280 Mira
What i want is,the project desc should be in row as per the customer.
CustomerName ProjectDesc ProjectID
A3 Consulting FZ, LLC.
A3 277
A3 - Chef 278
Anesthesia Business Consultant
Astra 279
ARI Network Services, Inc.
Mira 280
A: I agree with the comments, this is not a Query issue, but a display issue. But if you really want to do it in SQL, try this.
Select a.CustomerName,'' as ProjectDesc,'' as ProjectID,
a.CustomerName+'1' as SortKey
from dbo.projects a
join dbo.projects b on b.CustomerName=a.customerName
union
Select '' ,b.ProjectDesc,cast(b.ProjectID as varchar(20)),
a.customerName+'99'
from dbo.projects a
join dbo.projects b on b.CustomerName=a.customerName
order by 4
It will give you what you want, but it has an extra sort key column on the end that your front end will need to get rid of...
Here is another approach if you want to hide that key
select ROW_NUMBER() OVER(ORDER BY SortKey) as RowNum,
CustomerName, ProjectDesc, ProjectID
from
(
Select a.CustomerName,'' as ProjectDesc,'' as ProjectID ,
a.CustomerName+'1' as SortKey
from dbo.projects a
join dbo.projects b on b.CustomerName=a.customerName
where departmentID = @DeptID
union
Select '' ,b.ProjectDesc,cast(b.ProjectID as varchar(20)),
a.customerName+'99'
from dbo.projects a
join dbo.projects b on b.CustomerName=a.customerName
where departmentID = @DeptID
) xx
order by 1
This approach will convert the ugly key into a series of sequential numbers. But just because this CAN be done in SQL, doesn't mean it SHOULD be...
A: Use this code in sql server 2005. I think this will defiantly work...
create table #projects1
(
CustomerName varchar(max),
ProjectDesc varchar(max),
ProjectID varchar(max)
);
declare @count int;
declare @lastname varchar(max),@CustomerName varchar(max),@ProjectID varchar(max),@ProjectDesc varchar(max);
set @count=0;
set @lastname='';
declare pro_cursor CURSOR for
select CustomerName, ProjectDesc, ProjectID from projects
open pro_cursor
fetch next from pro_cursor into @CustomerName,@ProjectDesc,@ProjectID
while(@@fetch_status=0)
begin
if(@lastname!=@CustomerName)
begin
if(@count=0)
begin
set @lastname=@CustomerName;
set @count=@count+1;
end
set @lastname=@CustomerName;
insert into #projects1 values (@CustomerName,'','');
insert into #projects1 values ('',@ProjectDesc,@ProjectID);
end
else
begin
insert into #projects1 values ('',@ProjectDesc,@ProjectID)
end
fetch next from pro_cursor into @CustomerName,@ProjectDesc,@ProjectID
end
select * from #projects1
close pro_cursor;
deallocate pro_cursor
truncate table #projects1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Retain release count, confirmation needed Just because i pass a reference to a newly alloc init(ed) object to another class does not mean that class retained it in a constructor, right?
As i understand it, in order for a class to retain something, it actually needs to send retain message to an object. Is this correct?
In my example, i am referring to my own custom class, not an Apple class.
A: The other class should retain it if it is going to hold a reference to it. But, that's the concern of the class you're calling.
Yes, sending the retain message retains it.
It's important to read this guide:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html
Below is a good set of rules. The second rule says you retain something you store and it also says a received object is guaranteed to be valid for the lifetime of that function call. Which means if you're taking an object as an arg and your not going to store it as an iVar/property, then you don't need to retain it.
From the linked Apple doc:
You own any object you create
You create an object using a method whose name begins with “alloc”,
“new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or
mutableCopy).
You can take ownership of an object using retain
A received object is normally guaranteed to remain valid within the
method it was received in, and that method may also safely return the
object to its invoker. You use retain in two situations: (1) In the
implementation of an accessor method or an init method, to take
ownership of an object you want to store as a property value; and (2)
To prevent an object from being invalidated as a side-effect of some
other operation (as explained in “Avoid Causing Deallocation of
Objects You’re Using”).
When you no longer need it, you must relinquish ownership of an
object you own
You relinquish ownership of an object by sending it a release message
or an autorelease message. In Cocoa terminology, relinquishing
ownership of an object is therefore typically referred to as
“releasing” an object.
You must not relinquish ownership of an object you do not own
This is just corollary of the previous policy rules, stated
explicitly.
A: Correct. The retain must be coded or it doesn't happen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write query in ormlite when the condition generated using for loop I'm writing a query in ormlite as below
Where<Advertisement, Integer> where = queryBuilder.where();
where.and(
where.between("latitude", pLatitude - APPOXIMATION_FACTOR,
pLatitude + APPOXIMATION_FACTOR),
where.between("longitude", pLongitude - APPOXIMATION_FACTOR,
pLongitude + APPOXIMATION_FACTOR)
.and().between("width", pWidth - APPOXIMATION_FACTOR,
pWidth + APPOXIMATION_FACTOR),
);
and also one more and with this
for (int iterator = 0; iterator < moduleList.size(); iterator++) {
where.eq("id", moduleList.get(iterator).getmId());
if (iterator != advertisementList.size() - 1){
whereForModuleID.or();
}
}
but i am stuck how to write query in this case
Looking for help
A: In the 2nd case I'd use instead the where.in(String, Iterable) method. You should do something like this:
List<Integer> idList = new ArrayList<Integer>();
for (Module module : moduleList) {
idList.add(module.getmId());
}
where.in("id", idList);
This turns into a SQL query like:
SELECT * `foo` WHERE `id` IN (7, 17, 1, 34)
Here are the docs on where.in():
http://ormlite.com/docs/where-in
In terms of the original question, see this answer about the where.and(int) and or(int) methods.
A: To create a query which looks up an account by name and password you would do the following:
QueryBuilder<Account, String> qb = accountDao.queryBuilder();
Where where = qb.where();
// the name field must be equal to "foo"
where.eq(Account.NAME_FIELD_NAME, "foo");
// and
where.and();
// the password field must be equal to "_secret"
where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();
This is my code which i am using in my project to get PropertyModel from SQLite using ORMLite
public ArrayList<PropertyPicModel> selectArgumentQueryPropertyModel(int property_id, Dao<PropertyPicModel, Integer> dao)
{
try {
QueryBuilder<PropertyPicModel, Integer> queryBuilder = dao.queryBuilder();
Where<PropertyPicModel, Integer> where = queryBuilder.where();
SelectArg selectArg = new SelectArg();
// define our query as 'property_id = ?'
where.eq(ORMLiteConfig.PROPERTY_ID, selectArg);
// prepare it so it is ready for later query or iterator calls
PreparedQuery<PropertyPicModel> preparedQuery = queryBuilder.prepare();
selectArg.setValue(property_id);
// later we can set the select argument and issue the query
ArrayList<PropertyPicModel> picList = (ArrayList<PropertyPicModel>) dao.query(preparedQuery);
return picList;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
MyLog.e("Excep selectArgumentQuery " +e.toString());
}
catch (Exception e) {
MyLog.e("Excep selectArgumentQuery " +e.toString());
}
return null;
}
In this example, the SQL query that will be generated will be approximately:
SELECT * FROM account WHERE (name = 'foo' AND passwd = '_secret')
https://github.com/AshishPsaini/ormlite-examples/tree/master/android/HelloAndroid
http://ormlite.com/docs/in
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP and Javascript error I am trying to do something like this.
<script type="text/javascript">
$(window).load(function(){
<?php
if(isset($_SESSION['tagname']))
{
?>
var t = <?php echo $_SESSION['tagname'] ?>;
$('.tag span').html(t);
<?php
}
else
{
?>
$('.tag').hide();
<?php
}
?>
});
</script>
Now the problem is, the variable 't' is not getting set.
If I write a static text inside that line of code, then my code works.
Is there anything I am doing wrong here?
A: If t is a string value, then that should be a syntax error because you would be using a string outside quotes.
Try
var t = '<?php echo $_SESSION['tagname'] ?>';
A: Encode as JSON before outputting text to be used as JavaScript literals.
var t = <?php echo json_encode($_SESSION['tagname']) ?>;
And of course, make sure that $_SESSION['tagname'] actually contains something.
A: Because the t variable contains a string, which should be enclosed in single or double quotes (in this case, double quotes, as you have single quotes inside the string so it doesn't mess up).
var t = "<?php echo $_SESSION['tagname'] ?>;";
And, it depends if "tagname" is a Javascript variable or not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: perl parsing specific value from xml file based on condition Can someone show me how to parse out specific information from an xml file? Am I suppose to use a regex?
I am using XML::Simple to view my test.xml file.
For example, I want to search for the string test-out-00000, if it exists then give me/print the size = 135860644
Data:
$VAR1 = {
'recursive' => 'no',
'version' => '0.20.202.1.1101050227',
'time' => '2011-09-30T02:49:39+0000',
'filter' => '.*',
'file' => {
'owner' => 'test_act',
'replication' => '3',
'blocksize' => '134217728',
'permission' => '-rw-------',
'path' => '/source/feeds/customer/test/test-out-00000',
'modified' => '2011-09-30T02:48:41+0000',
'size' => '135860644',
'group' => '',
'accesstime' => '2011-09-30T02:48:41+0000'
},
'path' => '/source/customer/test',
'directory' => {
'owner' => 'test_act',
'group' => '',
'permission' => 'drwx------',
'path' => '/source/feeds/customer/test',
'accesstime' => '1970-01-01T00:00:00+0000',
'modified' => '2011-09-30T02:48:41+0000'
},
'exclude' => ''
};
recursive:no
version:0.20.202.1.1101050227
time:2011-09-30T02:49:39+0000
filter:.*
file:HASH(0x84c841c)
path:/source/customer/test
directory:HASH(0x84c7648)
exclude:
Working perl script:
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;
my $xml = $ARGV [0];
my $data = XMLin($xml);
print Dumper( $data );
foreach my $attributes (keys %{$data}){
print"$attributes:${$data}{$attributes}\n";
}
XML file test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<listing time="2011-09-30T02:49:39+0000" recursive="no" path="/source/customer/test" exclude="" filter=".*" version="0.20.202.1.1101050227">
<directory path="/source/feeds/customer/test" modified="2011-09-30T02:48:41+0000" accesstime="1970-01-01T00:00:00+0000" permission="drwx------" owner="test_act" group=""/>
<file path="/source/feeds/customer/test/test-out-00000" modified="2011-09-30T02:48:41+0000" accesstime="2011-09-30T02:48:41+0000" size="135860644" replication="3" blocksize="134217728" permission="-rw-------" owner="test_act" group=""/>
</listing>
A: I'm assuming you're always looking for the text string in the filename? If so, this is one way of doing it:
use strict;
use warnings;
use XML::Simple;
my $xml = $ARGV [0];
my $data = XMLin($xml);
my $size = 0;
if (exists $data->{file}->{path} and $data->{file}->{path} =~ /test-out-00000/) {
$size = $data->{file}->{size};
}
If your data follows this format you could also use XML::LibXML to just grab the values using an XPATH expression.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change the language of datepicker I am trying to build a function that changes the language of date picker
$(function(){
txtDate = $("#txtDate");
var minDate = new Date(2011, 1 - 1, 15);
var maxDate = new Date(2011, 6 - 1, 15);
txtDate.date
txtDate.dateEntry({
defaultDate: maxDate,
minDate: minDate,
maxDate: maxDate,
spinnerImage: ''
});
txtDate.datepicker({
minDate: minDate,
maxDate: maxDate
});
txtDate.datepicker("setDate", maxDate);
dateLanguageChange();
});
var dateLanguageChange = function () {
$("#txtDate").datepicker("destroy").datepicker($.datepicker.regional["fr"]);
};
html:
<div class="form-row">
<label>@Html.Resource("Date")</label>
<input id="txtDate" type="text" class="date-box" />
</div>
A: have you tried using jQuery UI Datepicker It's a highly configurable plugin and provides support for localizing its content to cater for different languages and date formats.
$(function() {
$("#txtDate").datepicker({
dateFormat: 'dd/mm/yy',
minDate: '-10y',
maxDate: 'now',
changeMonth: true,
changeYear: true,
firstDay: 1
});
$.datepicker.setDefaults($.datepicker.regional['fr']);
});
your html
<input id="txtDate" type="text" class="date-box" />
Note:configure datepicker options accordingly....make sure to include jquery.ui.datepicker-fr.js Hope it helps!!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: asp.net cshtml can't run asp.net code I'm following the tutorial at asp.net mvc3 at
http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part3-cs
@{
ViewBag.Title = "Welcome";
}
<h2>Welcome</h2>
<ul>
@for (int i=0; i < ViewBag.NumTimes; i++) {
<li>@ViewBag.Message</li>
}
</ul>
the hellowWorldcontroller
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class HelloWorldController : Controller
{
// GET: /HelloWorld/
/*public void Index()
{
//return "This is my <b>default</b> action...";
return View;
}*/
public ActionResult Index()
{
//ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
//
// GET: /HelloWorld/Welcome/
public ActionResult Welcome(string name, int numTimes = 1)
{
return View();
//return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
}
}
}
But it seems that in cshtml, it can't run the asp.net code, only display the static content, why?
And the cshtml also don't apply to the MainContent master page, there is only plain text without any background and button when I run the application, where's the problems?
A: To have your for to work, you must set the value of ViewBag in the controller.
Change the the controller like this
public ActionResult Welcome(string name, int numTimes = 1)
{
ViewBag.Message = name;
ViewBag.NumTimes = numTimes;
return View();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java Marshalling and UnMarshalling Employee.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="1.0" elementFormDefault="qualified">
<xsd:include schemaLocation="Family.xsd"/>
<xsd:element name="NewFields">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="empFirstName" type="xsd:string" />
<xsd:element name="empLastName" type="xsd:string" />
<xsd:element name="family" type="FamilyFields" nillable="true" maxOccurs="unbounded" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Family.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="1.0" elementFormDefault="qualified">
<xsd:complexType name="FamilyFields">
<xsd:sequence>
<xsd:element name="relation" type="xsd:string" />
<xsd:element name="firstName" type="xsd:string" />
<xsd:element name="lastName" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
A third party application that uses these 2 schemas generate an xml string like -
<NewFields>
<empFirstName>Kevin</empFirstName>
<empLastName>Smith</empLastName>
<family>
<FamilyFields>
<relation>self</relation>
<firstName>New Kevin</firstName>
<lastName>New Smith</lastName>
</FamilyFields>
<FamilyFields>
<relation>wife</relation>
<firstName>Jennifer</firstName>
<lastName>Smith</lastName>
</FamilyFields>
</family>
</NewFields>
The second schema is always a fixed schema.
My requirement is to parse the relation tag and if the relation is "self", I need to overwrite empFirstName and empLastName with firstName and lastName of the respective fields.
How can I achieve this?
EDIT 1 : Employee.xsd is dynamic and could be anything. But Family.xsd is static and can be imported from any other xsd.
A: The general outline: (a) map you XML schema files, (b) unmarshall the given XML, (c) modify the XML object in memory finally (d) marshall the modified object anywhere you want.
Map your XML schema files
@XmlRootElement(name = "FamilyFields") public class FamilyFields {
@XmlElement public String relation;
@XmlElement public String firstName;
@XmlElement public String lastName;
public FamilyFields() {}
}
@XmlRootElement(name = "NewFields") public class NewFields {
@XmlElement public String empFirstName;
@XmlElement public String empLastName;
@XmlElementWrapper(name = "family")
@XmlElement(name = "FamilyFields")
public List<FamilyFields> familyFields;
public NewFields() {}
}
(If you take an advice: do it by hand! Generating JAXB entities with XJC almost never outputs the things you expect and can get time consuming if you don't have very simple schema files at hand.)
Acquire JAXBContext, Unmarshaller and Marshaller
JAXBContext context = JAXBContext.newInstance(NewFields.class, FamilyFields.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Marshaller marshaller = context.createMarshaller();
// set optional properties
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Handle incoming XML
// the XML content you gave
String xml = ...
StringReader reader = new StringReader(xml);
NewFields newFields = (NewFields) unmarshaller.unmarshal(reader);
// modify the unmarshalled data to your heart's content
newFields.empLastName = ...
// marshal the modified data anywhere you want
marshaller.marshal(newFields, System.out);
A: If you have an XSD then manipulating XML is the easiest with XML data binding. Using the XSD you can create java bean like classes that represent the XSD. Now you can getters and setters on the java class and then output the XML. There are many XML data binding solutions. Try XML beans:
http://xmlbeans.apache.org/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Accessing a standalone PHP file How would you reference an actual file in a Drupal project?
I have a flash app that needs to talk to a php script, but I can't just say "http://{domain}/{filepath}/{file}" or even "http://{domain}/{file}" assuming there was some assumed pathing structure.
To be more specific, the file lives in /sites/all/flash/postit.php. How would Drupal tie it's database driven content to an actual file?
A: You'll need to reference it with a PHP include such as
include "/sites/all/flash/postit.php";
If you try to include it with http://domain.com/postit.php the webserver will process the PHP file and all you'll get is the HTML output.
A: If you postit.php use additional includes, that have next structure:
FOLDER1/someincludefile.php
someincludefile.php
postit.php
and use relative path for including, it will raise error that files doesn't found, so you can include in next manner:
$cwd = getcwd(); // current dir. usually where index.php running.
$file = base_path() ."/sites/all/flash/postit.php"; // path to our script
$dir = dirname($file);
chdir($dir); // changing to file folder.
require_once('postit.php');
// Run your code
..
chdir($cwd); // return to own dir.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Do JavaScript Static Variables stay present once control leaves the script? I have a question about static variables in JavaScript. Do they only last during the scope of the script? What I mean is what if control leaves the script and goes back to the html code, are the static variables still there?
A: I assume that you mean global instead of static variables. Global variables are declared in the global document scope. They are accessible from all methods (functions) and when you modify their value from within a function's code block, the value persists, since you are modifying the global variable.
For example:
<script type="text/javascript">
global_var = 0; // declared globally
function global_inc(){
global_var += 1; // global var incremented by 1
}
function local_inc(){
local_var = global_var; // declared locally, and scope ends at function end.
local_var += 1; // local var incremented by 1
alert('global: ' + global_var);
alert('local: ' + local_var);
}
function alert_global(){
alert('global: ' + global_var);
}
</script>
<script type="text/javascript">
alert_global(); // alert global (0)
global_inc(); // increment global to 1
local_inc(); // set local to global (1) and increment local to (2), alert both
alert_global(); // alert global (1)
</script>
You would get:
alert of "global: 0" from alert_global()
alert of "global: 1" from local_inc()
alert of "local: 2" from local_inc()
alert of "global: 1" from alert_global()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.net MVC 3 Unobtrusive Client Validations in JQuery Modal Pop up Issue When I tried to implement ASP.net MVC 3 Unobtrusive Client Validations in the application, the rendered html didn't generate the span tags which are generated by JQuery.
I have only got following rendering html and I used JQuery modal popup as a container for my partial View.
<input data-val="true" data-val-required="The City field is required." id="City" name="City" type="text" value="Seattle" />
However, when I used Unobtrusive Client validation with out JQuery Modal pop up it works correctly as follows in same application.
<div class="editor-field">
<input data-val="true" data-val-required="The City field is required." id="City" name="City" type="text" value="Seattle" />
<span class="field-validation-valid" data-valmsg-for="City" data-valmsg-replace="true"></span>
</div>
Is there any thing that I need to implement when I use Unobtrusive Client validations in JQuery Modal Popup?
JQuery Popup Code
$(document).ready(function () {
$('#actionPanelDialogs div').dialog({
autoOpen: false,
modal: true,
width: 700,
appendToBody: true
});
$('#actions a').click(function (event) {
event.stopPropagation();
event.preventDefault();
var link = $(this);
var action = link.attr('href');
var dialogDivId = link.attr('rel');
var dialogDiv = $('#' + dialogDivId);
$.get(action, null, function (data) {
dialogDiv.html(data);
dialogDiv.dialog('open');
});
return false;
});
});
A: You have to manually trigger a parse of any new elements added to the DOM.
jQuery.validator.unobtrusive.parse("#modalPopup");
If you are using jQuery UI
$( ".selector" ).dialog({
open: function(event, ui) {
jQuery.validator.unobtrusive.parse(ui);
}
});
A: Found the problem,
I've used form html to create form element as follows.
<form action="@Url.Action("Create", "Person")" enctype="multipart/form-data" method="post" id="contactForm">
When I used Html helper it worked correctly.
@{using (Html.BeginForm("Create", "Person", new { enctype = "multipart/form-data", id = "contactForm" }))
A: For anyone using bootstrap modals use the following code:
$('#myModal').on('shown.bs.modal', function () {
jQuery.validator.unobtrusive.parse($(this));
})
Thanks to Josh for the guts of it.
A: Tried all approaches and this is what worked for me:
$(".showModal").click(function () {
var id = $(this).attr("data-id");
$("#modal").load("/Controller/Action?id=" + id, function () {
$("#modal").modal();
$.validator.unobtrusive.parse($("#modal"));
})
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Group entries by date and time from timestamps I'm building a booking system and have opted to use timestamps to store the bookings in my mysql database. The user can book 2 or 3 slots consequtively however, for example:
9:00 - 9:30
9:30 - 10:00
10:00 - 10:30
or they can just book single slots.
I want to show the bookings made by a user but group them by the time frame, so for example in the times shown above it should show 9:00 - 10:30 instead of listing 3 items.
Each booking is stored with a bookingFrom and bookingUntil as a timetamp. I have managed to get it working for 2 bookings (eg 9:00-9:30 and 9:30-10:00 to show as just 9:00-10:00) but if there is a middle entry, i'm struggling with how to get this working.
Any ideas? I'm using PHP/mySQL
TABLE SCHEMA
bookingID, userID, bookingFrom (INT - unix timestamp), bookingUntil (INT - unix timestamp)
CREATE TABLE IF NOT EXISTS `dma_bookings` (
`bookingID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) NOT NULL,
`bookingFrom` int(11) NOT NULL,
`bookingUntil` int(11) NOT NULL,
`roomID` int(11) NOT NULL,
PRIMARY KEY (`bookingID`),
KEY `userID` (`userID`,`bookingFrom`,`bookingUntil`),
KEY `roomID` (`roomID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=98 ;
--
-- Dumping data for table `dma_bookings`
--
INSERT INTO `dma_bookings` (`bookingID`, `userID`, `bookingFrom`, `bookingUntil`, `roomID`) VALUES
(95, 1, 1317362400, 1317364199, 1),
(96, 1, 1317364200, 1317365999, 1),
(97, 1, 1317366000, 1317367799, 1);
Code so far (apologies very messy!):
$bookingArray = $data['bookingInfo'];
$bookingCleanArray = array();
$reversedArray = array_reverse($data['bookingInfo']);
$currentItemIndex=0;
$nextItemIndex=1;
foreach($reversedArray as $booking){
echo "<hr>BookingID: ".$booking['bookingID']."<br/><br/>";
$bookingFromMinusOne=$booking['bookingFrom']-1;
if($bookingFromMinusOne==$data['bookingInfo'][$nextItemIndex]['bookingUntil']){
//The current booking is part of a multiple booking range
$bookingArray[$nextItemIndex]['bookingUntil']=$booking['bookingUntil'];
unset($bookingArray[$currentItemIndex]);
}else{
echo "Single booking<br/>";
}
$currentItemIndex++;
$nextItemIndex++;
}
A: Assuming you've got separate fields for each time you load them into an array then use the first string and count to find the last string.
But yes as rahularyansharma said needs a bit more detail.
Okay... hhmm
Wouldn't you just want to grab:
SELECT dma_bookings (bookingID, userID, bookingFrom, bookingUntil, roomID) WHERE userID = 1)
Which should give us:
bookingID, userID, bookingFrom, bookingUntil, roomID
$bookingArray = array( 95, 1, 1317362400, 1317364199, 1 ),
array( 96, 1, 1317364200, 1317365999, 1 ),
array( 97, 1, 1317366000, 1317367799, 1 ),
so if we...
echo $bookingArray[][2]; we get '1317362400'
$c = count($bookingArray);
echo $bookingArray[$c][3]; we get '1317367799'
Or have I completely misunderstood what you're trying to do?
A: I think my approach would be to select all the bookings for a given user, but order the results by the start time. I get the feeling your current loop has the right start, you just need a few more conditions to make sure the slots work.
I would start with the first slot, and keep adjusting the end time until I reach a start time that is greater than the current end time. At that point you finish with the current slot, (say push it onto another array), and set your current slot to the new one.
Here is an example, although I don't have the time to test it I think it should work:
$slots = array(
array('bookingID' => 95, 'userID' => 1, 'bookingFrom' => 1317362400, 'bookingUntil' => 1317364199, 'roomID' => 1),
array('bookingID' => 96, 'userID' => 1, 'bookingFrom' => 1317364200, 'bookingUntil' => 1317365999, 'roomID' => 1),
array('bookingID' => 97, 'userID' => 1, 'bookingFrom' => 1317366000, 'bookingUntil' => 1317367799, 'roomID' => 1)
);
$condensed_slots = array();
$currentSlot = null;
foreach($slots as $slot){
if($currentSlot == null) $currentSlot = $slot;
else {
if($slot['bookingFrom'] <= $currentSlot['bookingUntil']){
$currentSlot['bookingUntil'] = $slot['bookingFrom'];
}
else {
$condensed_slots[] = $currentSlot;
$currentSlot = $slot;
}
}
}
So after that $condensed_slots should contain a reduced set (if possible) of slots, although the bookingID may not necessarily reflect the original from and until timestamps (obviously).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dojo multiple popup windows? Can some one tell me how to open multiple popup windows without freezing the parent window. Actually what I want to do is this: I have implemented a Dojo grid. If some one clicks on a cell I want to open a popup window with information in the cell. I have already done that. But the problem I can't click on the grid again to open another popup until I close the popup I have already open. Also I prefer the popup has minimize capability. Any help? I am new to Dojo related development. Thanks in advance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Assigning a variable to a wrapper set in jQuery doesn't make the code work I am trying to cache or to assign my selector $('#img-grp-wrap .img-wrap img:first-child') to a variable because I used it a lot of times in the code and I kept on repeating myself. But for some reason, when I assigned my selection to a variable, the code doesn't work anymore. Please see below (1st one is working, 2nd one not working):
Non-cached (working):
http://jsfiddle.net/g5tvZ/
Cached (not working):
http://jsfiddle.net/uMe2p/
(The code is supposed to automatically slide through the images and be able to use next/prev buttons to navigate. Please ignore the extra var rotate; on top. I would also appreciate any other refactoring tips about the code.)
A: This:
var imgFirst = $('#img-grp-wrap .img-wrap img:first-child');
leaves a set of DOM elements (along with jQuery wrapping) in imgFirst. Your imgFirst will match the state of the DOM when you assign your value to imgFirst.
Then later you change the DOM so :first-child doesn't select the same element that it used to and you're left with the wrong thing in imgFirst. Basically, the DOM changes but your imgFirst doesn't track those changes.
A: I'd like to point out another issue you have with your code. You need to remove the var from in front of the rotate assignment here so that you are assigning to the same global variable that keeps track of your timer. With the var in front of it, it's a local variable and you will get multiple timers stacking up when you repeatedly click on the prev or next buttons (which it's possible to make happen). So change this:
$('#img-grp-wrap .prev, #img-grp-wrap .next').hover(function() {
clearInterval(rotate);
}, function() {
var rotate = setInterval(function() {
slideShow();
}, 4000);
});
to this:
$('#img-grp-wrap .prev, #img-grp-wrap .next').hover(function() {
clearInterval(rotate);
}, function() {
rotate = setInterval(function() {
slideShow();
}, 4000);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ColdFusion unit test frameworks As a related sub-question - are there any CF unit test frameworks that support or make it easier to use mocks/stubs?
The 2 that I spotted in a quick google that look the most promising are MXUnit and CFUnit. Are there others, and which one(s) have the widest adoption and active development? Enough questions crammed into one?
Basically I want to make a good choice.
edit Note that at the time of writing the question originally, MXUnit was the go-to and TestBox wouldn't be on github for a few years yet. See comments on the accepted answer.
A: TestBox is a new xUnit and BDD style framework that is compatible with MXUnit and comes with MockBox which is a full mocking and stubbing library. Both of these are actively developed and professionally supported by Ortus Solutions.
https://testbox.ortusbooks.com/introduction/installing-testbox
https://testbox.ortusbooks.com/mocking/mockbox/installing-mockbox
A: Don't forget http://github.com/bobsilverberg/CFSelenium
A: Pretty sure that the only CF unit test framework still in active development is MXUnit.
Check out MockBox (also in active development) for support in using mocks/stubs.
http://wiki.coldbox.org/wiki/MockBox.cfm
Edit: Be sure to follow the MXUnit google group. http://groups.google.com/group/mxunit/topics
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Submitting HTML Form with AJAX I've got a form:
<form action="#" method="post" id="hubForm">
<label class="labelText">Expiration Date:</label>
<input class="datBox" type="text" id="cal" name="date">
<div class="clr"></div>
<div class="clr"></div>
<label class="labelText">Hub Name</label>
<input class="inputTxt" type="text" value="" name="name" />
<div class="clr"></div>
<label class="labelText">Description</label>
<textarea class="textArea" name="desc"></textarea>
<div class="clr"></div>
<input class="submitButt" type="submit" value="" />
<div class="clr"></div>
</form>
And I've got this JavaScript:
$('#hubForm').submit(function() {
$.ajax({
url: "hubControl.php",
type: "post",
data: $(this).serialize()
});
});
And this PHP code:
//Add the hub, task, or project to the database
mysql_query("INSERT INTO ".$type."s(".$IDvar.", name, description, users, expDate)
VALUES(".$ID.", \"".$_POST['title']."\", \"".$_POST['desc']."\", ".$ID.", ".$_POST['date'].")");
But it refuses to add anything to the database. I've rewritten the code to use $_GET and tested the PHP and I've verified that it works.
As for the JavaScript, I've also tried stuff like
$.post("hubControl.php", $('#hubForm').serialize());
but nothing seems to work. Any ideas?
EDIT:
The form HTML was given to me by someone else, so I don't know if it's 100% compatible with the AJAX/JavaScript with stuff like the method="post". You will all have a better idea than I would.
A: Since you're using jQuery, you should consider using the ajaxForm plugin. It's very easy to use, you can just drop it in to your project with minimal setup.
A: If it works with $_GET and not $_POST, it sounds like the $_POST array is not being filled correctly.
I would recommend you start working through this by viewing your $_REQUEST or $_POST array when the page is loaded. print_r($_POST) in some HTML pre tags can be very useful.
If you know that the PHP isn't even receiving the correct data, you can focus on fixing the Ajax/jQuery.
A: Try to use uppercase type:
$.ajax({
url: "hubControl.php",
type: "POST",
data: $(this).serialize()
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android: NoClassDefFoundError upon Android JUnit Test JUnit trace:
java.lang.NoClassDefFoundError: com.sample.Functions$Floor
at com.sample.test.FunctionsTest.testValidateLocation(FunctionsTest.java:289)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
Here's my test code:
public class FunctionsTest extends TestCase {
public void testValidateLocation() {
location.setLatitude(-90);
location.setLongitude(-180);
assertTrue(Functions.Location.validateLocation(location));
}
}
Here's the target method:
public static boolean validateLocation(android.location.Location location) {
return location==null?false:Double.compare(location.getLatitude(), MAXIMUM_LATITUDE) <= 0
&& Double.compare(location.getLatitude(), MINIMUM_LATITUDE) >= 0
&& Double.compare(location.getLongitude(), MAXIMUM_LONGITUDE) <= 0
&& Double.compare(location.getLongitude(), MINIMUM_LONGITUDE) >= 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need a query to put certain mySQL database columns into a row I need to join this mySQL table:
TABLE1
id pagetitle
1 remodeling
2 handywork
3 aesthetics
With this one:
TABLE2
id contentid tmplvarid value
1 1 1 Jaime
2 1 2 img/remodeling.jpg
3 2 1 Alex
4 2 2 img/handywork.jpg
5 3 1 Karla
6 3 2 img/aesthetics.jpg
To output this:
id pagetitle author image
1 remodeling Jaime img/remodeling.jpg
2 handywork Alex img/handywork.jpg
3 aesthetics Karla img/aesthetics.jpg
Note: The relation between Table1 and Table2 is: Table1.id = Table2.contentid
If it helps ...tmplvarid 1 is author and tmplvarid 2 is image
What is the SQL query I can use to accomplish this?
A: select t1.id,
t1.pagetitle,
(select value from TABLE2 where contentid = t1.id and tmplvarid = 1) as author,
(select value from TABLE2 where contentid = t1.id and tmplvarid = 2) as image
from TABLE1 t1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ std::list of pointer to a struct I believe it's a very easy question but I'm quite confused.
What I am doing wrong ?:
std::list<curvesdata *> curvelist;
curvesdata * curve = new curvesdata;
curvelist.pop_back(curve);
---> no matching function for call to 'std::list<curvesdata*>::pop_back(curvesdata*&)
Seems my pointer is converted to a pointer reference ... ? why ?
Thanks.
A: void pop_back ( );
Does not take any arguments. It removes the last element in the list container, effectively reducing the list size by one. See the reference here.
Since the function does not take any arguments, the compiler tries to tell you the same by giving the error of non matching function.
To know Why the compiler does not report the exact error, see this:
why-the-compiler-does-not-detect-correct-function-signature-in-error
To Add a new element at the end of the list,You should be using:
list::push_back()
To Add a new element at the front of the list, You should be using:
list::push_front()
See the reference here.
A: std::list::pop_back() doesn't take an argument, it deletes the last element from the list. Looks like you want to add, so use push_back().
curvelist.push_back(curve);
edit: Now let me wax on about clang++ and its nicer error messages:
#include <list>
int main() {
std::list<int> x;
x.pop_back(1);
}
$ clang++ example.cxx
example.cxx:6:13: error: too many arguments to function call, expected 0, have 1
x.pop_back(1);
~~~~~~~~~~ ^
A: Just FYI, the error message is telling you exactly what's wrong. There's no member function called pop_back for list that takes an argument.
You may be thinking of push_back: http://www.cplusplus.com/reference/stl/list/push_back/
A: pop_back() doesn't take an argument. There's no matching call to what you're trying to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: splitting a string based on multiple char delimiters I have a string "4,6,8\n9,4"
I want to split this based on ,and \n
Output array should be
4
6
8
9
4
Edit :
Now i am reading string from console , when i enter a string as above in console , in the code behind i get as "4,6,8\\n9,4" . Now that i want to split using "," and "\\n" . How can i change the expression ?
A: var s = "4,6,8\n9,4";
var split = s.Split(new char[]{',', '\n'});
But this has to be a dupe...
EDIT: Addressing the comment.
This code:
static void Main(string[] args)
{
var s = "4,6,8\n9,4";
foreach (var a in s.Split(new char[] { ',', '\n' }))
System.Diagnostics.Debug.WriteLine(a);
}
Outputs this:
4
6
8
9
4
EDIT: Reading input from the console is different. \n is different when entered manually.
static void Main(string[] args)
{
var s = "4,6,8\\n9,4";
foreach (var a in s.Split(new string[] { ",", "\\n" }, StringSplitOptions.RemoveEmptyEntries))
System.Diagnostics.Debug.WriteLine(a);
}
A: string tosplit = "4,6,8\n9,4";
var split = tosplit.Split(new Char [] {',', '\n' });
Just in case you are not printing / seeing it properly:
split.ToList().ForEach(Console.WriteLine);
A: Can you do a string.Replace('\n',',') followed by the string.split(',') ?
A: Use string.Split(char [])
string strings = "4,6,8\n9,4";
string [] split = strings .Split(new Char [] {',' , '\n' });
EDIT
Try following if you get any unnecessary empty items. String.Split Method (String[], StringSplitOptions)
string [] split = strings .Split(new Char [] {',' , '\n' },
StringSplitOptions.RemoveEmptyEntries);
EDIT2
This works for your updated question. Add all the necessary split characters to the char [].
string [] split = strings.Split(new Char[] { ',', '\\', '\n' },
StringSplitOptions.RemoveEmptyEntries);
A: Another option is to use Regex.Split. This is useful when the split sequences are more complex. For instance if spaces can also be part of the split delimiters such as:
"4,6,8 , 9\\n\\n4"
Then:
using System.Text.RegularExpressions;
var i = "4,6,8 , 9\n\n4";
var o = Regex.Split(i, @"[,\s\n]+");
// now o is:
// new string[] { "4", "6", "8", "9" }
Note that the regular expression used is "more accepting" - it ignored the empty "space" between the \n's and it would accept "4 6 8 9 4" just the same - so the above to to show a point: there is more than one way to skin a cat.
Happy coding.
A: // input string
string input = "email@domain.com;email2@domain.com,email3@domain.com;";
// each character in this string will split it
string splitBy = ",;";
// do the split, remove any blank results
string[] result = input.Split(splitBy.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
output is an array of strings:
email@domain.com
email2@domain.com
email3@domain.com
A: for every cases
string s = "";
s.Split(new string[] { ",", "DEL", ";"}, StringSplitOptions.None);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "87"
}
|
Q: VB.net list(of T) not returning indexed object I'm working on a small game that is based on a map of grid squares. I have a class (clsGrid) that stores a few properties for each grid square. The grid square objects are organized into a list(of clsGrid).
A loop and stream reader are successfully reading properties from a text file, putting the properties into grid objects, and adding the grid objects to a my list of grids. When retrieving a grid from the list of grids, I'm getting unusual results. Regardless of the index I give the list, I always seem to get the last indexed grid in the list. The debugger seems to suggest that the right numbers are being read into the stream reader and they are being added to gridHolder. However, the message box at the end will always show me the LAST grid.id, regardless of the index I give it.
I've been working on this so long it's probably something stupid. Thanks in advance for the help.
'A subroutine that generates a map (list of grids)
Sub GenerateMap()
Dim reader As StreamReader = File.OpenText("map1.txt")
Dim gridHolder As New clsGrid
'The streamreader peeks at the map file. If there's nothing in it, a warning is displayed.
If reader.Peek = CInt(reader.EndOfStream) Then
MessageBox.Show("The map file is corrupted or missing data.")
reader.Close()
Else
'If the map file has information, X and Y counts are read
intXCount = CInt(reader.ReadLine)
intYCount = CInt(reader.ReadLine)
'Reads in grid properties until the end of the file
Do Until reader.Peek = CInt(reader.EndOfStream)
gridHolder.TerrainType = CInt(reader.ReadLine)
gridHolder.MovementCost = CInt(reader.ReadLine)
gridHolder.DefensiveBonus = CInt(reader.ReadLine)
gridHolder.ID = listMap.Count
listMap.Add(gridHolder)
Loop
reader.Close()
End If
End Sub
'This function returns a Grid object given an X and Y coordinate
Function lookupGrid(ByVal intX As Integer, ByVal intY As Integer) As clsGrid
Dim I As Integer
Dim gridHolder As New clsGrid
'This formula finds the index number of the grid based on its x and y position
I = ((intX * intYCount) + intY)
gridHolder = listMap.Item(I)
MessageBox.Show(gridHolder.ID.ToString)
Return gridHolder
End Function
A: In GenerateMap, your Do Until loop is adding a reference to the same clsGrid instance (gridHolder) to the list each time through. Since all of your list items are referencing the same instance, your message box shows the same results regardless of the index I.
You need to create a new instance of clsGrid each time through the loop. One way to do this is to add the line "gridHolder = New clsGrid" as the first line in your loop. You can then also delete the word "New" from your existing Dim statment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trying to 'merge' partial data in 2 or more rows with MySql I have a database with three tables, one with titles, one with authors and a join table that combines the two. Most of the titles have one author, but some have more than one. I am able to return the rows I want, but the titles with more than one author return a row for each title, one having one author and one with the other author as you might expect. Is there I way I can combine the authors into one row?
Here is my statement
SELECT DISTINCT t.id, t.title, t.notes,
a.lastname, a.firstname, a.middlename
FROM titles t, author a, authortitle at
WHERE t.title LIKE '".$letter."%'
AND at.author_id_fk = a.id
AND at.title_id_fk = t.id
$letter is the first letter of the title.
A: Try this;
SELECT t.id, t.title, t.notes,
GROUP_CONCAT( CONCAT(a.lastname, a.firstname, a.middlename) SEPARATOR ', ') AS author
FROM titles t, author a, authortitle at
WHERE t.title LIKE '".$letter."%'
AND at.author_id_fk = a.id
AND at.title_id_fk = t.id
GROUP BY t.id
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xcode Array to TableView I was making a simple application that has a button. When clicked, it moves to another ViewController. As I load the new ViewController with a table view in it, I access the server that outputs a string that I place into an array. In the did load function, the Array was successfully read. BUt when I place the array to be processed by the table functions, the program shuts down..
here is my code..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *psalmCell = [tableView dequeueReusableCellWithIdentifier:@"psalmcell"];
//create a cell
if(psalmCell == nil)
{
psalmCell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"psalmcell"];
}
//fill contents
psalmCell.textLabel.text = @"Psalm";
psalmCell.textLabel.text = [listItemsR objectAtIndex:indexPath.row];
//return
return psalmCell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return listItemsR.count;
}
- (void)viewDidLoad {
NSURL *url = [NSURL URLWithString:@"http://sample.stie.com/sample.php"];
NSString *response_string = @"";
//
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"retrievePending" forKey:@"command"];
[request startSynchronous];
response_string = [request responseString];
NSLog(@"JSON : %@",response_string);
listItemsR = [[NSArray alloc] initWithArray:listItemsR];
listItemsR = [response_string componentsSeparatedByString:@":"];
NSInteger arCount = listItemsR.count;
NSLog(@"%d",arCount);
for(NSInteger i=1; i<arCount; i++){
NSString *final = [listItemsR objectAtIndex:i];
NSLog(@"%@",final);
}
[listItemsR release];
}
PLease do help me!! Im really confused here.. ^^,, Thanks!!! By the way Im using Xcode 3.2.6 with iOS SDK 4.x
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pointer Memory Allocation Issue Trying to allocate memory for the bobby array but it's not working. Why?
I expected the bobby pointer to be allocated for 5 spaces but when I run and look in local it only has one.
#include "queue.h"
#include <iostream>
using namespace std;
int main()
{
// Create the queue
CustomQueue* obj = new CustomQueue(5);
int astar[100];
int* bobby;
bobby = new int[5];
// Place numbers into the queue
obj->push(50);
obj->push(40);
obj->push(30);
obj->push(20);
obj->push(10);
return 0;
}
A: I think that maybe you are intending to do
int bobby[5];
then you will see all elements together in a debugger. Otherwise you see bobby as the pointer to the value, and in visual studio you will need to type something like
bobby,5 to see all 5 elements.
if you are doing this statically, you may as well put it on the stack.
also
int bobby[5];
sizeof(bobby) = 20 (assuming 4 B/int)
but
int* bobby;
sizeof(bobby) = 4.
A: Your debugger (I'm assuming that's what you mean by "look in local") only knows that the bobby pointer is a pointer to a single integer. The debugger does not understand the following allocation new int[5]. This is due to the way pointers and arrays work in C++, and is not due to incorrect code on your part.
You may be able to instruct your debugger to display more following elements of the array you allocated, but the way to do that would be specific to whatever tools you're using.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Including external C library with Xcode I have a built C static library (the Antlr 3 C library). It is installed properly and works (i.e., I can run gcc -o parser lexer.c parser.c -lantlr3c just fine).
In Xcode, however, I get an error. I've added -lantlr3c in the "other linker flags" build setting.
ld: library not found for -lantlr3c
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1
Several other questions I've found here (1, 2, 3, 4) generally have answers targeting Xcode 3. I'm using Xcode 4.1, in an iOS static library project. I'm currently building the unit test stuff.
EDIT: As requested by @LaceySnr, the output from verbose gcc and Xcode's error.
The output from gcc:
$ gcc -v -o parser.o BFMathParser.c BFMathLexer.c -lantlr3c -arch i386
Using built-in specs.
Target: i686-apple-darwin11
Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2335.15~25/src/configure --disable-checking --enable-werror --prefix=/Developer/usr/llvm-gcc-4.2 --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-prefix=llvm- --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin11 --enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2335.15~25/dst-llvmCore/Developer/usr/local --program-prefix=i686-apple-darwin11- --host=x86_64-apple-darwin11 --target=i686-apple-darwin11 --with-gxx-include-dir=/usr/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)
/usr/llvm-gcc-4.2/bin/../libexec/gcc/i686-apple-darwin11/4.2.1/cc1 -quiet -v -iprefix /usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1/ -D__DYNAMIC__ BFMathParser.c -fPIC -quiet -dumpbase BFMathParser.c -mmacosx-version-min=10.7.0 -mtune=core2 -auxbase BFMathParser -version -o /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccistonB.s
ignoring nonexistent directory "/usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1/../../../../i686-apple-darwin11/include"
ignoring nonexistent directory "/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/../../../../i686-apple-darwin11/include"
#include "..." search starts here:
#include <...> search starts here:
/usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1/include
/usr/local/include
/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
GNU C version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00) (i686-apple-darwin11)
compiled by GNU C version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00).
GGC heuristics: --param ggc-min-expand=150 --param ggc-min-heapsize=131072
Compiler executable checksum: edef36ecca2ce3f93d0f78610b5af911
/usr/llvm-gcc-4.2/bin/../libexec/gcc/i686-apple-darwin11/4.2.1/as -arch i386 -force_cpusubtype_ALL -o /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccqP9bOO.o /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccistonB.s
/usr/llvm-gcc-4.2/bin/../libexec/gcc/i686-apple-darwin11/4.2.1/cc1 -quiet -v -iprefix /usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1/ -D__DYNAMIC__ BFMathLexer.c -fPIC -quiet -dumpbase BFMathLexer.c -mmacosx-version-min=10.7.0 -mtune=core2 -auxbase BFMathLexer -version -o /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccistonB.s
ignoring nonexistent directory "/usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1/../../../../i686-apple-darwin11/include"
ignoring nonexistent directory "/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/../../../../i686-apple-darwin11/include"
#include "..." search starts here:
#include <...> search starts here:
/usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1/include
/usr/local/include
/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
GNU C version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00) (i686-apple-darwin11)
compiled by GNU C version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00).
GGC heuristics: --param ggc-min-expand=150 --param ggc-min-heapsize=131072
Compiler executable checksum: edef36ecca2ce3f93d0f78610b5af911
/usr/llvm-gcc-4.2/bin/../libexec/gcc/i686-apple-darwin11/4.2.1/as -arch i386 -force_cpusubtype_ALL -o /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccepo2q0.o /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccistonB.s
/usr/llvm-gcc-4.2/bin/../libexec/gcc/i686-apple-darwin11/4.2.1/collect2 -dynamic -arch i386 -macosx_version_min 10.7.0 -weak_reference_mismatches non-weak -o parser.o -lcrt1.10.6.o -L/usr/lib/i686-apple-darwin11/4.2.1 -L/usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1 -L/usr/llvm-gcc-4.2/bin/../lib/gcc -L/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1 -L/usr/lib/gcc/i686-apple-darwin11/4.2.1 -L/usr/llvm-gcc-4.2/bin/../lib/gcc/i686-apple-darwin11/4.2.1/../../.. -L/Developer/usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/../../.. /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccqP9bOO.o /var/folders/5v/9rvx60c17vl7kc3b_r8gz0wc0000gn/T//ccepo2q0.o -lantlr3c -lSystem -lgcc -lSystem
The output from Xcode:
Libtool /Users/bf/Library/Developer/Xcode/DerivedData/Calculator-dggaoccanosfnrampxhlfrbuuyoi/Build/Products/Debug-iphonesimulator/libcalclib.a normal i386
cd /Users/bf/Desktop/calclib
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/libtool -static -arch_only i386 -syslibroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/bf/Library/Developer/Xcode/DerivedData/Calculator-dggaoccanosfnrampxhlfrbuuyoi/Build/Products/Debug-iphonesimulator -filelist /Users/bf/Library/Developer/Xcode/DerivedData/Calculator-dggaoccanosfnrampxhlfrbuuyoi/Build/Intermediates/calclib.build/Debug-iphonesimulator/calclib.build/Objects-normal/i386/calclib.LinkFileList -lantlr3c -ObjC -framework Foundation -o /Users/bf/Library/Developer/Xcode/DerivedData/Calculator-dggaoccanosfnrampxhlfrbuuyoi/Build/Products/Debug-iphonesimulator/libcalclib.a
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/libtool failed with exit code 1
A: Click your project in the navigator, select the appropriate target, and unfold the Linked Frameworks and Libraries section. Click the plus, click Add Other..., and browse to your static object.
You'll have to remove the -lantlr3c flag too.
A: You can use that in the other linker flags, but you also need to make sure the path is in the library search paths too.
Also make sure you're building with the right config (debug / release / whatever) — you can specify different libraries to link for each one, so if you've set it for debug but you're building release it obviously won't link.
A: When you test this lib with gcc on your Mac you are using the x86 version of it. The iOS linker does not find it because you probably did not build the arm version of the library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What Delphi components ship with unit tests? Given the popularity of unit testing, and the inclusion of DUnit with Delphi, has this been embraced by any component vendors who have released their source along with a suite of unit tests?
I'm looking for examples to share with other developers.
A: DWScript ships with a large collection of DUnit-based tests, most of them "hand-made", and also leverages Delphi Code Coverage (see also the DCC Wizard project).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to Add Listeners to RadioButtons in EXTJS4 I'm very new to ExtJs and I wanted to display an alert box on clicking one of the radio buttons, but it does not seem to work. Could anyone guide me through this step? The listener does not seem to work.
{
xtype: 'radiogroup',
fieldLabel: 'Does Nodes have DHCP IP Scheme?',
id:'dhcpRadio',
columns: [50, 50],
// Arrange radio buttons into two columns, distributed vertically
columns: 2,
vertical: true,
items: [{
boxLabel: 'Yes',
name: 'rb',
inputValue: 'yes',
listeners: {
check: function(rb,value){
if(value=='yes')
alert('yes');
else alert('no');
}
}
},{
boxLabel: 'No',
name: 'rb',
inputValue: 'no',
checked: true
}]
}
A: Like Gregory just said, Radio does not have a click event.
You could try the change event instead:
listeners: {
change : function(rb, newValue, oldValue, options) {
if( newValue === 'yes') {
alert('Yes')
} else {
alert('No')
}
}
}
See the API documentation for details.
A: Radio do not have a click event
Instead of the listeners try this:
handler: function(ctl, val) {
alert("ddd");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mongodb mongoose unit of maxDistance In my application, I am trying to use,
RentModel.find({prop_location : { $near : [msg.lat, msg.lng],
$maxDistance : 500}}, function(err, docs){}
I have only one value in the database with latitude, longitude of san
francisco.
Now,
*
*
*
*When there is no maxDistance => It finds out the location
perfectly from anywhere.
*When I add maxDistance as 5 and search exactly at the same
location (with same latitude, longitude), it does not find the
location.
*If it is 50, same as point 2.
*If it is 500, I can even find the location from London.
What's wrong ?
what is the unit of distance ?
I want to find out everything within 5km (kilometer) distance.
will db.executeCommand solve my problem ? need to check.
Thanks in advance.
A: You need to divide the maxdistance value by 111.12 (one degree is approximately 111.12 kilometers) to convert the degree radius to km distance.
so you can try this
RentModel.find({prop_location : { $near : [msg.lat, msg.lng], $maxDistance : 500/111.2}})
But the same works different is sphere queries, there you have to divide the degree radius by earth-radius 6371 to work with km values
A: Finally I found the answer to my problem.
Theoretically longitude is x-axis and latitude is y-axis. But we are used to latitude- longitude rather than longitude-latitude...
So the way I was searching was wrong
$near : [msg.lat, msg.lng]
When I changed this to $near : [msg.lng, msg.lat] , it started working even with 5KM... So ordering was the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: execute mail function automatically on specified time, php-jquery I've a page with php script to list viewers info like browser,time they were viewing etc and save those details into a info.txt file which is stored in the server. I'd prefer to collect all the details from info.txt and mail me every day at specified time. I hope there should be a better way to do it with php-jquery.Thanks
A: If your server is a Linux server, it would be pretty easy to set up a cron job to send that file to you via email at a specified time daily/weekly/monthly.
You could either write a PHP script that can be called in the cron job, or you can also just create a cron job that uses a cli mail client.
A: PHP and jquery is the wrong tool for that - you would need a cron job or something on your webserver that does the work periodically.
Why don't you just RSS instead? you don't fill your mailbox with information outdated the next day, and your rss-feed is always up-to-date. Most browsers or email programs already have an RSS reader build in, and you can also set them to poll the feed either daily or on demand.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent File Now Available Popup Excel I have a problem here that I've been working on for hours.
I'm importing an Excel file, and I use this code to do it:
Dim objExcel As Excel.Application
Dim objWorkBook As Excel.Workbook
Dim totalWorkSheets As Excel.Worksheet
Dim ExcelSheetName As String = ""
objExcel = CreateObject("Excel.Application")
objWorkBook = objExcel.Workbooks.Open(excelfile, Notify:=False)
objExcel.DisplayAlerts = False
Dim exConS As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & excelfile & ";Extended Properties=Excel 8.0;"
For Each totalWorkSheets In objWorkBook.Worksheets
ExcelSheetName += totalWorkSheets.Name
Dim exCon As New OleDbConnection(exConS)
Dim dsExcel As New DataSet()
exCon.Open()
Dim sExcel As String = "SELECT * FROM [" & totalWorkSheets.Name & "$]"
Dim daExcel As New OleDbDataAdapter(sExcel, exCon)
daExcel.Fill(dsExcel)
exCon.Close()
Next totalWorkSheets
objWorkBook.Close()
objExcel.Quit()
Dim ggProcess As New Process
ggProcess = Process.Start("EXCEL.EXE")
ggProcess.Kill()
The problem is that the following dialog box keeps appearing when I run the code:
How can I prevent this pop-up dialog box from appearing?
A: As poweruser has suggested can simply change
objWorkBook = objExcel.Workbooks.Open(excelfile, Notify:=False)
to
objWorkBook = objExcel.Workbooks.Open(excelfile, Notify:=False, Readonly:=True)
Ok since that didn't work I've taken a more detailed look at the code and think your issue is because you are opening the excel file, then creating an external connection to it. The file does not have to be open in order create an OLEDB connection to it.
It appears that you don't know the tab names in advance so you need to open the file to get the tab names?
If so I would create a method to open the file get the tab names and return an array of the tab names which you can then iterate through in your code above, then close the file.
A: Use Set
let TWB as workbook
Set TWB=workbooks.open(Filename:="\\......", Readonly:=false, notify:=False)
make TWB as nothing at the end of the Sube procedure.
A: From my investigation if you use the creation of excel and quitting in fast succession, it will not immediately close the previously quit excel object. I noticed that after the xlApp.Quit, it takes a while before the real EXCEL.exe process is gone even if I have done all the cleanup (closing the worksheet, setting Excel COM object to nothing).
The solution worked for me especially during testing where you execute the Excel import / export function in fast succession.
Note that my code was derrived from the following link.
Function Excel_Conversation()
On Error GoTo Proc_Err
Dim xlApp As Excel.Application, _
booLeaveOpen As Boolean
'if Excel is already open, use that instance
booLeaveOpen = True
'attempting to use something that is not available
'will generate an error
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
On Error GoTo Proc_Err
'If xlApp is defined, then we
'already have a conversation
If TypeName(xlApp) = "Nothing" Then
booLeaveOpen = False
'Excel was not open -- create a new instance
Set xlApp = CreateObject("Excel.Application")
End If
'Do whatever you want
Proc_Exit:
On Error Resume Next
If TypeName(xlApp) <> "Nothing" Then
xlApp.ActiveWorkbook.Close False
If Not booLeaveOpen Then xlApp.Quit
Set xlApp = Nothing
End If
Exit Function
Proc_Err:
MsgBox Err.Description _
, , "ERROR " & Err.Number & " Excel_Conversation"
'comment next line after debugged
Stop: Resume
Resume Proc_Exit
End Function
A: Whilst others have, understandably, pointed out issues in the OP's methodology, I've been looking for a solution to the issue since a recent Office update started causing the same problem in Excel 2010, for an "application" for which I'm responsible - where the dialog is being generated spuriously and the file is available for reading. The solution - is:
Application.DisplayAlerts = False
Set oBook = Application.Workbooks.Open(Filename:=strFilename, ReadOnly:=False, Notify:=False)
Application.DisplayAlerts = True
To reiterate, this successfully stops the spurious File Now Available dialog for both this and subsequent loads, as long as it is actually spurious. If it's not spurious, your routine will likely error.
A: You can set to the Excel.Application visible and display alerts to false:
Dim objExcel As Excel.Application
objExcel.Visible = False
objExcel.DisplayAlerts = False
...
Then when you close the books the file no available alert will not appear
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: springSecurityService is null in base controller This is a rather weird problem and I been at it for a while so I am going nuts.
I have a controller extending another controller so I can have multiple controllers inheriting a method and they go something like this:
class EventController extends EventAwareController {
def springSecurityService
def edit = {
// this line prints out principal id
println springSecurityService.principal.id
def eventInstance = getAuthorizedEventById(params.id)
if (!eventInstance) {
flash.message = "${message(code: 'event.not.found.message')}"
redirect(action: "list", controller: "event")
return false
}
}
class EventAwareController {
def eventService
def springSecurityService
def getAuthorizedEventById(def eventId) {
def event
if (eventId) {
// this springSecurityService is null and throws an error
event = eventService.findAuthorizedEvent(eventId, springSecurityService.principal.id)
if (event) {
session.eventId = eventId
}
}
return event
}
}
EventAwareController is throwing:
java.lang.NullPointerException: Cannot get property 'principal' on
null object at
com.ticketbranch.EventAwareController.getAuthorizedEventById(EventAwareController.groovy:14)
but my prinln statement in EventController prints principal id without any issues?!? So springSecurityService is injected as null in EventAwareController?
Any ideas? suggestions? Thanks.
A: You have the field in both classes, and this is a problem when using Groovy. Dependency injection in Grails is typically done like you're doing, with def <beanname>. This is a public field, so Groovy creates a public getter and setter for it and makes the field private. The getter isn't used, but Spring sees the setter and since beans are configured to be wired by name (as opposed to by type) the bean is injected since there's a match between the setter name (setSpringSecurityService) and the bean name.
Since you have this twice, you have two setters and one wins, so you'll have a null value for the private field in one class.
But like any public (or protected) property the dependency injection is inherited, so just remove it from all of your subclasses and leave it in the base class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Ensuring that memory cache is properly invalidated So I have a piece of code that looks like the following:
uint8_t *buffer = <16 MB memory region>
uint32_t count = 1024;
uint32_t position = 0;
uint8_t *get_data() {
uint8_t *region = buffer + position * 16;
position += 1;
position %= count;
do {
__sync_synchronize();
} while (reigon[0] != 1);
return region;
}
The buffer in question is being written to by a hardware device. At some point (maybe before we started looping, maybe after we've started), the hardware will write to that location, as well as to the rest of the buffer.
I'm currently using __sync_synchronize to issue a memory barrier, because I would like to ensure that there is no way that the compiler would cause the rest of that memory region to be cached from any time before region[0] == 1.
I'm aware that I could mark the entire buffer as volatile. However, I'd like to be able to return a non-volatile buffer from this function.
So, is there any way to do a __sync_synchronize, but only have it target the range of memory that I specify. In this case the memory from [region, region + 1024)?
As an aside, this code is living in userspace. The memory buffer is a pinned region of memory that I've allocated with a kernel module, mapped into userspace, and told a FPGA to eventually DMA to it. This is essentailly attempting to implement a polling mechanism on the FPGA finishing a DMA tranfer.
A: A region-limited memory fence would be a fairly unusual architectural feature. However, you only need the fence after the loop has terminated:
while (*(volatile uint8_t *)region != 1)
;
__sync_synchronize();
return region;
A: This should do the trick:
uint8_t *get_data() {
uint8_t *region = buffer + position * 16;
volatile uint8_t *volatile_region = region;
position += 1;
position %= count;
do {
} while (volatile_region[0] != 1);
return region;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is there a shorter code to join the keys and values for a dictionary? Is there a shorter or better snippet that accomplishes the following:
>>> h = { 'apple' : 'ipad' , 'amazon': 'kindle' }
>>> [' '.join(item) for item in zip( h.keys(), h.values())]
[ 'apple ipad', 'amazon kindle' ]
A: >>> [' '.join(item) for item in h.iteritems()]
['amazon kindle', 'apple ipad']
>>> map(' '.join, h.iteritems())
['amazon kindle', 'apple ipad']
But avoid using map() these days. And list comprehensions if you can help it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to virtualize config file I have a PHP script that is encrypted with Ion Cube. Since I don't want to violate the license, I can't modify anything in the script.
The script makes calls to an XML based config file.
I want to create a database to store the config data and then feed it to the encrypted script based on the referer URL that made the request.
Basically, I want to "virtualize" the config XML file so I can feed the encrypted script the data I want based on the referer URL.
Any ideas?
A: You can use LD_PRELOAD and a custom library to override the php interpreter's file open of the config file and so switch it to open a different config file on demand.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to pass sql transaction to methods in different classes? I'm working with ASP.NET(VB.NET), SQL 2008 Project. I need to write data to more than one table with methods in different classes. I have to ensure all the data is written using one transaction so I'm using the older method (not a TransactionScope) So do i have to pass the connection & transaction both to the methods from main method (what if im using TransactionScope) ?
A:
So do i have to pass the connection & transaction both to the methods from main method
Yes. Also, any commands that you create have to have both their connection and transaction properties assigned to the connection/transaction, respectively, that you've passed along.
(what if im using TransactionScope)
Infinitely easier. You can just open a new transaction scope in your main, and then any methods that need to be enlisted in the transaction scope can just open a new transaction scope with the option TransactionScopeOption.Required and they will automatically enlist in the ambient transaction from main. You don't need to pass anything around.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Query for time attendance : min and max hours group by day Somebody can help me.
I have eventime field type datetime in mysql
ex. eventime record:
2011-09-01 10:29:37
2011-09-01 10:50:04
2011-09-01 17:10:45
2011-09-02 08:30:01
2011-09-02 .....
2011-09-02 .....
2011-09-03 .....
2011-09-03 .....
2011-09-03 .....
.....
2011-09-30 08:15:10
2011-09-30 11:40:44
2011-09-30 15:50:40
2011-09-30 17:50:11
I want to query with result first login and last login group by day.
ex:
Day | first login | last login
-----------+----------------+-------------
2011-09-01 | 10:29:37 | 17:10:45
2011-09-02 | 08:30:01 | 17:15:00
2011-09-03 | 07:10:45 | 17:10:12
2011-09-14 | 07:50:25 | 16:12:45
.......
2011-09-30 | 08:15:10 | 17:50:11
Can help me how code query in mysql group by date or eventime?
Thanks
A: This should do the trick:
SELECT
MIN(login_time) AS `first login`,
MAX(login_time) AS `last login`
FROM
login_table
GROUP BY
DATE(login_time)
A: select min(eventtime) AS min_event_time, max(eventtime) AS max_event_time FROM table;
A: something similar to this
select min(eventtime) as sTime, max(eventtime) as eTime
from yourtable
group by [someuseridorsomethingcolumn]
where [useridcolumn] = 'anActualUserID'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to load photos from photo gallery and store it into application project? I'm working on an application that is almost the same as the sample codes i found here. But the method i want to do is different from the sample codes.
Link: PhotoLocations
The first screen will have an ImageView and 2 buttons (Choose Photo, Confirm).
When the 'Choose Photo' button is tapped, it will navigate to another screen which retrieves photos from my iPad's photo gallery. When a photo is chosen, it will dismiss the current screen and return to the first screen displaying the chosen photo on the ImageView.
When the 'Confirm' button is tapped, the photo will be stored into my application's project (e.g. /resources/images/photo.jpg).
May i know how can i do this?
A: This will take you to the image gallery and you can select the image.
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePickerController animated:YES completion:nil];
this will help you select the image
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
// Dismiss the image selection, hide the picker and
//show the image view with the picked image
[picker dismissViewControllerAnimated:YES completion:nil];
//UIImage *newImage = image;
}
And then you can store this image to the documents directory...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
For clicking the image yourself use this
- (IBAction) takePhoto:(id) sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:imagePickerController animated:YES];
}
A: UIImagePickerController *cardPicker = [[UIImagePickerController alloc]init];
cardPicker.allowsEditing=YES;
cardPicker.delegate=self;
cardPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:appDelegate.cardPicker animated:YES];
[cardPicker release];
And this delegate method will return the image u select from the album
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
noImage.image=img;
}
A:
- (IBAction)UploadPhoto:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Please Select Your Option"delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Camera", @"Gallery",nil];
[actionSheet showInView:self.view];
UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *clickedButtonPath = [jobstable indexPathForCell:clickedCell];
isSectionIndex = clickedButtonPath.section;
isRowIndex = clickedButtonPath.row;
}
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
NSLog(@"From didDismissWithButtonIndex - Selected Option: %@", [actionSheet buttonTitleAtIndex:buttonIndex]);
NSString*image=[actionSheet buttonTitleAtIndex:buttonIndex];
if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Camera"]) {
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"Device Camera Is Not Working" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
return;
}
else{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Gallery"]){
UIImagePickerController *pickerView = [[UIImagePickerController alloc] init];
pickerView.allowsEditing = YES;
pickerView.delegate = self;
[pickerView setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
[self presentViewController:pickerView animated:YES completion:nil];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage* orginalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:isRowIndex inSection:isSectionIndex];
UITableViewCell *cell = [jobstable cellForRowAtIndexPath:indexPath];
UIImageView *tableIMAGE=(UIImageView *)[cell.contentView viewWithTag:19];
tableIMAGE.image=orginalImage;
answersARRAY[indexPath.row] = [NSString stringWithFormat:@"-1,%@,%@,",answersARRAY[indexPath.row],imageStris];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Preprocessor macro value to Objective-C string literal I have a preprocessor macro defined in build settings
FOO=BAR
That value I want to massage into an Objective-C string literal that can be passed to a method. The following #define does not work, but it should demonstrate what I am trying to achieve:
#define FOOLITERAL @"FOO" //want FOOLITERAL to have the value of @"BAR"
myMethodThatTakesAnNSString(FOOLITERAL);
I expect that I am just missing the obvious somehow, but I cannot seem to find the right preprocessor voodoo to get what I need.
A: Use the stringizing operator # to make a C string out of the symbol. However, due to a quirk of the preprocessor, you need to use two extra layers of macros:
#define FOO BAR
#define STRINGIZE(x) #x
#define STRINGIZE2(x) STRINGIZE(x)
#define FOOLITERAL @ STRINGIZE2(FOO)
// FOOLITERAL now expands to @"BAR"
The reason for the extra layers is that the stringizing operator can only be used on the arguments of the macro, not on other tokens. Secondly, if an argument of a macro has the stringizing operator applied to it in the body of the macro, then that argument is not expanded as another macro. So, to ensure that FOO gets expanded, we wrap in another macro, so that when STRINGIZE2 gets expanded, it also expands FOO because the stringizing operator does not appear in that macro's body.
A: A convenient macro OS_STRINGIFY(s) is predefined in SDK's /usr/include/os/base.h, which is included in Foundation.framework.
So you can use the following code without additional definitions.
myMethodThatTakesAnNSString(@OS_STRINGIFY(FOO));
A: Here's a modified version of Adam Rosenfield's answer with clearer semantics:
#define NSStringize_helper(x) #x
#define NSStringize(x) @NSStringize_helper(x)
I use it to replace code like this:
case OneEnumValue: name = @"OneEnumValue"; break;
case AnotherEnumValue: name = @"AnotherEnumValue"; break;
with this:
#define case_for_type(type) case type: name = NSStringize(type); break
case_for_type(OneEnumValue);
case_for_type(AnotherEnumValue);
A: You need to define preprocessor macro like,
FOO=\@\"BAR\"
And use code side like,
[NSString stringWithFormat:@"macro: %@", FOO];
A: What error are you seeing exactly? This type of thing does work as you expect:
#define kMyString @"MyString"
[NSString stringWithFormat:@"macro: %@", kMyString];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: running FxCop in NAnt on VS 2010 project I'm trying to set up a CI tool using NAnt.
I have managed to have NAnt build the project
I've created the .FxCop file for the project, but when I inserted the FxCop commands in the Nant Build configuration, I received
[exec] Loading C:\projects\BuildingSolution\BuildingSolution.FxCop...
[exec] Failed loading FxCop project.
[exec] Error text: Project version is incompatible with current application version..
the project and solution is made from Visual Studio 2010 on .NET 4.0
NAnt version is 0.91-alpha2
FxCop version is 10
The settings that I inserted:
<target name="runFxCop">
<exec program="c:\devtools\fxcop10\fxcopcmd.exe"
commandline="/p:${FxCop.Filename} /o:${Build.OutputFolder}Latest\fxcop-results.xml"
failonerror="false"/>
</target>
The error message says that the project is not supported, but I've seen posts that talks about FxCop supporting .Net 4.0.
I'm not sure whether I'm configuring it wrong or it's not supported at the moment.
Can anyone help me with this?
A: Try setting the nant.settings.currentframework property like this:
<property name="nant.settings.currentframework" value="net-4.0" />
A: Ditto @TrueWill - try to get it running via the command line to ensure it works, then integrate it into your nant scripts.
However I have chosen an alternative method of running this analysis for my projects as the FxCop command line runner produces different results than the IDE Code Analysis runner (namely because FxCop doesn't support the new phoenix engine), and I wanted the build server to enforce the same rules as were run in the IDE.
I used the process as described in this blog to set up my environment. This also gave me the ability to relax the rules for my unit test projects. When the build task is run, the code analysis results are written to a CodeAnalysisLog.xml file for each project. My CI server then simply checks these logs for the report.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is the tableview being scrolled after adding into a uialertview and seting pagingEnabled as NO? I add a UITableview into a UIAlertview, and set the pagingEnabled as NO, but when I dragged the table, it is still scrolling/paging left or right! Why? I found that in iPhone 3GS, it can not to be scrolled/paged, but in iPhone 4, it can be scrolled/paged. Why is this so?
A: First of all, although UITableView is a subclass of UIScrollView and thus has pagingEnabled property, UITableViews don't actually support paging, thus setting that property has little effect.
UITableViews normally shouldn't scroll horizontally. If it does, then most likely the UITableView frame is out of its bounds.
A: Pay attention that the UIAlertVidw's frame in ios has limit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605865",
"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.