text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Is there a way to find the size of the area in a bitmap which has been filled using the bitmapdata.floodfill method? Basically, I am using the floodfill method to colour-in sections of a bitmap image. That part is easy enough but the issue comes in with the way I am adding an effect to the colour fill routine.
To add the effect, first a copy of the bitmap data is created and floodfill is used on that instead of the original bitmap. Then the bitmapdata.compare method is used to set the alpha value of everything apart from the filled-in section to 0 and the result is saved in another bitmapdata. After that, a 1 px radius circle sprite is added to the stage and is being tweened to the image dimensions and its mask is set to the sprite which contains the result of the compare operation.
This works perfectly except for the fact that the fill sprite has to be tweened to the complete image dimensions irrespective of how small the area is being coloured-in since I am not able to find a way to get the dimensions of the fill area. I am doing an bitmap image update at the end of the tween and I have to disable user interaction till the tween is complete to avoid the errors which come in if another fill-in operation is started before the base image has been updated. If I could somehow get the dimensions of the fill area then the time during which I have to disable the user interaction will go down considerably.
Any ideas?
A: What about getColorBoundsRect? I don't know if your fill color will be present in other parts of your bitmap, but it might do the trick.
A: I think getColorBoundsRect is exactly what you need. You choose a colour and get the bounding box of that colour in the bitmap.
A: Write your own fill routine. As you fill in the pixels, store the dimension info you need. Simplest would be to just store the bounding box. You fill by finding neighboring pixels of the appropriate color, and any time such a move takes you out of working bounding box, adjust.
More complex could store a bitmap. Any way you choose, the point is that you will get what you need more readily by not working around what wasn't designed for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: xml parsing is faster in C/C++ or Java? I need to parse XML either in C/C++ or Java.
Which one is fast?
I think SAX parser will be ok with java
Pl. help
A: Generally C++ is compiled to native code while java is compiled to byte code and then is interpreted at runtime. Therefore C++ code should theoretically run fater.
But due to automatic memory management and other good features java development is much easier and faster. The big question is do you really ned some extraordinal performance requirements here? If not, implement everything in java. If you do have such requirements think about other options.
And BTW, why SAX? It is the hardest (and really fastest) whay to parse XML. Did you problably think about easier ways like JAXB? It requires 1% of efforts (relatively to SAX).
A: SAX parser is ok with Java.
But it is not connected to the Java/C++ performance comparison. SAX parsers are faster than DOM ones. But C++ and Java both have XML parsers for SAX and DOM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: .load() jquery with JSP and Access Database I have got a situation where I call .load() with a jsp which returns a html table and values extracted from database.
Every time there is a change through insert, update or delete, .load() is called.
function showResponse(responseText, statusText, xhr, $form)
{
var success = "Success";
var updated = "Updated";
var deleted = "Deleted";
if(responseText.substr(0,7) == updated)
{
document.getElementById('editForm').reset();
document.getElementById('editFormDiv').style.display = 'none';
retrive();
return;
}
if(responseText.substr(0,7) == success)
{
document.getElementById('addBeneficiary').reset();
document.getElementById('otherBank').style.display = 'none';
document.getElementById('bene_name').focus();
document.getElementById('editFormDiv').style.display = 'none';
retrive();
return;
}
if(responseText.substr(0,7) == deleted)
{
retrive();
return;
}
}
function retrive()
{
$('#updateEditResults').load('retriveBeneficiaryDetails.jsp?process=u');
$('#updateDeleteResults').load('retriveBeneficiaryDetails.jsp?process=d');
}
Now whenever I call it after delete and update, the updated database (with record deleted / edited) is shown. But after insert sql statement the changes are not reflected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dump terminal session to file? I run gnome-terminal with unlimited scroll-line history
I want to dump text I can see in terminal to file and parse it
Is there a way to do it?
A: If you want the whole contents of the terminal history:
In the gnome-terminal menu, Edit > Select All and then Edit > Copy. (Or use your favorite keyboard shortcut for the copy.)
Then paste anywhere.
If you want just part of the history, select with your mouse and then copy.
A: You could use the unix script command to capture things as you go.
A: If it's the output of a program that you want to capture and parse, simply redirect (>) it into a file
program_with_lots_of_output > output.log
and then parse it. Append a 2>&1 to that if you want standard error as well.
If you want a screen capture (i.e. including input), use the script program.
A: You may want to use the 'tee' command. Tee bifurcates out stdout and makes a copy out the output in a file. So you can see the output and have the output stored also. Example:
ls | tee ls_out
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: android: webservice image replace with images in Local folder I am into final stage of chat application in android.
I am facing few issues while working with images and web service.
So when i select the image and sent that image to web service i get URL from service. How can i convert that url into image that is in my local folder. I am confused how can i make this working.
I want to display the selected image in list view along with message returned from web service.
Please guide me in this issue. Is there another option to work this issue.
Thanks.
A: Use this method:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
connection.setReadTimeout(120000);
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Here You need to pass the URL of the image to the function and you can set the image as setImageBitmap function.
A: use this method to convert url into image Bitmap bi=convertImage(url);, mention your image sizes in this line
bit=Bitmap.createScaledBitmap(bm,120, 120, true);
public Bitmap convertImage(String url)
{
URL aURL = null;
try
{
final String imageUrl =url.replaceAll(" ","%20");
Log.e("Image Url",imageUrl);
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(new PatchInputStream(bis));
if(bm==null)
{}
else
bit=Bitmap.createScaledBitmap(bm,120, 120, true);
return bm;
}
catch (IOException e)
{
Log.e("error in bitmap",e.getMessage());
return null;
}
}
Set returned bm(bitmap) to your ImageView imageview.setImageBitmap(bi)
feel free to ask doubts
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Payment APIs in android Is there any google payment APIs for android like we are having "paypal" ?
And
I want to implement credit card payment process in my android application. There is a form in my application. User will enter his card information and on submission the service will verify and accept or reject the card. I have no idea if there is any API or a tutorial available in android. Please help me if someone knows how to do that.
A: You might consider the Temboo Android SDK, which provides normalized access to a large number of APIs. It includes modules for interacting with both Stripe (https://www.temboo.com/library/Library/Stripe/) and PayPal (https://www.temboo.com/library/Library/PayPal/ProcessDirectPayment/)
The SDK is an open download, which you can grab at https://www.temboo.com/download although you'll need a (free) Temboo account to do anything with it.
(Full disclosure: I work at Temboo)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: My app isn't closing correctly and I'm not sure why First off, I'm using the Action Bar. When I go back to my Main class after pressing the Home option, then press the Back button, my app won't close like it should. Instead, it tries to open the activity it left from, but since I'm calling finish(), it just animates like it's switching activities and then shows my Main class. After this, I can press the Back button and properly close the app. If I don't press the Home option and use the Back button from my second activity, everything works like it should.
Intent leading back to my Main class.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(First.this, Second.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(item);
}
A: Try using intent.addflags(flags) not using intent.setflags(flags)...!!!!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how to reserve vector space for class objects? If I have a class's header file like the following:
class arrayStack
{
private:
struct StackNode
{
StackNode(int p, int v):previous(p),value(v){}
~StackNode(){std::cout<<"destructor calledn"<<std::endl;}
int previous;
int value;
};
public:
static const int STACKSIZE=100;
static const int NUMSTACK=3;
static int indexUsed;
arrayStack();
~arrayStack();
void push(int stackNum, int val);
int top(int stackNum);
void pop(int stackNum);
bool isEmpty(int stackNum);
vector<StackNode*> buffer;
int stackPointer[NUMSTACK];
};
Here is the content of cpp file:
void arrayStack::push(int stackNum, int val)
{
int lastIdx=stackPointer[stackNum];
stackPointer[stackNum]=indexUsed;
indexUsed++;
buffer[stackPointer[stackNum]]=new StackNode(lastIdx,val);
}
int arrayStack::top(int stackNum)
{
return buffer[stackPointer[stackNum]]->value;
}
basically, I know that I need to store STACKSIZE*NUMSTACK StackNode* in the vector buffer (I know I just use an array here). Now, I wonder how I could reserve large enough space for buffer in the ctor.
Here is what I tried:
buffer.reserve(STACKSIZE*NUMSTACK*sizeof(StackNode*))
but it seems not working, because in the client code, when I tried:
arrayStack tStack;
for(int i=0;i<3;i++)
for(int j=0; j<10;j++)
{
tStack.push(i,i+j);
}
the program crashed due to vector assignment over subscript.
A: It sounds like want to use the resize function, rather than reserve.
Also, as mentioned in a comment, the argument to the function is the number of elements, not the number of bytes.
If you call buffer.resize(23), it will give you a vector of 23 null pointers, which you can then read/modify using square brackets.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Name sorting using counting sort I'm having trouble sorting names in alphabetical order using counting sort, for instance I'm suppose to sort in alphabetical order and have number input added to it for example 0001 Alex Smith, Gregory John, Alex Smith, Adam Richard, Alex Ryan. The output should be in this order:
Adam Richard
Alex Ryan
Alex Smith
Gregory John
My code so far:
public class Names
{
//private static int[] c;
public ArrayList<String> getUserInput()
{
ArrayList<String> names = new ArrayList<String>();
Scanner in = new Scanner(System.in);
while (in.hasNext())
{
names.add(in.next());
System.out.println(names);
}
in.close();
return names;
}
private static CountingSort(int A[], int B[], int k[])
{
int i;
int C[0];
for(i = 0; i <= k; i++){
C[i]=0;
}
for(int j=1; j <= A.length; ){
C[A[j]] = C[A[j]] + 1;
}//C[i] now contains numbers of elements equals to i
for(int i=1; i < k; i++){
C[i] = C[i] + C[i - 1];
}
for(int j = A.length; j--){
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
}
}
A: Preparing Data
a. Make lengths of each string equal. Add ‘*’ at the end of each string to make all lengths equal.
Modified Data — [‘a*’, ‘bd’, ‘cd’, ‘ab’, ‘bb’, ‘a*’, ‘cb’]
b. Convert this modified data strings into numbers by assigning positional values to letters. a-z to 1–26 and * to 0. So this becomes 2-dimensional array.
Converted Data — [[1,0],[2,4],[3,4],[1,2],[2,2],[1,0],[3,2]]
Counting Sort
*
*Create Count Array of n-dimensions
where n=length of longest string (in this case 2) and,
number of columns in each dimension = maximum value in ‘Converted Data’ (in this case 4) +1(added for ‘*’).
So, a count array of 5x5 is created.
For example — if the longest length of string was 5 and highest character ‘f’ then an array of 7x7x7x7x7 would be created.
And just like normal count array, store values based on ‘Converted Data’. For example, for [1,0] the value stored is 2.
Count Array
*Cumulate this n-dimensional array starting from [0,0] all the way to [4,4].
*Now similarly use the ‘Converted Data’ with Count Array to determine the position of each string in sorted array. For ex. — [1,0] (a*) the position is 2.
And similarly after determining position, subtract 1 from that value in count array. So value at [1,0] in Count array becomes 1. Similarly position of [2,4] (bd) is 5 in sorted array.
https://playcode.io/475393
A: Counting sort is the wrong sorting algorithm for this problem. The counting sort algorithm is designed to sort integer values that are in a fixed range, so it can't be applied to sort strings.
On the other hand, you could use radix sort for this problem. Radix sort works by sorting the input one digit or character at a time, and it's very well-suited for sorting strings. There are two general flavors of radix sort - most-significant-digit radix sort and least-significant-digit radix sort. The MSD flavor of radix sort isn't too reminiscent of counting sort, but LSD radix sort works by using counting sort one character at a time. If you really must use counting sort, I'd recommend investigating LSD radix sort as an option.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How should I Implement Localization on Wpf Application using MVVM pattern? I am working on a wpf application using Devexpress Tool and following MVVM pattern..
I have applied Localization on it using Locbaml Tool and it is working perfectly fine but just for the View.
In this app i am setting Grid Row Vlidation errors and also Popping some MessageBoxes from View Model but LocBaml is not looking helpful for converting these error messages and message boxes message in other languages. How can I accomplish this?
A: LocBaml only extracts stuff from baml, which is the compiled form of your xaml files. Anything not defined in xaml (eg, strings defined in code-behind) will never be seen by it. The only way around this that I'm aware of is to define all the strings you might want to localize as string resources in xaml. These can easily be referenced from code-behind, so it's not as bad as it sounds. Strings that are entirely dynamically generated won't be localizable, but with some work you can construct them from snippets defined in your xaml resources.
A: It's wrong to have messageboxes directly from the ViewModel. Instead you should raise events and let the view do the UI. Otherwise you couldn't unit test the ViewModel, and that's one of the main goals of the MVVM pattern.
A: If you are using .resx files to manage you translations, you can simply make them generate code (with Access Modifier: Public in the combo box at the .resx screen) and then make the VM send the messages directly to the view.
That way the underlying functionality of code-generated resource files will return the translated version of the desired text.
A: http://blogs.microsoft.co.il/blogs/tomershamam/archive/2007/10/30/wpf-localization-on-the-fly-language-selection.aspx check this. You can send localized text from VM by calling the translate method from the code. For example
LanguageDictionary.Current.Translate("resourceKey","value Name")
A: You can take a look at some software I wrote to do this:
http://tap-source.com/?p=232
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to change the background or foreground color of the visual studio 2010 tooltip I need to change the tooltip in visual studio 2010 when you hover your mouse over a code item when not debugging.
Obviously I am trying to theme my VS to be dark, but I cant seem to change this setting.
I have Powertools, Visual Assist X and Color Theme editor installed.
I can rule out Color Theme editor colors because it has a global edit function where I can make every setting black and it does not change.
I have tried
Tools->Options->Environment->Fonts and Colors->Signature Help Tooltip Background
It has no effect.
The foreground text is derived from windows window text color (i cant change this in windows as my theme relies on it)
Other tooltips in VS look fine
Solution explorer:
Parameter help is OK because the forecolor is darker:
It appears to be a WPF brush which gives me the impression that I cant change it with a simple color setting.
I would be happy with either background or foreground color change.
A: I no longer have 2010, but in 2013 you change foreground here
Tools->Options->Environment->Fonts and Colors->Editor Tooltip
Maybe its similar in 2010?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: regular expression to check if string is valid XML I am looking java code to check if a string is valid XML.
A: It's not possible to validate XML with regular expressions. XML is not a regular language.
Use an XML parser to try to parse the string as XML or else validate the XML document against a schema, for example a DTD or XSD file.
A: you can check whether document or text is well-formed, by using a parser.
i think this link will help you:
http://www.roseindia.net/xml/dom/DOMParserCheck.shtml
for string replace this line in the link:
InputSource is = new InputSource(xmlFile);
with
ByteArrayInputStream stringStream=new ByteArrayInputStream("XML Text".getBytes());
InputSource is=new InputSource(stringStream);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
}
|
Q: Jquery Unobtrusive validation lost after implementing onSubmit event I'm using ASP.NET MVC. My validation works well until I attached an event to the form's onSubmit event.
This is how my form looks:
@using (Html.BeginForm("Recover", "Auth", FormMethod.Post, new { Id = "RecForm", onSubmit = "return Events.Submit(this,event)" }))
{
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
<input type="submit" value="Recover" />
}
The Javascript (works fine, just put it here so you can check if something in this is causing the validation not to fire):
//Events
window.Events = (function () {
// Baseline setup
var Events = {};
function disableAllChildren(el) {
$(el).find(':input').attr('disabled', true);
}
function enableAllChildren(el) {
$(el).find(':input').attr('disabled', false);
}
//Ajax submit
Events.Submit = function (el, event) {
event.preventDefault();
//serialize the form before disabling the elements.
var data = $(el).serialize();
disableAllChildren(el);
$(el).find('.success, .error').hide();
$.ajax({
url: el.action,
type: 'POST',
data: data,
success: function (data) {
//Stuff happens.
}
});
};
return Events;
})(this, this.document);
How do I get back my validations?
A: What I do is to check if the form is valid before I submit it. See the below code :
$form = $("#myForm");
if (form.valid()) {
form.validate();
//other codes here
}
If the form is valid, then post your data. If not, do nothing.
A: There're more problems in your code than validation. Case is that disabled fields do not get posted to server. They do not participate in validation either. So, even if your code worked, you would get nothing posted to server side. Remove disableAllChildren(el); or recode it to not disable fields, but maybe make them readonly.
With this, they will get validated, but not surprisingly after the ajax submit. This is behavior you should not wish, so take a look at validate method. Especially you should be interested in part where it
Submits the form via Ajax when valid.
I believe that way validated form ajax submission can be done easier.
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
})
Or, just add validation checking right before ajax submit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set more than one html table in an aspx page in different alignments? I am having 5 table which I need to show in one page.
For that I have to show 2 tables in one row and other 3 in second row.
Is it possible to do this in C#? Or is there any other way to do fulfill requirement of getting so many input form user and not show so many tables in page and make it ugly
A: You can. Just use HTML to add it onto your aspx page like you would on a normal html page.
Open your ASPX page in Visual Studio, then down the bottom left of the screen you'll see 'source', click on that and add the tables in like a normal html page. You may need to add some CSS to the tables to make them stay on the one line.
A: I' not quite sure about what you mean. You can put these tables into another table as their container. Are your tables look like as belows:
<table>
<tr>
<td colspan="3">
<table id="table1" />
</td>
<td colspan="3">
<table id="table2" />
</td>
</tr>
<tr>
<td colspan="2">
<table id="table3" />
</td>
<td colspan="2">
<table id="table4" />
</td>
<td colspan="2">
<table id="table5" />
</td>
</tr>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7564996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to load a UserControl dynamically with LoadControl Method (Type, object[]) I am a bit new to user controls. my user control class is ucDefault . I dont have any constructors explicitly specified . I have to load my user control with the default constructor . How can i do it ?
A: Try,
Control control=LoadControl("~/UserControlFile.ascx");
My answers of threads posted by you:
*
*How to load a web usercontrol from a physical path rather than a virtual path
*Loading web user controls from blob storage in asp.net
Edit:
Here is a TestControl.cs located at App_code
public class TestControl : UserControl
{
public TestControl() { }
public TestControl(string message)
{
SayHello = message;
}
public string SayHello { get; set; }
public override void RenderControl(HtmlTextWriter writer)
{
base.RenderControl(writer);
writer.Write(SayHello);
}
}
and code to loads/creates a control object:
TestControl tc = (TestControl)LoadControl(typeof(TestControl), new object[] { "Hello Buddy" });
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to use VBO for morphing? I want to have a mesh that can be animated. I'm loading mesh from a file, including key frames. I want to put all the frames into VBO and compose two of them on the GPU in a vertex shader. So i want to pass to frames to GPU and some uniform that will allow to create one result frame from these two
Is it possible? If so, how can i do it?
A: You would just have more vertex attributes. Normally, you might have:
in vec3 position;
in vec3 normal;
in vec4 color;
in vec2 texCoord;
With morph targets, you would need:
in vec3 position0;
in vec3 position1;
in vec3 normal0;
in vec3 normal1;
in vec4 color;
in vec2 texCoord;
The actual model-space position would be a linear interpolation between position0 and position1. Same goes for the normal (I guess). Once you get them, you pass them through the usual transforms. The color and texture coordinates presumably don't change, but if they do, then they too need to have 0 and 1 versions.
The actual rendering is pretty simple. Presumably, you will have all the positions for the morph targets in the same buffer. So it's a matter of binding position0's attribute to the first morph target, and position1's attribute to the second morph target. Same goes for the normals. Then you render as normal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it possible to load Office documents in Blackberry using Browser Field and WP7? It is possible to load Office documents, PDF in UIWebView in iOS and I think same case applies to Android.
How about Blackberry and Windows ?
A: Regarding each platform:
*
*Yes, you can load PDF into a UIWebView in iOS
*No, you cannot with Windows Phone 7. If a PDF is navigated to, you are prompted to save it, which will then launch it in a dedicated viewer.
*For BlackBerry, I am not sure, it looks like it might be possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does column-oriented NoSQL differ from document-oriented? The three types of NoSQL databases I've read about is key-value, column-oriented, and document-oriented.
Key-value is pretty straight forward - a key with a plain value.
I've seen document-oriented databases described as like key-value, but the value can be a structure, like a JSON object. Each "document" can have all, some, or none of the same keys as another.
Column oriented seems to be very much like document oriented in that you don't specify a structure.
So what is the difference between these two, and why would you use one over the other?
I've specifically looked at MongoDB and Cassandra. I basically need a dynamic structure that can change, but not affect other values. At the same time I need to be able to search/filter specific keys and run reports. With CAP, AP is the most important to me. The data can "eventually" be synced across nodes, just as long as there is no conflict or loss of data. Each user would get their own "table".
A: The main difference is that document stores (e.g. MongoDB and CouchDB) allow arbitrarily complex documents, i.e. subdocuments within subdocuments, lists with documents, etc. whereas column stores (e.g. Cassandra and HBase) only allow a fixed format, e.g. strict one-level or two-level dictionaries.
A: In Cassandra, each row (addressed by a key) contains one or more "columns". Columns are themselves key-value pairs. The column names need not be predefined, i.e. the structure isn't fixed. Columns in a row are stored in sorted order according to their keys (names).
In some cases, you may have very large numbers of columns in a row (e.g. to act as an index to enable particular kinds of query). Cassandra can handle such large structures efficiently, and you can retrieve specific ranges of columns.
There is a further level of structure (not so commonly used) called super-columns, where a column contains nested (sub)columns.
You can think of the overall structure as a nested hashtable/dictionary, with 2 or 3 levels of key.
Normal column family:
row
col col col ...
val val val ...
Super column family:
row
supercol supercol ...
(sub)col (sub)col ... (sub)col (sub)col ...
val val ... val val ...
There are also higher-level structures - column families and keyspaces - which can be used to divide up or group together your data.
See also this Question: Cassandra: What is a subcolumn
Or the data modelling links from http://wiki.apache.org/cassandra/ArticlesAndPresentations
Re: comparison with document-oriented databases - the latter usually insert whole documents (typically JSON), whereas in Cassandra you can address individual columns or supercolumns, and update these individually, i.e. they work at a different level of granularity. Each column has its own separate timestamp/version (used to reconcile updates across the distributed cluster).
The Cassandra column values are just bytes, but can be typed as ASCII, UTF8 text, numbers, dates etc.
Of course, you could use Cassandra as a primitive document store by inserting columns containing JSON - but you wouldn't get all the features of a real document-oriented store.
A: In "insert", to use rdbms words, Document-based is more consistent and straight foward. Note than cassandra let you achieve consistency with the notion of quorum, but that won't apply to all column-based systems and that reduce availibility. On a write-once / read-often heavy system, go for MongoDB. Also consider it if you always plan to read the whole structure of the object. A document-based system is designed to return the whole document when you get it, and is not very strong at returning parts of the whole row.
The column-based systems like Cassandra are way better than document-based in "updates". You can change the value of a column without even reading the row that contains it. The write doesn't actualy need to be done on the same server, a row may be contained on multiple files of multiple server. On huge fast-evolving data system, go for Cassandra. Also consider it if you plan to have very big chunk of data per key, and won't need to load all of them at each query. In "select", Cassandra let you load only the column you need.
Also consider that Mongo DB is written in C++, and is at its second major release, while Cassandra needs to run on a JVM, and its first major release is in release candidate only since yesterday (but the 0.X releases turned in productions of major company already).
On the other hand, Cassandra's designed was partly based on Amazon Dynamo, and it is built at its core to be an High Availibility solution, but that does not have anything to do with the column-based format. MongoDB scales out too, but not as gracefully as Cassandra.
A: I would say that the main difference is the way each of these DB types physically stores the data.
With column types, the data is stored by columns which can enable efficient aggregation operations / queries on a particular column.
With document types, the entire document is logically stored in one place and is generally retrieved as a whole (no efficient aggregation possible on "columns" / "fields").
The confusing bit is that a wide-column "row" can be easily represented as a document, but, as mentioned they are stored differently and optimized for different purposes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "110"
}
|
Q: Adding node in Account settings tree of Thunderbirds account settings dialogue I am developing a Thunderbird add-on in which I want to add a node to every mail account in the account manager (opens when the user clicks on Tools->Account Settings). This node should show a panel with additional settings for the account.
I have seen that the tree in this dialog is not using XUL but JavaScript instead. So i did some changes to the JavaScript file but if tomorrow a new version comes out then their will be issues with my add-on. So I need to add the node as a XUL overlay but this doesn't see possible.
A: You cannot use XUL overlays to overlay content that is built dynamically. But fortunately, the account manager is explicitly extensible. There is even some documentation covering your exact case. In short, you need to create an XPCOM component and register it in mailnews-accountmanager-extensions category. The account manager will then load your component and call showPanel() method for each account to determine whether you want your panel to be displayed for this account. You need to set chromePackageName and name properties appropriately, the panel will be loaded from chrome://chromePackageName/content/am-name.xul and panel name from chrome://chromePackageName/locale/am-name.properties. Please note that starting with Thunderbird 4 XPCOM components need to be registered in chrome.manifest.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android resource diectory name to string for WavFile usage I am using the Wave tools downloaded from here: http://www.labbookpages.co.uk/audio/javaWavFiles.html
To begin to read a wav file in my res/raw directory I have done the following in a sub class which extends my main activity.
WavFile wavFile = WavFile.openWavFile(new File(context.getResources().openRawResource(R.raw.xsp11_10db).toString()));
Where context is defined as:
Context context;
The first line returns a NullPointerException, so it seems the type of class WaveFile (wavfile) returns null. Which brings to question the way I define the File string:
new File(context.getResources().openRawResource(R.raw.xsp11_10db).toString());
I know it is a crude way to obtain the resource wavfile "xsp11_10db", but I am unaware of any other methods to access the file. I tried with URI's but the directory was not found.
Does anyone know of a better way to read the wave file from resource, or what is causing my null pointer exception.
Any help would be appreciated, thankyou in advanced.
A: It looks like Wav API you are using does not support InputStream, and only accepts File as input. This is understandable, because most likely they use RandomAccessFile for implementation.
You probably thought that .openRawResource(...).toString() would give you file name, but that is not true. It will just call .toString() on InputStream returned from openRawResource(...). Which is not what you want.
The solution is to open InputStream using openRawResource() and copy data to a new file on SD card yourself. And then use that file for Wav API you are using.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I stop Py_Initialise crashing the application? From VBA and VB6 I'm calling a dll the creates a Python interpreter. If I set the PATH environment variable to point to "C:\python27" and PYTHONPATH to "c:\python27\lib" all is fine.
If I don't set the PATH then calling Py_Initialise() crashes XL or my VB6 app, even if I call Py_SetProgramName with "c:\python27\python27.exe" first.
I'd like to specify the installation in VB/VBA rather than having it set in the environment as I can't do that in XL (works ok for VB6).
A: The best answer I've found so far is that it is a bug in Python - http://bugs.python.org/issue6498. The intepreter seems to call exit() on certain errors rather than passing a code back to the caller. Not very friendly if you're embedding python in an app. But there you go.
A: try to change the working directory before calling the dll:
In your VBA code:
chdir("c:\python27\") '- change the working-directory for python
=> call dll '- call the dll
chdir(app.Path) '- change back to your folder (maybe you want to save your current folder bevore you change it the first time and change back to this?!)
regards Thomas
A: You can simply check if the needed environment variable is set:
dim PPath as string
PPath = trim(Environ("PYTHONPATH"))
if (PPath<>"")
<call dll>
else
msgbox ("Error!")
end if
Or you can run the dll in a nother Test-Process: if this call works you know that it is OK to call the dll - it depends on the DLL call your using so I'm not sure about that:
Private Declare Function CloseHandle Lib "kernel32" (ByVal _
hObject As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal _
dwDesiredAccess As Long, ByVal bInheritHandle As _
Long, ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
Const STILL_ACTIVE = &H103
Const PROCESS_ALL_ACCESS = &H1F0FFF
...
dim IsActive as boolean
dim Handle as long
Dim TaskID As Long
TaskID = Shell("rundll32.exe pyton.dll Py_Initialise()", vbNormalNoFocus)
<wait for some time>
'- check if pyton.dll is still running
Handle = OpenProcess(PROCESS_ALL_ACCESS, False, TaskID)
Call GetExitCodeProcess(Handle, ExitCode)
Call CloseHandle(Handle)
IsActive = IIf(ExitCode = STILL_ACTIVE, True, False)
if (not IsActive) then
msgbox ("Error!")
else
<kill process>
<call dll normally>
end if
Regards Thomas
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can multiple threads write into a file simultaneously, if all the threads are writing to different locations? I am writing the code in c++. Can I run into any kind of race conditions or seg-faults?
A: There's no problem doing that from the point of view of the underlying system (for all systems I know). However, typically you would need to have completely separate file descriptors/handles. This is because the file descriptor maintains state, e.g. the current file position.
You also need to check the thread-safety of the particular C++ interface to the filesystem that you are using. This is needed in addition to the thread-safety of the underlying filesystem.
You should also consider the possibility that threaded I/O will be slower. The system may have to serialise access to the bus. You may get better performance from overlapped I/O or a dedicated I/O thread fed through a producer/consumer pipeline.
A: Another solution, depending on the size of the file and the system you're running on, is to use memory mapped files, ie. mapping the file into virtual memory. This would give you direct access to the file as if it was a piece of memory. This way, any number of threads can simply write to the memory region and subsequent calls to flush the mapping to disk (depending on your configuration of the memory mapping) will simply store the data on disk.
Do note, that due to adressing restrictions on 32 bit platforms, it will not be possible for you to map any file larger than usually 2-3 GB, depending on the architecture and the actual number of bits available to do virtual memory adressing. Most 64 bit systems have 48 bits or more available for this task, allowing you to map at least 256 TB, which I'd take it is more than sufficient.
A: It depends.
Files are not their handles, and streams are not files.
This three different concept must be clear.
Now, the operating system can open the file more times returning different handles, each of which have its own "position pointer". If the file is opened in "share mode" for both reading and writing, you can seek the handles where you want and read/write as you like. The fact you don't overwrite depends on you. The system grants the sequentiality of the operations either for the entire file or for part of it (but more information on the operating system are required)
If every handle is attached to a different stream, each stream will write independently of the other. But -in this case- there is the complication of "buffering" (writing can be delayed and read can be anticipated: and can be longer as the one you ask: make sure you manage eventual overlap properly by flushing as appropriate)
A: Sure you can. Race condition may occur depending on how you are writing actual code(ie using that file). Also, if IO is buffered strange things may appear if buffered regions overlap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Sample code for progressive video streaming on Android? Is progressive video streaming in the Android Media Player possible?? if yes then can anyone please provide me with a sample code for the same?
thanks
A: It's rather simple. You able to use setDataSource method of MediaPlayer or SetPath of VideoView.
Hope it's helpful for you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: OSX su command issue So I cant get su command to work on a terminal. All I do is type "su" and press enter, it asks for the password and I enter my currently logged in user password. It always gives this error. I swear this used to work earlier, not sure what happened.
su: Sorry
I am running a Mac OSX 10.7.1 (Lion). Anyone know what could be wrong? I am entering the right password.
A: sudo su
will do the trick in Mac Os X terminal :)
A: There is no root account on mac osx. Just go sudo bash then type the command or commands you want as root.
A: If sudo stops working because permission to read sudoers is missing, this solution from kahisv.com solves the problem:
Check if the permissions are still correct, that's how it should be:
$ ls -lad / /private /private/etc
d--xrwxr-t+ 36 root wheel 1292 25 sty 12:34 /
If this is wrong in your case, boot in Single-User Mode (hold cmd+s while booting) and enter theese commands:
# /sbin/fsck -fy
# /sbin/mount -wu /
# /bin/chmod 1775 /
# /bin/sync
# exit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: hide textbox control using javascript or jquery I want to hide textbox control using javascript or jquery.I have used javascript
document.getElementsByName('Custom_Field_Custom1').style.display="none";
java console shows me this error :
document.getElementsByName('Custom_Field_Custom1').style.display="none" is undefined.
Please help me
A: getElementsByName returns an array. You either want to use an ID and call getElementById, or use getElementsByName('Custom_Field_Custom1')[0].
A: $('input:text') would select all textboxes in the page.
Hence, $('input:text').hide(); would hide all your textboxes.
If you need to hide a single textbox you can give it an id, as in <input type="text" id="Custom_Field_Custom1" />
$('#Custom_Field_Custom1').hide(); would then hide that single one.
A: getElementsByName returns a NodeList not an HTMLElementNode. It doesn't have a style property, so you get the error because undefined.display isn't allowed.
Loop over the NodeList as if it was an array.
A: Well seems all the possible answer comes here. I just simplified the answer :
for change CSS with jquery use following code :
$('#Custom_Field_Custom1').css('display','none');
For hide the text box with jquery use following code :
$('#Custom_Field_Custom1').hide();
In both case remember one thing here "Custom_Field_Custom1" must be id of the textbox.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android aSyncTask and starting another activity I've got this inner class as part of an application which doesn't accept changes in orientation (it makes more sense in landscape orientation).
private class initialDBQuery extends AsyncTask<SQLiteDatabase, Void, Cursor> {
@Override
protected Cursor doInBackground(SQLiteDatabase... params) {
final SQLiteDatabase mDatabase = params[0];
mCursor = mDatabase.rawQuery("SELECT * FROM database", null);
return mCursor;
}
@Override
protected void onPostExecute(Cursor c){
ParentActivity.this.mCursor = mCursor;
ParentActivity.this.updateQuery();
mDatabase.close(); //Close database connection ASAP
}
// can use UI thread here
protected void onPreExecute() {
ParentActivity.this.mAnimalPager = null;
Toast.makeText(ParentActivity.this.getBaseContext(), "Loading Database...", Toast.LENGTH_SHORT).show();
}
}
My main UI has a number of buttons which lead to different activities, the function of which is to provide search criteria via intents to the main activity (ParentActivity) which will then perform a search. the rest of the main activity is a viewpager which dependsonthe cursor returned from the AsyncTask (the update of this is working fine).
My problem is that: with this code i, I press one of the onscreen buttons (launch another activity) while the asynctask is running then I get the error "Unable to pause activity".
what are the further steps I need to take to deal with the running of the AsyncTask when the app pauses?
thanks, m
A: The problem I was experiencing here was actually to do with the viewpager I have on the main activity.
As the AsyncTask was creating a cursor for the PagerAdapter i wasn't setting the adapter until it had finished. There is a known problem with ViewPagers and activity onPause when an adapter has not been set (see here).
To overcome this I modified my adapter to return 0 when there is no cursor available to the adapter:
public int getCount() {
// return the size of the cursor if it has been instantiated;
return (mCursor !=null) ? mCursor.getCount() : 0 ;
}
and added a setCurrentCursor method to the adapter. This way I was able to set the adapter up and bind it to the viewpager in onCreate and then add the cursor to the adapter when it became available from the ASyncTask;
public void setCurrentCursor(Cursor cu){
this.mCursor = cu;
this.notifyDataSetChanged();
}
Now all I have to do is call adapter.setCurrentCursor in the onPostExecute method of the ASyncTask passing in the created cursor.
Hope this helps.
Thanks,
m
A: first try to cancel the asynctask and then start another activity may be that work for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASIHTTPRequest and ASINetworkQueue and JSON Parsing //
// RootViewController.m
// JsonPetser33
//
// Created by ME on 9/26/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "RootViewController.h"
//
#import "SBJson.h"
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
//
@implementation RootViewController
//
@synthesize mNetworkQueue;
@synthesize mArrData;
//
- (void)viewDidLoad
{
[super viewDidLoad];
//adding right button
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@"Load"
style:UIBarButtonItemStyleDone
target:self
action:@selector(loadData)];
}
-(void) loadData{
//Stop anything already in the queue before removing it
[[self mNetworkQueue] cancelAllOperations];
//Creating a new queue each time we use it means we don't have to worry about clearing delegates or resetting progress tracking
[self setMNetworkQueue:[ASINetworkQueue queue]];
[[self mNetworkQueue] setDelegate:self];
[[self mNetworkQueue] setRequestDidFinishSelector:@selector(requestFinished:)];
[[self mNetworkQueue] setRequestDidFailSelector:@selector(requestFailed:)];
[[self mNetworkQueue] setQueueDidFinishSelector:@selector(queueFinished:)];
//create url request using ASIHTTPRequest
ASIHTTPRequest *request;
request = [ASIHTTPRequest requestWithURL:[NSURL
URLWithString:@"http://mikan-box.x10.bz/testing/json_test.php"]];
[[self mNetworkQueue] addOperation:request];
[[self mNetworkQueue] go];
}
//ASIHTTPRequest protocol?
- (void) requestFinished: (ASIHTTPRequest *)request{
//You could release the queue here if you wanted
if ([[self mNetworkQueue] requestsCount] == 0) {
//Since this is a retained property, setting it to nil will release it
//This is the safest way to handle releasing things - most of the time you only ever need to release in your accessors
//And if you an Objective-C 2.0 property for the queue (as in this example) the accessor is generated for you
[self setMNetworkQueue:nil];
}
//... Handle success
//parsing the data
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *dicTemp = [jsonParser objectWithData:[request responseData]];//parse json
mArrData = [dicTemp objectForKey:@"markers"];
//do something like loading data in table for now NSLog data
NSLog(@"markers: %@",mArrData); //here the app freezes can't click button etc for a few seconds//
NSLog(@"count %d",[mArrData count]); // how can i enhance it?
[jsonParser release];
NSLog(@"Request finished");
}
- (void) requestFailed:(ASIHTTPRequest *)request{
//You could release the queue here if you wanted
if ([[self mNetworkQueue] requestsCount] == 0) {
[self setMNetworkQueue:nil];
}
//... Handle failure
NSLog(@"Request failed: %@",[[request error] localizedDescription]);
}
-(void) queueFinished:(ASIHTTPRequest *) queue{
//You could release the queue here if you wanted
if ([[self mNetworkQueue] requestsCount] == 0) {
[self setMNetworkQueue:nil];
}
NSLog(@"Queue finished");
}
//
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc
{
[mNetworkQueue reset];
[mNetworkQueue release];
[super dealloc];
}
@end
*
*im new to objective-c and to ios.. i use the ASIHTTPRequest because it already has a httphandler..
*the problem is when i do http request from the url given(its json) it freezes during parsing and displaying "NSLog(@"markers: %@",mArrData)".. is there a way i could improve this code?
*i would like to improve this code like doing it in another thread just like the ASINetworkQueue done for the url request
*i heard about gcd (Grand central dispatch) but dont know how or even if it is useful..
*thanx in advance
A: Have you tried not using an ASINetworkQueue and just using a simple ASIHTTPRequest and using startAsynchronous? For example:
NSURL *url = [NSURL URLWithString:@"http://mikan-box.x10.bz/testing/json_test.php"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
If you have multiple requests you can use [request setTag:tag] to differentiate them in requestFinished:.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Check if fields exist in other table I have two queries, one is to check the no. of times the STUDENTNO exists in the table Subjects
SELECT COUNT(*) AS COUNT
FROM Subjects R
INNER JOIN students w W ON R.studentno = W.studentno
WHERE R.studentno = '89514'
Next is to get the valid students (whose name and student no doesn't exist in the table SUBJECT):
SELECT DISTINCT W. *
FROM STUDENTS W
LEFT JOIN SUBJECTS R ON W.STUDENTNO + w.NAME = R.STUDENTNO + r.NAME
WHERE R.STUDENTNO + r.NAME IS NULL
I didn't get any output here. I still need to get those whose STUDENTNO exist in the SUBJECT table, but I guess this doesn't retrun it. Help. Please. Thanks
A: Couple suggestions for your second query:
*
*use meaningful table aliases! Why is Students aliased to be W ??
*if you want to join on multiple columns - do so separate, not by concatenating together two columns... also: is StudentNo a primary key?? If so: checking for the primary key to match would be sufficient - no need to add an extra condition that doesn't add any value to the JOIN.....
Try this:
SELECT DISTINCT stu.*
FROM Students stu
LEFT JOIN Subjects sub ON stu.StudentNo = sub.StudentNo AND stu.Name = sub.Name
WHERE sub.StudentNo IS NULL
or if StudentNo is the primary key, then maybe this will do:
SELECT DISTINCT stu.*
FROM Students stu
LEFT JOIN Subjects sub ON stu.StudentNo = sub.StudentNo
WHERE sub.StudentNo IS NULL
Does that return anything??
A: The first query can be simplified to:
SELECT COUNT(*)
FROM Subjects
WHERE StudentNo = '89514';
The second can probably be simplified to:
SELECT *
FROM Students
WHERE StudentNo NOT IN (SELECT StudentNo FROM Subjects);
This formulation does assume that the names in the Subjects table match the names in the Students table. The design of the database is (seriously) flawed if the student name is recorded in the Subjects table too. For instance, you can't update the name in the Students table without also updating the matching rows in the Subjects table - which is bad.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPad Split View Call/Load from another view Please help me with the issue mentioned below.
My issue is, whether there is way to call the split view from another view, say after I tap on a button..?
For eg, as shown in the attached pic, when the app launches, it shows the first screen.
When the user taps on "Click" button, the split view opens up.
The user is able to perform all operations of the split view and when he presses the Home Button, he should be taken back to the first screen.
Is this possible..? How can I go about it..?
I am a beginner. Any help with code would be greatly appreciated..
PS: I have tried using MGSplitView and TOSplitView, but have not been able to achieve the solution to the above mentioned issue.
Thanks...
A: Check the foll code. This should easily help you to solve your issue.
//Intialise the 2 views root and detail
RootViewController * rootVC = [[RootViewController alloc] initWithStyle:UITableViewStylePlain];
//To show the nav bar for root, add it into a UINavigationController
UINavigationController * rootVCNav = [[UINavigationController alloc] initWithRootViewController:rootVC];
DetailViewController * detailVC = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
//initialise split view
splitVC = [[UISplitViewController alloc] init];
splitVC.viewControllers = [NSArray arrayWithObjects:rootVCNav,detailVC, nil];
//Tell the split view that its delegate is the detail view.
splitVC.delegate = detailVC;
//tell root that the changes need to be shown on detail view.
rootVC.detailViewController = detailVC;
[rootVC release];
[detailVC release];
[rootVCNav release];
//Here, we get the app delegate object of the project
ProjectAppDelegate * appDel = (ProjectAppDelegate*)[[UIApplication sharedApplication] delegate];
//get window object of the delegate
UIWindow * window1 = [appDel window];
//get the navigation controler of the window of app delegate.
mainNav = [appDel rVC];
//remove the current view from the window.
[mainNav.view removeFromSuperview];
//add the split view to the window
[window1 addSubview:locSplitVC.view];
Hope this helps you..
Regards,
Melvin
A: i m do this type but i am not get split view
*
*(void)viewDidLoad
{
[super viewDidLoad];
MainViewController *first =[[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
UINavigationController *sec=[[UINavigationController alloc]initWithRootViewController:first];
DetailViewController *detail =[[DetailViewController alloc]initWithNibName:@"DetailViewController" bundle:nil];
UINavigationController *detailv =[[UINavigationController alloc]initWithRootViewController:detail];
UISplitViewController *split =[[UISplitViewController alloc]init];
split.viewControllers=[NSArray arrayWithObjects:sec,detailv, nil];
// split.delegate=detail;
split.delegate =self;
//first.detail=detail;
appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];
window1 = [appDel window];
UINavigationController *mainNav =[[UINavigationController alloc]init];
mainNav = [appDel nav];
[mainNav.view removeFromSuperview];
[window1 addSubview:split.view];
// Do any additional setup after loading the view from its nib.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java multiple selection dialog box I have a dialog box with a drop down menu like this:
Object[] possibilities = {"1", "2", "3", "4"};
ImageIcon icon = new ImageIcon("images/middle.gif");
int i = Integer.parseInt((String)JOptionPane.showInputDialog(pane,"How Many Channels:","Reset Visible Channels",
JOptionPane.PLAIN_MESSAGE,icon,possibilities,"1"));
The problem is that it only lets you select one option. Instead, I would like
for users to be able to select multiple options from a list that is given in
the dialog box. Something like the following:
Object[] possibilities = {"apples", "oranges", "lemons", "grapes"};
ImageIcon icon = new ImageIcon("images/middle.gif");
String s = (String)what do i put here instead of JOptionPane.showInputDialog(); ?
Can anyone show me how to alter this code so that it does what I am asking?
It would be nice to know what some of my various format options are. And I would really appreciate any links to some good articles on the topic. The articles I have found from my google searches are not very informative. I might be using the wrong key words.
A: JList is also a good alternative for multiple selections.
A: I would suggest a JTable with 2 columns. The first one is Boolean class based and the second one is text for the boolean.
A: you probably needed JCheckBox or JRadioButton tutorial shows similair example as you ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to use hashmap value to textview in android? i have one hashmap.hashmap have different value.
i want to display hashmap value in textview.
my code is
Iterator iterator = objJMap.keySet().iterator();
while (iterator.hasNext())
{ String key = (String) iterator.next();
String value1 = objJMap.get(key); }
how it display in textview?
A: you want display all hashmap value in a textview? textview set value in java code like this:
textview.setText(value1);
A: You have to create run time text view in while loop and put the value in it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ABPersonPickerNavigationController and UITabbarController How can we use use ABPersonPickerNavigationController on suppose the third tab of the UITabbarcontroller.
Actually I am showing all Address book contacts in this controller...so I use ABPersonPickerNavigationController
Currently I am using this code but when we click on third tab of UITabbarcontroller.. this controller will present and we can not see that UITabbar..
Here is my code..
-(void)viewWillAppear:(BOOL)animated
{
// creating the picker
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
// place the delegate of the picker to the controll
picker.peoplePickerDelegate = self;
// showing the picker
[self presentModalViewController:picker animated:NO];
// releasing
[picker release];
}
So what can I do so that both the ABPersonPickerNavigationController and UITabbarcontroller can be seen...
Please help me to solve this problem..
Thanks in advance...
A: Instead of
[self presentModalViewController:picker animated:NO];
Try this
[self.navigationController pushViewController:[[picker viewControllers] objectAtIndex:1] animated:NO];
Check your Controller Structure. UINavigationController is needed.
UITabBarController - UINavgationController - UIViewController
But I recommend make custom people picker controller using AddressBook Framework not AddressBookUI.
Without customizing, you can change only a few factor.
A: Try adding some code like this in the app delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UITabBarController *tabBar = [[UITabBarController alloc] init];
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
tabBar.viewControllers = [NSArray arrayWithObjects:viewFor1stTab, viewForSecondTab, picker, nil];
[self.window add subview tabBar.view];
replace viewFor1stTab, viewForSecondTab with the views you want for those tabs.
Please read the documentation, this is probably the most basic function of UITabBarController.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Don't understand this Rails error message I'm using code downloaded from a book called Agile Web Development with Rails 4th edition. It provides code for Rails 3.05 and Rails 3.1. I'm using the latter... I don't understand the error message it produced when I tried to load it in the server.
I'd be grateful if you can explain for a newbie..
This is the index created for the Product
<h1>Listing products</h1>
<table>
<% @products.each do |product| %>
<tr class="<%= cycle('list_line_odd', 'list_line_even') %>">
<td>
<%= image_tag(product.image_url, :class => 'list_image') %>
</td>
<td class="list_description">
<dl>
<dt><%= product.title %></dt>
<dd><%= truncate(strip_tags(product.description),
length: 80) %></dd>
</dl>
</td>
<td class="list_actions">
<%= link_to 'Show', product %><br/>
<%= link_to 'Edit', edit_product_path(product) %><br/>
<%= link_to 'Destroy', product,
confirm: 'Are you sure?',
method: :delete %>
</td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New product', new_product_path %>
This is the error message
SyntaxError in Products#index
Showing /Users/michaeljohnmitchell/Sites/peep/app/views/products/index.html.erb where line #15 raised:
compile error
/Users/michaeljohnmitchell/Sites/peep/app/views/products/index.html.erb:15:
syntax error, unexpected ':', expecting ')'
length: 80) );@output_buffer.safe_concat('</dd>
^
/Users/michaeljohnmitchell/Sites/peep/app/views/products/index.html.erb:23:
syntax error, unexpected ':', expecting ')'
confirm: 'Are you sure?',
^
/Users/michaeljohnmitchell/Sites/peep/app/views/products/index.html.erb:23:
syntax error, unexpected ',', expecting ')'
Extracted source (around line #15):
12: <dl>
13: <dt><%= product.title %></dt>
14: <dd><%= truncate(strip_tags(product.description),
15: length: 80) %></dd>
16: </dl>
17: </td>
18:
Trace of template inclusion: app/views/products/index.html.erb
Rails.root: /Users/michaeljohnmitchell/Sites/peep
Application Trace | Framework Trace | Full Trace
app/views/products/index.html.erb:36:in `compile'
app/controllers/products_controller.rb:7:in `index'
A: Try using a ruby 1.8-style hash literal:
<%= image_tag(product.image_url, :class => 'list_image') %>
UPDATE: Since you are using ruby 1.8.7, not 1.9, all your hashes have to be in this format:
<%= image_tag(product.image_url, :class => 'list_image') %>
<%= truncate(strip_tags(product.description), :length => 80) %>
<%= link_to 'Destroy', product, :confirm => 'Are you sure?', :method => :delete %>
Plus any other hashes you us in the future.
A: The options must be an hash for image_tag @ http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag
<%= image_tag(product.image_url, :class => 'list_image') %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: upload images having an url I have a script to upload files to the server from your computer. It works fine and basically it's a
<form enctype="multipart/form-data" action="post_img_upload.php?id='.$topicid.'" method="POST">
<input name="uploaded_file" type="file" />
<input type="submit" value="Subila" />
then, the post_img_upload.php starts like this:
$target = "pics/";
$fileName = $target . $_FILES["uploaded_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom);
Now I want to have the option to upload a file having an url address. Another form basically with
<form action="post_img_url_upload.php?id='.$topicid.'" method="POST">
<input name="url" type="text" size="100" />
<input type="submit" value="Copiar"/>
I would like to have post_img_url_upload.php similar to the post_img_upload.php.
How can I approach that?
How can I basically write
$fileName = $target . $_FILES["url"]["name"];
? Is it doable?
Thanks!
A: AFAIK, no. The server would only get the url string, and then should try to fetch the image itself (instead of the image data being transferred from the client). You could google for "php external request" as there are a couple of ways to do it (cURL, remote file access, etc.).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to connect to a remote unix box from java and run unix script in it? I need help in writing java code that can connect to a remote UNIX box, and run a script on that box.
I have scoured the internet, but I have been unable to find proper documentation on how this can be accomplished.
Where is the best place to start reading about this ? What all should I know ?
Any help is appreciated. Thanks.
A: ssh is probably the best protocol to use for that sort of thing. It's more secure than telnet and can be set to up to use authentication keys so your code won't need to know (or ask the user) for the password to the remote box.
Java Secure Channel (JSch) is a popular pure Java implementation of the ssh protocol.
A: You can use telnet and/or ssh to connect to the box. Then you can send your command, as you would do it in a terminal. Look out for a telnet/ssh implementation for java with good documentation. Telnet should be simpler, but there is no encryption. Apache has a telnet implementation: http://commons.apache.org/net/
regards
Andreas
A: You could use Runtime.exec(java.lang.String)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to get template name in symfony I want to get my template name in my layout.php. please help me
<?php $module_name = $sf_context->getModuleName(); ?>
i'm using this above code to get module name, but how to get my current template name.
A: if you set the template in your action with the setTemplate() function you can just get the template name with getTemplate(). If you did¡nt assign a template in the action the get Template function will return null.
If you didn't modify the template associated to an action (by default the execute[Action] has a [action]Success.php template) you can make a function like this in your action:
$funcName = $this->getActionName();
--> find the first uppercase letter there starts the function name.
--> $new String() = [first letter of name in lowercase] . [rest of the name]
--> $String = string . "Success.php";
i'm not advanced enough in php to tell the exacte code but that's the algorithm.
Hope it helped you, good luck;
A: So symfony is a MVC framework your question belongs to sfView
/* layout.php e.g. */
var_dump($this->getTemplate());
See :
*
*http://www.symfony-project.org/api/1_4/sfView#method_gettemplate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: django null and empty string I find that when I insert nothing of a string form field through a form it captures it as an empty string ''.
However when I insert nothing of an integer form field through a form it captures it as [null].
Is this good practice? Should the string be null as well in the db?
A: It is good practice. If strings were allowed to be null, there would be two ways to have an empty string: null and "". This gives you multiple values to check against, which is inefficient and messy.
This is a Django convention, but is good practice in all applications, unless you have the need for null to mean something different than "".
A: It depends on the field.empty_strings_allowed attribute.
Some fields have it overridden to False. But CharField keeps it True, thus making Field._get_default return empty string as default — even if blank=True. The only way to get None as default is to have null=True on a field.
So if you have field in db that should never be null and not allow blanks to be never ever put in there by for e.g. objects.create. You need to put self.full_clean() — or other validation — in the model save method.
A: I think the string should be NULL too, but depends on your application see MySQL, better to insert NULL or empty string?.
If you want to store NULLs for an empty field, add null=True to the Field in question. See https://docs.djangoproject.com/en/dev/ref/models/fields/#null
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: How do I make a form background translucent? I want to use the code provided here (http://www.codeproject.com/KB/GDI-plus/LovelyGoldFishDeskPet.aspx)
to make a form background semitransparent using an alpha image. But I don't know how to implement the code. Can you help me, I just started my C# 3 hours ago. Please guide me.
Edit 1:
Look at the border of the inner image. I want my border to be like that.
A: I believe I know what you are trying to do now.
The code you were attempting to use is GDI+ based and uses Win32 calls...
If you can avoid that, then you definitely should.
The reason it probably won't build is because you havent included "using Microsoft.Win32" or something similar.
Either way, if transparent forms are what you are after there is a MUCH easier way that is supported by WinForms.
As per this article, the trick is to set a forms transparency key to the same thing as the forms back colour.
Try this in your FishForm() or equivilant constructor:
this.TransparencyKey = this.BackColor;
I'm pretty sure that will do the trick!
A: In the FishForm() function try placing:
this.Opacity = 0.5;
Inside. Normally that works, but I don't know how it will interact with the other drawing you have going on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: GWT/Gin creating class with @Inject annotation in constructor Let's say I have a class
public class Foo{
@Inject
public Foo(MessageBus messageBus, SomeServiceAsync service){
...
}
...
I have some doubt on how I would construct such a class, given that the constructor parameters are to be injected. Or must I somehow also get an instance of the Foo class through Gin (is that the case anyway for injection to take place)?
Thanks in advance
A: Your assumption is correct. You must get all Foos from Gin if you want them to have their constuctors injected. To get a Foo from Gin, you need to either have it injected into something else, or use a Ginjector. Usually you'll get only one class' instances (or a small number of classes' instances) from a Ginjector, and rely on Gin to inject all of their dependencies, and their dependencies' dependencies, and so on.
The Gin Tutorial is a great place to start.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How make font in TextView more thinner? I want to make font in TextView more thinner. How can I do it?
A: You can do this using a fontFamily:
From xml:
android:fontFamily="sans-serif-light"
Programmatically
textView.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
A: in android only four fonttype-face
TypeFace
Typeface.DEFAULT
Typeface.MONOSPACE
Typeface.SANS_SERIF
Typeface.SERIF
and font-type
Typeface.NORMAL
Typeface.BOLD
Typeface.BOLD_ITALIC
Typeface.ITALIC
you can use like as
textView.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
and other way is you can download any .ttf file and put it in asset folder and use like as this
Typeface type=Typeface.createFromAsset(context.getAssets(),
"DroidSansMono.ttf");
textView.setTypeface(type, null);
A: Have you tried this attribute in your layout xml?
android:height="10dp" //Use as many pixel as you want here
A: you can use another typeface as well if you want:
android:typeface="monospace"
or increase the size of the text :
android:textSize="15sp"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Which IDE can detect method1 from class1 object by inheritance? I am beginning CakePHP, but I need IDE for detect method of class that have 2 level extends.
I need IDE that detect method1 from class1 object.
A: NetBeans replaces the line number of method declarations with an indicator when a method is either overriding a method in another class or overridden by a method in another class.
Clicking it takes you to the line of the indicated method declaration in the other class.
A: See here and here for some good tips on getting Netbeans to recognise relations nicely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Alternate to PHP exec() function Currently I am using:
exec("zcat $filename", $output)
To uncompress a .Z type file but unfortunately my hosting company has now disabled this function.
Is there a workaround?
$pathtofile = "filename.lis.Z";
exec("zcat $pathtofile", $output);
A: .Z files are LZW compression. If you can't run shell commands on your host, you can use an LZW PHP library. Here are two:
*
*web wonders
*php-lzw
A: system($shell_command, $response_var);
So in your case:
system("zcat $filename", $output);
A: do this
echo ini_get("disable_functions");
to know if you are able to use one of the following:
system();
exec();
passthru();
shell_exec();
but if it's a shared hosting all the above are for sure blocked and you will have to find an alternative
A: In my case, disabled commands are
dl
sh2_exec
diskfreespace
disk_free_space
disk_total_space
escapeshellarg
escapeshellcmd
exec
highlight_file
link
lchgrp
lchown
passthru
pclose
popen
proc_close
proc_get_status
proc_nice
proc_open
proc_terminate
set_time_limit
shell_exec
show_source
symlink
system
mail
sendmail
So if one of those commands not blocked in your side, you may find a way to execute command.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: facebook oauth dialog not working in android 2.2(samsung GT-S5830) in a webview and web browser I am trying to implement facebook Oauth dialog(direct url approach)
http://developers.facebook.com/docs/reference/dialogs/oauth/
It works fine at all places except android in samsung GT-S5830 where it stops with the text
window.location.href="REDIRECT URL?code=code
even in the webview as well as in the webbrowser
A: After a bit of research, figured out that the problem is when display = 'touch'. It works fine with display='wap'.
But display='wap' has the following disadvantages
1) It always shows the allow access screen(even if the user has allowed the app)
2) Design looks distorted as compared to display=touch
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Virtual function calling mechanism class base {
public:
virtual void fn(){}
};
class der: public base {
public:
void fn(){}
};
der d;
base *b = &d;
b->fn();
When the compiler encounters the statement b->fn(), the following information is available to the compiler:
*
*b is a pointer to the class base,
*base class is having a virtual function as well as a vptr.
My question is: how does the vptr of class der come into picture at run time?
A: The Holy Standard does not require a vptr or a vptr table. However in practice that’s the only way this is implemented.
So here’s psudo-code for what happens:
*
*a_base_compatible_vtable_ptr = b->__vtable_ptr__
*a_func_ptr = a_base_compatible_vtable_ptr[INDEX_FOR_fn]
*a_func_ptr( b )
A main insight is that for an object of the der class the vtable pointer in the object will point to the der class’ vtable, which is compatible with the base class’ vtable, but contains pointers pointing to the der class’ function implementations.
Thus, the der implementation of the function is called.
In practice the this pointer argument passing in point (3) is typically optimized, special, by passing the this pointer in a dedicated processor register instead of on the machine stack.
For more in depth discussion see the literature on C++ memory model, e.g. Stanly Lippman’s book Inside the C++ Object Model.
Cheers & hth.,
A: When reasoning about this, it helps me to maintain a clear image of the memory layout of the classes, and in particular to the fact that the der object contains a base subobject that has exactly the same memory layout as any other base object.
In particular your base object layout will simply contain a pointer to the vtable (there are no fields), and the base subobject of der will also contain that pointer, only the value stored in the pointer differs and it will refer to the der version of the base vtable (to make it a bit more interesting, consider that both base and der did contain members):
// Base object // base vtable (ignoring type info)
+-------------+ +-----------+
| base::vptr |------> | &base::fn |
+-------------+ +-----------+
| base fields |
+-------------+
// Derived object // der vtable
+-------------+ +-----------+
| base::vptr |------> | &der::fn |
+-------------+ +-----------+
| base fields |
+-------------+ <----- [ base subobject ends here ]
| der fields |
+-------------+
If you look at the two drawings, you can recognize the base subobject in the der object, when you do base *bp = &d; what you are doing is obtaining a pointer to the base subobject inside der. In this case, the memory location of the base subobject is exactly the same as that of the base subobject, but it need not be so. What is important is that the pointer will refer to the base subobject, and that the memory pointed to has the memory layout of a base, but with the difference that the pointers stored in the object will refer to the der versions of the vtable.
When the compiler sees the code bp->fn(), it will consider it to be a base object, and it knows where the vptr is in a base object, and it also knows that fn is the first entry in the vtable, so it only needs to generate code for bp->vptr[ 0 ](). If bp refers to a base object then bp->vptr will refer to the base vtable and bp->vptr[0] will be base::fn. If the pointer on the other hand refers to a der object, then bp->vptr will refer to the der vtable, and bp->vptr[0] will refer to der::fn.
Note that at compile time the generated code for both cases is exactly the same: bp->vptr[0](), and that it gets dispatched to different functions based on the data stored in the base (sub)object, in particular the value stored in vptr, which gets updated in construction.
By clearly focusing on the fact that the base subobject must be present and compatible with a base object you can consider more complex scenarios, as multiple inheritance:
struct data {
int x;
};
class other : public data, public base {
int y;
public:
virtual void fn() {}
};
+-------------+
| data::x |
+-------------+ <----- [ base subobject starts here ]
| base::vptr |
+-------------+
| base fields |
+-------------+ <----- [ base subobject ends here ]
| other::y |
+-------------+
int main() {
other o;
base *bp = o;
}
This is a more interesting case, where there is another base, at this point the call base * bp = o; creates a pointer to the base subobject and can be verified to point to a different location than the o object (try printing out the values of &o and bp). From the calling site, that does not really matter because bp has static type base*, and the compiler can always dereference that pointer to locate base::vptr, use that to locate fn in the vtable and end up calling other::fn.
There is a bit more magic going on in this example though, as the other and base subobjects are not aligned, before calling the actual function other::fn, the this pointer has to be adjusted. The compiler resolves by not storing a pointer to other::fn in the other vtable, but rather a pointer to a virtual thunk (small piece of code that fixes the value of this and forwards the call to other::fn)
A: In a typical implementation there is only one vptr per object. If the object is of type der that pointer will point to the der vtable, while if it is of type base it points to the base vtable. This pointer is set upon construction. Something similar to this:
class base {
public:
base() {
vptr = &vtable_base;
}
virtual void fn(){}
protected:
vtable* vptr;
};
class der: public base {
public:
der() {
vptr = &vtable_der;
}
void fn(){}
};
A call to b->fn() does something similar to:
vtable* vptr = b->vptr;
void (*fn_ptr)() = vtpr[fn_index];
fn_ptr(b);
A: i found the best answer over Here..
A: Vptr is a property of the object, not of the pointer. Therefore the static type of b (base) does not matter. What does matter is its dynamic type (der). The object pointed to by b has its vptr pointing to der's virtual method table (vtbl).
When you call b->fn(), it's der's virtual method table that gets consulted to figure out which method to call.
A: The vptr is not "of the class", but of the "instantiated object".
When d is constructed, first the space for it is allocated (and contains the vptr as well).
Then base is constructed (and the vptr is made pointing to base vtable) and then der is constructed around baseand the vptr is updated to point to the der vtable.
Both the base and der vtables have entries for the fn() functions, and since the vptr refer t othe der one, when you call b->fn(), in fact what happens is a call to vptr(p)[fn_index]() is called.
But since vptr(p) == vptr(&d), in this case, a call to der::fn will results.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get all unique character of String in sql I have a Table with column firstName and lastName as String. Now want to take all unique first char of those column.my table have thousand of row in that table ,but i just want to have Is the any string function in SQL to do this?
One more thing I need to find only alphabets no special characters.As my table is big it contains firstname and lastname with special character i need to ignore them
EG:assume my table contains firstname entry as ::jack,tom,riddle,monk,*opeth
In that case my sql should return j,m,r,t
A: Try this:
SELECT DISTINCT LOWER(SUBSTR(firstName,1,1)) firstChars
FROM your_table
WHERE LOWER(SUBSTR(firstName,1,1)) IN
('a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z')
ORDER BY firstChars
A: If you are working on 10g or higher the RegEx version of the query requires a lot less typing :)
SELECT DISTINCT SUBSTR(firstName,1,1)
FROM your_table
WHERE REGEXP_LIKE(firstName,'^[[:alpha:]]')
/
You may want to apply UPPER() or LOWER() to smooth out mixed case results.
A: SELECT DISTINCT left(firstName,1) FROM table_name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Configuration for .Net application I have very little knowledge of .Net programming, i got my software developed on .Net platform, Now i have installed the software but it prompts an error like Error in LibraryManager.SelectActive(),I have my database configured on local sql server and using windows authentication for it.THe xml configuration file is like <add key="ConnectionString" value="Password=;User ID=salman;Initial Catalog=LogoStick;Data Source=symbol;"/> with symbol as a DSN name.
Please tell me where i am doing it wrong ???
A: your connection string is
Server =myServerName\theInstanceName; Database =myDataBase; Trusted_Connection =True;
for the windows authentication
For refence you can check : Database Connectionstrings
for Connection strings : Connection strings for SQL Server 2005
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to install Maven Plug in into My eclipse How to install Maven PLug into My eclipse
Actually i followed this way please refer to the screen shots
below
http://imageshack.us/f/405/31444757.jpg/
http://imageshack.us/f/13/32898163.jpg/
Under Eclipse Find and Install New Software i used below paths
http://m2eclipse.codehaus.org/
http://m2eclipse.codehaus.org/update/
I am getting an error saying that , It could not find the repository .
Please tell me how to resolve this
A: The plugin homepage (http://www.eclipse.org/m2e/) states for this URL:
http://download.eclipse.org/technology/m2e/releases
Try it and luck!
A: Please follow this:
STEPS TO INSTALL MAVEN (in Eclipse):
Maven Eclipse plugin installation step by step:
1. Open Eclipse IDE
*Click Help -> Install New Software...
*Click Add button at top right corner
*At pop up: fill up Name as "M2Eclipse" and Location as "http://download.eclipse.org/technology/m2e/releases"
Now click OK After that installation would be started.
Another way to install Maven plug-in for Eclipse:
1. Open Eclipse
2. Go to Help -> Eclipse Marketplace
3. Search by Maven
4. Click "Install" button at "Maven Integration for Eclipse" section
5. Follow the instruction step by step
After successful installation do the followings in Eclipse:
1. Go to Window --> Preferences
2. Observe, Maven is enlisted at left panel
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Disable Auto-link for TBB When I build my VS project as Debug, it always auto-linked with tbb_debug.lib (which in turn linked with tbb_debug.dll). Is there a way to override this and make tbb.lib linked even for a Debug build?
A: First, are you sure it is 'auto-linked'?
If so, this is done using #pragma comment( lib, tbb_debug.lib ). Find where this code is, modify it if it's yours, or else disbale it somehow (either by do not including the file where that code is, or by #defining something that disables this piece code; any sane library writer should provide such a mechanism and it should be documented clearly as well).
If there is no such pragma, the library is linked because it appears in the project settings. Right-click project->Properties->Linker->Input and adjust.
Edit thanks to Alexey's comment it seems that you can probably disable TBB's autolinking, as seen in this header file. Defining __TBB_NO_IMPLICIT_LINKAGE should do the trick.
A: If the autolinking with tbb_debug.lib is accomplished with:
#pragma comment( lib, "tbb_debug" )
then as explained on the MSDN documentation page for pragma comment:
Places a library-search record in the object file. ... The library name follows the default library-search records in the object file; the linker searches for this library just as if you had named it on the command line provided that the library is not specified with /nodefaultlib.
You could disable the autolinking via #pragma comment( lib, "tbb_debug" ) by passing the linker option /NODEFAULTLIB:tbb_debug.lib.
However, are you asking because you are receiving a "multiply defined symbols" error (LNK1169) or perhaps LNK4098? If so, it may be that you have tbb.lib listed as input to linker for both Debug and Release profiles. You should remove this entry for the Debug profile as the correct library is being automatically linked in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how can i know if my code is Synthesizable? [Verilog] In designing a circuit in verilog using top-down method, I can start from the behavior of a circuit followed by defining the details in every module to construct a structural circuit that is synthesizable.
But how can I know if my code is synthesizable?
Are there any guidelines to follow to support synthesis in verilog?
A: There is a 'standard', IEEE 1364.1 but as Martin pointed out each tool supports whatever it wants. I recommend the Xilinx XST User Guide if you need a free resource.
Also, structural verilog typically means you are creating description close to a netlist and the constructs you would use in this case are a small subset of those that are synthesizable.
A: Read the documentation that comes with whatever synthesis tool you are going to be using. This will show you what you can do - sometimes there are very specific ways you have to write code to get the intended results.
Ultimately though, there's nothing to beat experience - run your synthesiser over your code (or small parts of it) at regular intervals and see what the tool produces.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to hide the box in html file before changing the module I had developed an application.In my application Message Button .if we click on that means one page*(first html)* is open and page consist of see all messages link,If we click on that link means it will go to another page (change the module),I try to hide that (first html) after clicking the see all messages .again its not hiding,my coding
function MessageNotification() {
this.inheritForm = PluginBase;
this.inheritForm();
this.initialise = function() {
this.hasLeftPane = false;
$("#messageTopBarContainer").hide();
$("#topMessageNotifier").click(function(e){
e.preventDefault();
$("#messageTopBarContainer").show();
return false;
});
$("#closeMessageWindow").click(function(e){
e.preventDefault();
$("#messageTopBarContainer").hide();
return false;
});
$("#seeAllMessagesLink").click(function(e){
e.preventDefault();
$("#messageTopBarContainer").hide();
mainApplication.changeModule("OfflineMessage");
return false;
});
};
}
My html
<div id="MessageNotificationEntryPoint">
<span id="messageNotificaitonCount" class="topHeaderNewIncomingCount">0</span>
<div id="messageTopBarContainer" class="messageNotificationContainer">
<div id="messageTitle">
<h6 id="headingMessage">Messages</h6>
<span id="closeMessageWindow" class="topbarWidgetCloseButton"></span>
</div>
<div id="composeInMainWrapper" class="composeInMainWrapperClass">
<input type="button" id="composeLink" class="composeMessageLink" name="composeLink" value="Compose Message">
</div>
<div id="messageListContainer" class="messageListContainerClass">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div id="seeAllMessages" class="seeAllMessagesFooter">
<span id="seeAllMessagesLink" class="seeAllMessagesLinkClass">See All Messages</span>
</div>
</div>
Suggest some solution to overcome
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implementing Database in WP7 Mango I had many doubts regarding Database in windows Phone Mango.
*
*In WP7 mango how i can enter/Insert a list of objects or observable
collection to a table
*I had a database (*.sdf) with me that contains some data, I used
SQLMetel and i created a .cs file; but while reading that cs file
it's showing plenty of irrelevent information.
My question is from that automatically generated cs file, how I can split the generated information based on my independent tables. i.e. I need to keep the information of each table in two separate cs files. For example, the student database contains student details and parents details. While creating the cs file with sql metal it's only giving a single file that contains both table related data. I need to split this table info to two independent .cs files. What do I need to do to do this?
A: Why do you want to split the entity classes in separate files. You can use classes generated for all tables and ignore those that you do not want to.
But if you must, here is one way. Generate an intermediate dbml file, edit it and then generate the code using dbml file(s). Say you have two tables student and parent in database.sdf
*
*run:SqlMetal.exe /dbml:database.dbml database.sdf
*Copy the database.dbml file to student.dbml and parent.dbml
*Edit student.dbml and remove the XML node for parent. Similarly edit parent.dbml and delete the XML node for student
*run: SqlMetal.exe /code:database1.cs student.dbml and SqlMetal.exe /code:database2.cs parent.dbml
Since it generates the classes as partial classes, you should be able to include both files in your project. (You will need to delete constructors that you use IDbConnection from both files)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Will you create a service for Rx.Observable? I have the following code in VM..
Observable
.Timer(remainingTimeSpanForNextHour, TimeSpan.FromHours(1))
.Timestamp()
.Subscribe( x => FillBookingData());
My questions are ~
*
*Do you think we need to test this code? Would it be like we are trying to test Rx if we are planning to test this code? maybe. we should just test only this value "remainingTimeSpanForNextHour"
*Let's say we should test this code. Do you think it's good idea to create the service like IObservableService ?
A: It's always a good idea to test your code, but with observables it can be a little hard if your code is all in the one method or code block.
You should try to separate out the components of this query - and for me there are three components:
*
*Parameters
*Observable
*Observer
So write tests to ensure you get the right parameter values coming in.
Then write tests that ensure that your query produces values according to a similar set of input values. I wouldn't write a test that has to wait an hour for a value to arrive, so change hours to seconds, etc.
Then write tests that make sure that the observer works.
Now, as far as writing an IObservableService interface/implementation I think that is not a good thing. I'd instead focus on writing one or more service that abstract away what you're trying to do on a functional basis so that you are being DRY (Don't Repeat Yourself).
So, I would think an ITimerService might be useful.
public interface ITimerService
{
IDisposable Subscribe(TimeSpan dueTime, TimeSpan period, Action action);
}
Clearly it is designed to fit in with Rx - the signature is similar to Observable.Timer crossed with IObservable.Subscribe. It would use your existing query, just made to use the input parameters.
You should find testing this code to be quite easy.
Let me know if this is a good starting point for you.
A: Testing a timer is easy using Virtual Time - you can ignore the ReactiveUI bits, use AdvanceTo and figure out a way to inject the IScheduler you're using into your code (both Timer() and Timestamp() must be given your TestScheduler objects)
Even though this seems like a pain, the end result is that you can test code that will normally take time to execute, instantly and your tests will have the same result every time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android - referencing string array using another string with getIdentifier() and getStringArray I have a variety of string arrays I want to access depending on which one the user decides to use. I don't want to use a SQLite DB because I am very new to Android/Java and I have struggled to find examples so I'm guessing this is a rather poor way to do it but all the same...
If I have in a xml file this:
<string-array name="bob">
<item>1</item>
<item>4</item>
<item>7</item>
<item>11</item>
</string-array>
And in a Java file this:
String name = "bob";
Why does the following not work? It crashes on startup every time.
int holderint = getResources().getIdentifier("name", "array",
this.getPackageName());
String[] items = getResources().getStringArray(holderint);
A: Shouldn't this line be like this?
int holderint = getResources().getIdentifier(name, "array",
this.getPackageName()); // You had used "name"
String[] items = getResources().getStringArray(holderint);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Facebook: Custom Landing Page "For Fans" Facebook provides us with an option to choose a custom landing tab for the new visitors (i.e. non-fans). Can we have a custom Landing tab for fans so that every time i open the page, i m directed to that custom page rather than the Wall..
A: Have you checked Facebook Help Center?
How can I select a tab as default for people who already Like my Page?
This functionality does not exist.
A: What you are trying to do is straightforwrd.
*
*Create a "landing page" tab app and add it to your page. Here is a tutorial on how to do it: http://how-to-create-facebook-app.koliber.com
*Make this tab the default for your app. On your page, in the upper-right corner click "Edit Page" and change the "Default Landing Tab" to the one you would like displayed by default.
*Now everyone will be shown the default tab when they log in. How to distinguish between those visitors who "liked" your page and those that didn't? Easy. Make two versions of the page and display one to those who liked and one to those who didn't like. How to find out whether the current visitor liked your page or not follows:
*When your Page Tab URL is called in the iframe, it is passed a signed_request POST parameter. This parameter contains the info you need. However, it is encoded and structured so it needs some processing to get the info
*Split the signed_request on the '.' character. The first part is the signature. The second part is the encoded_data
*Decode the encoded_data into a JSON string using the URLBase64Decode function equivalent in your server-side programming language
*The JSON object contains a node called "page". This contains a node called "liked".
*If "liked" is true, the user liked the page and you display the "liked" version of your app. If false, show the "Please like me" version of the site.
This way, when visitors visit your page, they see your custom app in a tab. The actual content is determined server-side on your server based on the page.liked property inside of the JSON object passed to you in signed_request
A: The simple answer as far as I have been able to find out is "No". There is no setting which aligns with this requirement.
The wall is the default tab for people who like the page.
A: http://apps.facebook.com/static_html_plus/ this application gives you those options... enjoy!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compare List and enable the required control I am having two list<string> as follows
listA is having the following values 10,20,30,40 and
listB is having the following values 10,20,30
If listB contains listA elements i would like to enable particular controls if not i would like to disable the Controls
I tried of using two loops as follows
for(int ilist1=0;ilist1<listA.count;ilist1++)
{
for(int ilist2=0;ilist2<listB.count;ilist2++)
{
if(listA[ilist1]==listB[ilist2])
{
//Enable particular control
}
}
}
But i know this is not an appropriate one to do so can any one tell me the best approach to achieve this
A: It's easy by using the Intersect method:
if (listB.Intersect(listA).Count() > 0)
{
//enable Control
}
else
{
//disable control
}
A: What you want to do is to hash the items in the first list into a set then verify for each item in the second is within the set. Unfortunately the HashSet<> is not available so the closest you can get is the Dictionary<,>.
Do this:
Dictionary<string, string> set = new Dictionary<string, string>();
foreach (string item in listA)
{
set.Add(item, item);
}
foreach (string item in listB)
{
if (!set.ContainsKey(item))
{
//Enable particular control
}
}
A: I think you are looking for something like this
List<string> lista = new List<string>() {"10","40","30" };
List<string> listb = new List<string>() { "10", "20" };
var diff = listb.Except<string>(lista);
diff should give you the ones which didn't match else all would have been matched.
For 2.0
if (listb.TrueForAll(delegate(string s2) { return lista.Contains(s2); }))
MessageBox.Show("All Matched");
else
MessageBox.Show("Not Matched");
A: In fx 2.0, you can do it like this:
string b = listA.Find(delegate(string a) { return listB.Contains(a); });
if (string.IsNullOrEmpty(b))
{
//disable control
}
else
{
//enable control
}
A: Control.Enabled = listB.Intersect(listA).Any()
Note that Any() will only check to see if there is at least one item. Count() > 0 will evaluate the entire collection when you only need to check if there is at least one item
Edit: If you are in a .NET 2.0 environment then you can loop through and do this:
foreach (int item in listB)
{
if (listA.Contains(item))
return true;
}
return false;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Referencing textfield on stage issue I use this sample code taken from the docs: all the code is contained inside SocketExample.as, that is the DocumentClass too.
package {
import flash.display.Sprite;
public class SocketExample extends Sprite {
public function SocketExample() {
var socket:CustomSocket = new CustomSocket("127.0.0.1", 5000);
}
}
}
import flash.errors.*;
import flash.events.*;
import flash.net.Socket;
class CustomSocket extends Socket {
private var response:String;
public var txt:TextField;
public function CustomSocket(host:String = null, port:uint = 0) {
super();
configureListeners();
if (host && port) {
super.connect(host, port);
}
}
private function configureListeners():void {
addEventListener(Event.CLOSE, closeHandler);
addEventListener(Event.CONNECT, connectHandler);
addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
private function writeln(str:String):void {
str += "\n";
try {
writeUTFBytes(str);
}
catch(e:IOError) {
trace(e);
}
}
private function sendRequest():void {
trace("sendRequest");
response = "";
writeln("GET /");
flush();
}
private function readResponse():void {
var str:String = readUTFBytes(bytesAvailable);
response += str;
}
private function closeHandler(event:Event):void {
trace("closeHandler: " + event);
trace(response.toString());
}
private function connectHandler(event:Event):void {
trace("connectHandler: " + event);
sendRequest();
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function socketDataHandler(event:ProgressEvent):void {
trace("socketDataHandler: " + event);
readResponse();
}
public function returnResponse(){
return response.toString();
}
}
On socket close closeHandler gets called. How can I write the value of the response to a textfield on stage? I tried sending a custom Event from CustomSocket closeHandler but, even if I correctly added a listener to the constructor of SocketExample, I did not receive any event. What can I do?
A: Looks like you already added a public txt field for storing a reference to a text field. How about you create a text field in your SocketExample class, add it to the stage, and then set socket.txt = yourTextField. Then you can just use txt directly in closeHandler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Event.target issue with Firefox 6 In Firefox 6 I tried to get the target element on which the event occurred, but it does not show any element and it shows undefined in alert. Tried to debug it using the Firebug tool and found the attribute "target" missing for the event object. Can anyone help me out? I do have the code below:
function getSource(event)
{
if(!event)
{
field = window.event.srcElement;
alert(field);
}
else
{
field = event.target;
alert(field) //Getting undefined in FF6
}
}
Edited Portion:
document.onkeypress = getSource;
document.onmouseup = getSource;
Any help would be appreciated.
A: Try the code below
function getSource(e)
{
if(!e)
e = window.event;
field = evt.srcElement || evt.target;
alert(field);
return true;
}
Hope this helps you.
A: Test this in Fx 6:
<script type="text/javascript">
window.onload = function() {
document.getElementById('d0').onclick = showTarget;
}
function showTarget(e) {
e = e || window.event;
var target = e.target || e.srcElement;
alert(target.tagName);
}
</script>
<div id="d0">
<p>click on me</p>
</div>
It should alert "P".
A: As also explained in the similar question, change the function to this:
function getSource(evt)
{
if(!evt)
evt = window.event;
if (evt) {
field = evt.srcElement || evt.target;
alert(field);
return true;
}
alert("event not found");
return false;
}
A: function getSource(ev) {
var el=(ev=ev||window.event).target||ev.srcElement;
alert(el+" "+el.tagName);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Develop GPS application I have a Windows 7 tablet pc with GPS facility. I need to develop a GPS application for my tablet pc. How can I do that? Is there any built in API is available for that?
What kind of API do I have to use?
some1 please help.
A: Use the framework 4's Location API, check out samples below:
http://blogs.msdn.com/b/gavingear/archive/2009/11/30/net-4-location-let-s-take-a-look-at-status.aspx
http://blogs.msdn.com/b/gavingear/archive/2009/11/20/let-s-write-a-simple-net-4-location-aware-application.aspx
http://wotudo.net/blogs/wotudo/archive/2010/02/08/windows-7-setup-gps-for-the-location-api.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Load image to a tableView from URL iphone sdk I have tableView and need to load image from URL. I have an array that contains the URLs of images and when the page loads I need to load all the images into the tableview. Note that, not from a single URL, have an array with different URLs. How can I implement that? Please help
Thanks.
A: You can use Lazy Loading when you want to download Images from internet
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//All you reusable cell implementation here.
//Since your Images sizes differ. Keep a custom Imageview
if(![imagesForCategories containsObject:indexPath])
{
customImageView.image = [UIImage imageNamed:@"default-image.png"];
NSMutableArray *arr = [[NSArray alloc] initWithObjects:[imageUrlArray objectAtIndex:indexPath.row],indexPath, nil];
[self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];
[arr release];
}
return cell;
}
- (void) loadImageInBackground:(NSArray *)urlAndTagReference
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *imgUrl=[[NSURL alloc] initWithString:[urlAndTagReference objectAtIndex:0]];
NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
UIImage *img = [UIImage imageWithData:imgData];
[imgUrl release];
NSMutableArray *arr = [[NSMutableArray alloc ] initWithObjects:img,[urlAndTagReference objectAtIndex:1], nil ];
[self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
[arr release];
[pool release];
}
- (void) assignImageToImageView:(NSMutableArray *)imgAndTagReference
{
[imagesForCategories addObject:[imgAndTagReference objectAtIndex:1]];
UITableViewCell *cell = [celebCategoryTableView cellForRowAtIndexPath:[imgAndTagReference objectAtIndex:1]];
UIImageView *profilePic = (UIImageView *)[cell.contentView viewWithTag:20];
profilePic.image = [imgAndTagReference objectAtIndex:0];
}
A: You can use SDWebImage which permits very easy and speed loading of images in UITableView.
https://github.com/rs/SDWebImage
A: Try this code,imagearray contains urls of image
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [imagearray objectAtIndex:row]]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
cell.imageView.image =image;
return cell;
}
A: You can use GCD to load images in background thread, like this:
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *image = [[NSData alloc] initWithContentsOfURL:imageURL];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithData:image];
});
});
Hi. But you probably need to add a dispatch_release(concurrentQueue); to be sure no leak. – Franck Aug 25 at 19:43
A: You need to create your custom cell for lazy loading. This will allow you to download images correctly and without freezing. Here is nice example how to do this:
Asynch image loading
A: With afnetworki, it is too easy.
//afnetworking
#import "UIImageView+AFNetworking.h"
[cell.iboImageView setImageWithURL:[NSURL URLWithString:server.imagen] placeholderImage:[UIImage imageNamed:@"qhacer_logo.png"]];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: My custom ForeignKeyConvention is resulting in two foreign keys being created instead of one I am trying to create my own foreign key convention that will name the FK in "FK_SourceTable_TargetTable" format.
However, when I run it I end up with two foreign keys instead of one.
My custom foreign key convention looks like this:
public class OurForeignKeyConvention : ForeignKeyConvention
{
protected override string GetKeyName(Member property, Type type)
{
if (property == null)
return string.Format("FK_{0}Id", type.Name); // many-to-many, one-to-many, join
if (property.Name == type.Name)
return string.Format("FK_{0}_{1}", property.DeclaringType.Name, type.Name);
return string.Format("FK_{0}_{1}_{2}", property.DeclaringType.Name, property.Name, type.Name);
}
}
My code to exercise it:
[TestMethod]
public void ShouldBeAbleToBuildSchemaWithOurConventions()
{
var configuration = new Configuration();
configuration.Configure();
Fluently
.Configure(configuration)
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<Widget>()
.Conventions.Add<OurForeignKeyConvention>()
)
.BuildSessionFactory();
new SchemaExport(configuration).Create(false, true);
}
My classes and mappings:
public class Widget
{
public virtual int Id { get; set; }
public virtual string Description { get; set; }
public virtual WidgetType Type { get; set; }
public virtual ISet<WidgetFeature> Features { get; set; }
}
public class WidgetFeature
{
public virtual int Id { get; set; }
public virtual Widget Widget { get; set; }
public virtual string FeatureDescription { get; set; }
}
public class WidgetMap : ClassMap<Widget>
{
public WidgetMap()
{
Id(w => w.Id);
Map(w => w.Description);
HasMany(w => w.Features).Cascade.AllDeleteOrphan().Inverse();
}
}
public class WidgetFeatureMap : ClassMap<WidgetFeature>
{
public WidgetFeatureMap()
{
Id(w => w.Id);
Map(w => w.FeatureDescription);
References(w => w.Widget);
}
}
The end result is two foreign keys, one called what I want - FK_WidgetFeature_Widget - and another one called FK_WidgetId.
If I change OurForeignKeyConvention to always return the same name regardless of whether the "property" parameter is null then I correctly get a single FK - but I then cannot get the "SourceTable" part of my FK name.
Can anyone explain what I am doing wrong here? Why is GetKeyName called twice? And why does one of the calls not provide a value for the "property" parameter?
A: Doh. ForeignKeyConvention provides the name for the FK column. What I should have been using is the IHasManyConvention, which can be used to name the FK constraint itself.
public class OurForeignKeyConstraintNamingConvention : IHasManyConvention
{
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Key.ForeignKey(string.Format("FK_{0}_{1}", instance.Relationship.Class.Name, instance.EntityType.Name));
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why wont my data filter the date .. smalldatetime SELECT S.studentID, S.studentFName, S.DOB, S.studentEMail, S.studentAddress
FROM Student AS S RIGHT OUTER JOIN
(SELECT Attendance.studentID, COUNT(*) AS cnt FROM Attendance CROSS JOIN
CourseUnit WHERE (Attendance.attStatus = 'Yes') AND (CourseUnit.courseCode = 'S3000') AND (CONVERT(VARCHAR, Attendance.attDate, 101) < '11/10/2010') GROUP BY Attendance.studentID
HAVING (COUNT(*) < 5)) AS A ON A.studentID = S.studentID
Everything works, except the attDate. I dont have any records in 2010, and it still brings up all of them ??
A: Let me guess - your dates are a varchar? Fired. Any reason for that ugly ugly ugly unperformant and error prone construct
(CONVERT(VARCHAR, Attendance.attDate, 101) < '11/10/2010')
instead of Attendance.attDate being a Date object to start with? Try that and see whether that works.
A: Aren't you saying 'give me all dates less than this day in 2010' (< '2/10/2010')?
Maybe you need to switch around your < to a >.
A: Attendance.attDate should be of data type datetime and the comparison should be Attendance.attDate < '20101110' (YYYYMMDD) if you want the rows prior to the given date value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: java.lang.ArrayStoreException in java.util.Hashset Here is the stack trace :
java.lang.ArrayStoreException
at java.util.HashMap.transfer(Unknown Source)
at java.util.HashMap.resize(Unknown Source)
at java.util.HashMap.addEntry(Unknown Source)
at java.util.HashMap.put(Unknown Source)
at java.util.HashSet.add(Unknown Source)
Some observations :
*
*Its an intermittent issue
*JDK 1.6
*CentOS 5.3
As I understand this error is intermittent I suspect it occurs whenever the HashSet (hence underlying HashMap) needs to resize itself. But not sure why this ArrayStoreException. Now what I want to know is
-What are the scenarios wherein this error can occur ?
A: My guess is that you're trying to update the set from multiple threads concurrently. HashSet and HashMap aren't designed to be thread-safe - if you're going to access your set from multiple threads, you should use synchronization to prevent concurrent access.
That's just a guess, of course - without seeing your code I can't tell whether you are using multiple threads. It would go along with the intermittent side of things though...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Class and Activator.CreateInstance Here is some class:
public class MyClass<T, C> : IMyClass where T : SomeTClass
where C : SomeCClass
{
private T t;
private C c;
public MyClass()
{
this.t= Activator.CreateInstance<T>();
this.c= Activator.CreateInstance<C>();
}
}
And I'm trying to instanciate object of this class by doing this:
Type type = typeof(MyClass<,>).MakeGenericType(typeOfSomeTClass, typeOfSomeCClass);
object instance = Activator.CreateInstance(type);
And all I get is a System.MissingMethodException(there is no no-arg constructor for this object)...
What is wrong with my code?
A: It sounds like typeOfSomeTClass or typeOfSomeCClass is a type that doesn't have a public parameterless constructor, as required by:
this.t = Activator.CreateInstance<T>();
this.c = Activator.CreateInstance<C>();
You could enforce that via a constraint:
where T : SomeTClass, new()
where C : SomeCClass, new()
in which case you can also then do:
this.t = new T();
this.c = new C();
A: MakeGenericType should use an array of Type in this context.
See http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx
For example
Type type = typeof(LigneGrille<,>).MakeGenericType(new Type[] {typeOfSomeTClass, typeOfSomeCClass});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed I built an application and deployed locally ... and it was working perfectly. I deployed it on a remote server and started getting the exception mentioned in the subject line. It's not because of any firewall issues.
I changed my hibernate.xml to connect via my IP address rather then localhost and now I get the same timeouts on my locally deployed application. I get this error when I keep the application running for more than one day.
I am not performing any operations after committing transactions or closing sessions myself. I am using the following properties in hibernate.cfg.xml
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://myremotehost:3306/akp</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed by the driver.
Detailed:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed by the driver.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1193)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1180)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4137)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4103)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:505)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:423)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:139)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1547)
at org.hibernate.loader.Loader.doQuery(Loader.java:673)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
... 36 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 34,247,052 milliseconds ago. The last packet sent successfully to the server was 34,247,052 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3321)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1940)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:94)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1569)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at com.xyz.abc.DAO.GenericHibernateDAO.findByField(GenericHibernateDAO.java:119)
at com.xyz.abc.DAO.JobDAO.getJobsByLdap(JobDAO.java:115)
at com.xyz.abc.business.Jcr.getMyruns(Jcr.java:272)
at com.xyz.abc.business.abcService.getMyruns(abcService.java:54)
at sun.reflect.GeneratedMethodAccessor139.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:194)
at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:102)
at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:173)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:173)
at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:142)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:203)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:237)
... 4 more
Caused by: java.net.SocketException: Software caused connection abort: socket write error
Does anyone have any ideas what might cause this behavior?
EDIT:
Now am using folloing in my hibernate.cfg.xml file.Is it correct?
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/xyz</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<!-- <property name="hibernate.c3p0.max_size">1800</property>-->
<property name="hibernate.c3p0.max_statements">50</property>
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.maxIdleTimeExcessConnections">3600</property>
<property name="c3p0.idleConnectionTestPeriod">3600</property>
<property name="c3p0.maxIdleTime">3600</property>
A: As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.
Connection Pooling
Hibernate itself admits that its connection pooling strategy is minimal
Hibernate's own connection pooling algorithm is, however, quite
rudimentary. It is intended to help you get started and is not
intended for use in a production system, or even for performance
testing. You should use a third party pool for best performance and
stability. Just replace the hibernate.connection.pool_size property
with connection pool specific settings. This will turn off Hibernate's
internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
I personally use C3P0. however there are other alternatives available including DBCP.
Check out
*
*http://www.mchange.com/projects/c3p0/index.html
*http://commons.apache.org/dbcp/
Below is a minimal configuration of C3P0 used in my application:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">1800</property> <!-- seconds -->
By default, pools will never expire Connections. If you wish
Connections to be expired over time in order to maintain "freshness",
set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many
seconds a Connection should be permitted to go unused before being
culled from the pool. maxConnectionAge forces the pool to cull any
Connections that were acquired from the database more than the set
number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size
Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier.
The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:
Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)
# c3p0.properties
c3p0.testConnectionOnCheckout=true
With this configuration each connection is tested before being used. It however might affect the performance of the site.
A: MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ≈ 9.5 hours).
If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed.
MySQL suggests:
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property autoReconnect=true to avoid this problem.
A: If you don't want use connection pool (you sure, that your app has only one connection), you can do this - if connection falls you must establish new one - call method .openSession() instead .getCurrentSession()
For example:
SessionFactory sf = null;
// get session factory
// ...
//
Session session = null;
try {
session = sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
session = sessionFactory.openSession();
}
If you use Mysql, you can set autoReconnect property:
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/database?autoReconnect=true</property>
I hope this helps.
A: *
*First Replace the MySQL dependency as given below
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
*An error showing "Authentication plugin 'caching_sha2_password'" will appear. Run this command:
mysql -u root -p
ALTER USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
A: Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.
You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/
Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.
This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.
A: This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site.
Good Luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: Calling a java-script function when value of a Dojo auto-completer changes I am trying to call a javascript function when the value of a Dojo auto completer changes.
Calling the javascript function from the "onChange" attribute has no effect (I mean the function is not called/executed).
In the javascript function I want to:
*
*Call a struts2 action.
*Change the value of a hidden field.
For calling the action I have another way :
publishing a topic using attribute " valueNotifyTopic="topicName" ", then I can call an action by listening to the topic.
But I cant change the value of the hidden field through this way. So I need to call a javascript function
Please advise
Thanks!!
Edit:
This is the code in the jsp:
<s:url id="scriptURL" action="viewContactInfo" />
<sd:div href="%{scriptURL}" listenTopics="viewContactInfo" formId="contactInfo" showLoadingText="false" preload="false">
<s:form id="contactInfo">
<sd:autocompleter autoComplete="false" name="customer" list="customerList" valueNotifyTopics="viewContactInfo"/>
<sd:autocompleter autoComplete="false" name="contact" list="contactList" valueNotifyTopics="viewContactInfo"/>
<s:hidden id="chngd" value="initial"/>
</s:form>
</sd:div>
Here if I change "valueNotifyTopics='viewContactInfo'" to "onChange='dojo.event.topic.publish('viewContactInfo');'" the action "viewContactInfo" stops getting called. Whereas the same thing (the "onChange" one) works with other elements (in other places in my project).
A: I had started another thread for this question.
I figured out the solution and have posted the answer here :
Cannot find a way to pass a hidden value to the action file
Hope this helps!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .NET Application Updater Component without Webdav Does the .NET Application Updater Component (http://windowsclient.net/articles/appupdater.aspx) work without the WebDav protocol?
A: Quote from the page you linked:
The .NET Application Updater component uses HTTP-DAV to download the application update and thus requires a Web server that supports HTTP-DAV.
Although the source code is supplied, so you could possibly modify it to work another way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GroupBy in LINQ and set property I have such class:
public class Foo
{
public string Regn{get;set;}
public string DocName{get;set;}
...
}
In the my application this class uses with IEnumerable:
IEnumerable<Foo> items;
How to get new IEnumerable, where for all items with the same Regn and DocName property DocName sets like this(only if objects with same DocName >1):
item.DocName=item.DocName+".1";//+"2",etc.
[UPDATE]
Input sample:
Regn DocName
1 1
1 2
1 2
2 5
2 5
2 6
Output:
Regn DocName
1 1
1 2.1
1 2.2
2 5.1
2 5.2
2 6
A: If you have a default constructor for Foo try to use this:
var newItems = items.
GroupBy(f => Tuple.Create(f.Regn, f.DocName)).
SelectMany(gr => gr.Count()<=1 ? gr : gr.Select((f, i) => new Foo
{
Regn = f.Regn,
DocName = f.DocName + "." + (i + 1)
}));
A: You can group with LINQ and cast out groups that only have one item, then iterate over the items in each group to set the DocName:
// Group and filter
var groups = items.GroupBy(i => new { i.Regn, i.DocName })
.Where(g => g.Count() > 1);
// Iterate over each group with many items
foreach (var g in groups) {
var itemsInGroup = g.ToArray();
// Iterate over the items and set DocName
for (var i = 0; i < itemsInGroup.Length; ++i) {
itemsInGroup[i].DocName = g.Key + "." + (i + 1);
}
}
A: All in one statement, just for fun.
var query = items.GroupBy(i => new { i.DocName, i.Regn })
.SelectMany(group =>
{
int itemNum = 0;
return group.Select(item =>
{
var suffix = itemNum > 0 ? ("." + itemNum) : "";
var newDocName = item.DocName + suffix;
itemNum++;
return new { item, NewDocName = newDocName };
});
});
A: Or use a LINQ statement to create a new result set like:
var fixedSet = from entry in existing
group entry by entry.DocName + entry.Regn into groupedEntries
let groupedEntriesAsArray = groupedEntries.ToArray()
from groupedEntry in groupedEntriesAsArray
let index = Array.IndexOf(groupedEntriesAsArray, groupedEntry)
select new Foo
{
DocName =
string.Format("{0}.{1}", groupedEntry.DocName, index + 1),
Regn =
string.Format("{0}.{1}", groupedEntry.Regn, index + 1)
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to make our application to support multi-touch?
Possible Duplicate:
Android multi-touch support
My application requires multi-touch user input.
How can i achieve multi-touch in my application ? is there any tutorial from which i can learn ? Please give me some links of tutorials.
Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP array group by data values This is my $data variable:
cv = 1,2,3,4,5:::cpt = 4,5 ...
Now I need some function, where I can add the number as param (number will be $data number value).
for example.
function getPermission($id) {
... return $something;
}
Then if I call the function like: echo getPermission(4); it'll print out the data 'keys' where the 4 will be inside, as a value.
So, to be clear:
if I call the function like this:
echo getPermission(4); output will be "cv" and "cpt".
but if I call it this way:
echo getPermission(1);
it'll only output "cv" because number (1) is located in the cv key.
Hope you guys understand, feel free to ask if something aren't clear enough.
A: $str = 'cv = 1,2,3,4,5:::cpt = 4,5';
$tmp = explode(':::', $str);
$data = array();
foreach ($tmp as $arr) {
$tokens = explode(' = ', $arr);
$data[$tokens[0]] = explode(',', $tokens[1]);
}
print_r(getPermission(4, $data));
print_r(getPermission(1, $data));
function getPermission($id, $data) {
$out = array();
foreach ($data as $key => $arr) {
if (in_array($id, $arr)) $out[] = $key;
}
return $out;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Roo finder issue I have followed Spring Roo tutorial (by Ben Alex). Until create finder everything went fine. When I am create finder It won't generate generate relevent JSP file. it only update java and .aj file. What kind of issue this can be?
~.domain.Rsvp roo> controller class --class ~.web.PublicRsvpController
Created SRC_MAIN_JAVA\com\wedding\web\PublicRsvpController.java
Updated SRC_MAIN_WEBAPP\WEB-INF\i18n\application.properties
Created SRC_MAIN_WEBAPP\WEB-INF\views\publicrsvp
Created SRC_MAIN_WEBAPP\WEB-INF\views\publicrsvp\views.xml
Created SRC_MAIN_WEBAPP\WEB-INF\views\publicrsvp\index.jspx
Updated SRC_MAIN_WEBAPP\WEB-INF\views\menu.jspx
~.domain.Rsvp roo> finder list --class ~.domain.Rsvp --filter code,equ
findRsvpsByAttendingEquals(Integer attending)
findRsvpsByAttendingGreaterThanEquals(Integer attending)
findRsvpsByAttendingLessThanEquals(Integer attending)
findRsvpsByAttendingNotEquals(Integer attending)
findRsvpsByCodeEquals(String code)
findRsvpsByCodeIsNotNull()
findRsvpsByCodeIsNull()
findRsvpsByCodeLike(String code)
findRsvpsByCodeNotEquals(String code)
findRsvpsByConfirmedEquals(Date confirmed)
findRsvpsByConfirmedGreaterThanEquals(Date confirmed)
findRsvpsByConfirmedLessThanEquals(Date confirmed)
findRsvpsByConfirmedNotEquals(Date confirmed)
findRsvpsByEmailEquals(String email)
findRsvpsByEmailNotEquals(String email)
findRsvpsBySpecialRequestsEquals(String specialRequests)
findRsvpsBySpecialRequestsIsNotNull()
findRsvpsBySpecialRequestsIsNull()
findRsvpsBySpecialRequestsLike(String specialRequests)
findRsvpsBySpecialRequestsNotEquals(String specialRequests)
~.domain.Rsvp roo> finder add --finderName findRsvpsByCodeEquals
Updated SRC_MAIN_JAVA\com\wedding\domain\Rsvp.java
Created SRC_MAIN_JAVA\com\wedding\domain\Rsvp_Roo_Finder.aj
~.domain.Rsvp roo>
A: In Roo 1.1.2 is a Bug [#ROO-2108] that does not generate JSPs for Finder.
And in 1.1.4 there is an other bug: [#ROO-2480]
But it is fixed in newer Version.
A: I faced the same problem.
It was just missing this roo command:
web mvc finder all
That adds all the necessary finders (:
A: This is was Spring Roo document problem, They haven't update their document for Spring Roo 1.2.0 related API changes.
A: web mvc finder all is the solution for this.
It worked for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 3 Apache & Mongrel colleagues.
Here is what I have:
Windows XP
Ruby 1.9.2p180 (2011-02-18) [i386-mingw32]
Rails 3.1.0
Also I have installed mongrel server gem install mongrel -v 1.2.0.pre2 --pre
When I do rails s, mongrel starts (everything is ok)
But I want to use my RoR application via Apache 2.2, that is installed as service.
I decided that best way is to use Apache & Mongrel. Then I have installed mongrel_service gem install mongrel_service, and run mongrel as service mongrel_rails service::install -N efiling_mongrel -c c:\sites\uplodify -p 3000 -e development -a 127.0.0.1. Then I also setuped Apache...
When I started Apache as service and Mongrel as service, I see such picture:
1) my ruby proccess uses more than 50% of CPU resource
2) permanent growth log/mongrel.log file size
3) there are such errors in log/mongrel.log:
** Starting Mongrel listening at 127.0.0.1:3000
** Starting Rails with development environment...
C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-.1.0/lib/active_support/dependencies.rb:240:in `require': no such file to load -- dispatcher (LoadError)
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-.1.0/lib/active_support/dependencies.rb:240:in `block in require'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-.1.0/lib/active_support/dependencies.rb:223:in `block in load_dependency'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-.1.0/lib/active_support/dependencies.rb:640:in `new_constants_in'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-.1.0/lib/active_support/dependencies.rb:223:in `load_dependency'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-.1.0/lib/active_support/dependencies.rb:240:in `require'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/lib/mongrel/rails.rb:148:in `rails'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/bin/mongrel_rails:116:in `block (2 levels) in run'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/lib/mongrel/configurator.rb:149:in `call'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/lib/mongrel/configurator.rb:149:in `listener'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/bin/mongrel_rails:102:in `block in run'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/lib/mongrel/configurator.rb:50:in `call'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/lib/mongrel/configurator.rb:50:in `initialize'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/bin/mongrel_rails:86:in `new'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/bin/mongrel_rails:86:in `run'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/lib/mongrel/command.rb:210:in `run'
from C:/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/mongrel-1.2.0.pre2-x86-ingw32/bin/mongrel_rails:282:in `<top (required)>'
from C:/Ruby/Ruby192/bin/mongrel_rails:19:in `load'
from C:/Ruby/Ruby192/bin/mongrel_rails:19:in `<main>'
Someone have any ideas?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Exception in thread AWT-EventQueue-2 java.lang.NullPointerException I am trying to run a JApplet with jnlp.
I have created my MyApplet which extends JApplet and packaged in a jar.
I have also created MyApplet.jnlp and MyApplet.html
My Runtime env is jdk 1.7.0.02.
When I run it in a browser I get below exception from the browser, but my applet is running properly from the eclipse as a stand alone
This is the exception I am getting
Exception in thread "AWT-EventQueue-2" java.lang.NullPointerException
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter$8.run(Unknown Source)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.runOnEDT(Unknown Source)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.resize(Unknown Source)
Please find my code below. This is the applet class which is running fine through Eclipse:
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.JApplet;
//This is my applet class
public class MyApplet extends JApplet {
private Container Panel;
//constructor
public MyApplet () {
super ();
Panel = getContentPane();
Panel.setBackground (Color.cyan);
}
//paint method
public void paint (Graphics g) {
int Width;
int Height;
super.paint (g);
Width = getWidth();
Height = getHeight();
g.drawString ("The applet width is " + Width + " Pixels", 10, 30);
g.drawString ("The applet height is " + Height + " Pixels", 10, 50);
}
}
This is the html file, MyApplet.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en-US">
<head>
<title>My Applet Menu Chooser Applet</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
</head>
<body>
<noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript>
<h1>Draggable Menu ChooserApplet</h1>
<p>Press the <b>Left</b> button on your mouse and drag the applet.</p>
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = { code:'MyApplet', width:900, height:300 };
var parameters = {jnlp_href: 'MyApplet.jnlp', draggable: 'true'} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
</body>
</html>
MyAppletJnlp.jnlp
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" href="MyApplet.jnlp">
<information>
<title>Jnlp Testing</title>
<vendor>akash sharma</vendor>
<description>Testing Testing</description>
<offline-allowed />
<shortcut online="false">
<desktop />
</shortcut>
</information>
<security>
<all-permissions/>
</security>
<resources>
<!-- Application Resources -->
href="http://java.sun.com/products/autodl/j2se"/>
<jar href="MyApplet.jar" main="true" />
</resources>
<applet-desc
name="Draggable Applet"
main-class="com.acc.MyApplet"
width="900"
height="300">
</applet-desc>
<update check="background"/>
</jnlp>
A: I got the solution. Actually In the jar file the path of the class file was not correct that which I have mentioned in the JNLP file that is why I was getting null pointer exception.Once i updated the jar files i got it resolved
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: list for flex mobile app (android) I am new in flex android and I've been practicing this right now. I have here an exercise program with flex android app (AS3). Here's the code of my HomeView.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
title="Home">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var people:ArrayCollection;
private function init():void
{
people = new ArrayCollection();
var somebody:Object = new Object();
somebody.firstname = "John";
somebody.lastname = "Doe";
somebody.phone = "555213412";
somebody.email = "john@doe.com";
somebody.twitter = "@johndoe";
people.addItem(somebody);
somebody = new Object();
somebody.firstname = "Jane";
somebody.lastname = "Baker";
somebody.phone = "5559981272";
somebody.email = "jane@baker.com";
somebody.twitter = "@janebaker";
people.addItem(somebody);
}
private function handleClick():void
{
navigator.pushView( PeopleDetails, peopleList.selectedItem );
}
]]>
</fx:Script>
<s:List id="peopleList" dataProvider="{people}" click="handleClick()" labelField="name" width="100%" height="100%" />
</s:View>
And this is the code of my PeopleDetails.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
title ="Person Details">
<fx:Script>
<![CDATA[
private function gotoHome():void
{
navigator.popToFirstView();
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:layout>
<s:VerticalLayout paddingBottom="5" paddingLeft="5" paddingRight="5" paddingTop="5"/>
</s:layout>
<s:Form width="100%" height="100%">
<s:FormItem label="Name:" width="100%">
<s:Label text="{data.name}"/>
</s:FormItem>
<s:FormItem label="Phone:" width="100%">
<s:Label text="{data.phone}"/>
</s:FormItem>
<s:FormItem label="Email:" width="100%">
<s:Label text="{data.email}"/>
</s:FormItem>
<s:FormItem label="Twitter:" width="100%">
<s:Label text="{data.twitter}"/>
</s:FormItem>
</s:Form>
<s:navigationContent>
<s:Button label="Home" click="gotoHome()"/>
</s:navigationContent>
</s:View>
Now, my problem is, why is it that I can't see my list, and that if just click anywhere in the screen, it brings me to the the PeopleDetails.mxml view, and still, no data shown (but the labels where there).? What did I miss in my code?
And by the way, I'm currently using FlashDevelop for my apps, is there something you can recommend for me to study about it (flex android app)? thanks all.
A: Flex Android Apps are nothing more than glorified browser. You can test your code on the browser and figure out the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using IOS and facebook APIS Hi Does any one know how to use facebook chat apis with ios, I have use git command from the steps followed here http://developers.facebook.com/docs/guides/mobile/ios/ after that i dont have any idea how to create a sample app and what syntax to follow. Thanks a lot
Max
A: I haven't yet worked with the FB SDK, but their guide says
The Github repository contains a sample application that showcases the iOS SDK features.
And indeed here's the sample: https://github.com/facebook/facebook-ios-sdk/tree/master/sample/DemoApp
You should check this sample app first. You can just open the DemoApp.xcodeproj file from your local git clone folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Comparison Report of migration from VSS 2005 to TFS 2010 We have Visual Source Safe 2005 and tried migrating on TFS 2010 in test environment but some of the nodes are missing and it looks like some data got skipped during migration and we have so many projects with multiple nodes and sub nodes so its hard to identify which nodes are missing. What I want to know is that is there any built-in tool available to give me a comparison report from source to target that what's missing in target compare to source.
A: Could you download the source from the two trees and use a recursive folder diff tool?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Functional programming vs. variable and memory Does functional programming use variables?
If no, how do the functional programs occupy memory?
A: Both functional programs and imperative (C#, Java) programs use variables, but they define them differently.
In functional programs the variables are like those in mathematics, once a value has been assigned the value cannot change.
In imperative languages it is typical that the values held by variables an be changed.
In both cases variables use memory.
A: If you're asking about implementation details for various methods of compiling functional programs, you probably need to start with reading "Implementing functional languages: a tutorial". It is a bit out of date (e.g., it does not cover the modern STG approach), but still valuable. Another, even older text to read is Field, Harrison, "Functional programming" (never mind the title, it's mostly about implementing FP compilers).
A: Pure functional programming uses no variables, but maybe constants in the C sense (that is, assigned only once, but at runtime).
Functional programs occupy memory with the function call "stack", i.e. the current expression and the arguments of recursively called functions.
A:
Does functional programming use variables?
Well, at least you can bind names to values. One can call this name a variable, even if it is not variable. But in math, when we see:
x + 3 = 5
we call x a variale, though it is just another name of 2.
Otoh, the names that are bound to arguments of functions are indeed variable, if only across different invocations of the function.
If no, how do the functional programs occupy memory?
There will be language elements to construct non-primitive values, like lists, tuples, etc. Such a data constructor creates new values from old ones (somewhere in memory, but those details are irrelevant for FP).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Linq intersect or join to return items from one collection that have matching properties to another? I have the following scenario: Two lists of different Types which happen to contain 3 matching properties (in reality, the names are not the same as they are from different systems/database tables, but their contents match).
In my example I have named the properties the same just to make it easier!
I'd like to get a list of Prefix+Number+Suffix for accounts where there is a matching item in lookup (NOTE: Lookup can contain the same values multiple times - the rest of the properties in the objects are different)
This is the code I am currently using, but it feels clunky. Is there a cleaner, better way to acheive the same result? I tried "Contains()" but wasn't sure how to restrict to all three properties.
var accounts = new List<Account>{
new Account{Prefix="001", Number="10101", Suffix="666"},
new Account{Prefix="001", Number="10202", Suffix="777"},
new Account{Prefix="001", Number="10303", Suffix="777"},
new Account{Prefix="002", Number="20101", Suffix="666"},
new Account{Prefix="002", Number="20101", Suffix="777"}
};
var lookup = new List<Lookup>{
new Lookup{Prefix="001", Number="10101", Suffix="666"},
new Lookup{Prefix="001", Number="10101", Suffix="666"},
new Lookup{Prefix="002", Number="20101", Suffix="666"},
new Lookup{Prefix="001", Number="10101", Suffix="666"},
};
var match = ((from a in accounts
select a)
.Intersect(from l in lookup
from a in accounts
where l.Prefix == a.Prefix &&
l.Number == a.Number &&
l.Suffix == a.Suffix
select a)
).Select(a => string.Format("{0}{1}{2}", a.Prefix, a.Number, a.Suffix));
A: You can use the following code to get the match:
var match = (from a in accounts
select new { P = a.Prefix, N = a.Number, S = a.Suffix })
.Intersect(from l in lookup
select new { P = l.Prefix, N = l.Number, S = l.Suffix })
.Select(t => string.Format("{0}{1}{2}", t.P, t.N, t.S));;
You make use here of the automatically generated equality operators on anonymous types.
A: why dont you try join between them
from a in accounts
join l in lookup
on
new { a.Prefix, a.Number, a. Suffix}
equals
new { l.Prefix, l.Number,l. Suffix}
select a;
A: Why not just simply:
match = (from l in lookup
from a in accounts
where l.Prefix == a.Prefix &&
l.Number == a.Number &&
l.Suffix == a.Suffix
select string.Format("{0}|{1}|{2}", l.Prefix, l.Number, l.Suffix))
.Distinct();
A: Try this:
from a in accounts
join l in lookup on
new
{
a.Prefix, a.Number, a. Suffix
}
equals
new
{
l.Prefix, l.Number, l. Suffix
}
into gls
select a
A: I would not work directly with the tables but use a database view in cases like this. Create a view which performs the union for you and returns a normalised data structure, like so:
CREATE VIEW ExampleView
AS
SELECT
Prefix = a.Prefix,
Number = a.Number,
Suffix = a.Suffix
FROM
FirstTable AS a
UNION ALL
SELECT
Prefix = l.Prefix,
Number = l.NumberWithDifferentName,
Suffix = l.WeirdlyNamedSuffix
FROM
SecondTable AS l
Then you can run a simple select on that view instead of performing complex database logic in your application, where it does not really belong anyway:
SELECT Prefix, Number, Suffix FROM ExampleView; /* or obviously the LINQ equivalent */
Here a link to an article on that matter (why to use views): http://www.tdan.com/view-articles/5109. To cite the part that explains why its better practice to let the database do what it does best, not the application:
Developers find having to work with normalized data structures awkward and time-consuming, since it involves coding complex SQL queries that join data from multiple tables. [...] "refactoring" non-normalized data structures into normalized ones after the fact is always extremely difficult and labor-intensive, and sometimes isn't even possible (because data in non-key fields must be "refactored" into key fields, and data in these fields may have missing or incorrect values).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Solr query is hanging server I have developed a enterprise search using solr, I have developed a patternMatching class to match the query string
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: java.lang.IllegalArgumentException: Invalid authentication type: want I have a web-service method which works fine until enabling FIPS mode in tomcat.
The code bellow executes fine if FIPS mode is disable:
((X509TrustManager) tm[0]).checkClientTrusted(clientCert, "want");
But when FIPS get enable on tomcat. Same line throws exception as:
java.lang.IllegalArgumentException: Invalid authentication type: want.
I gone through java doc, it says method throws IllegalArgumentException if:
IllegalArgumentException - if null or zero-length chain is passed in for the chain parameter or if null or zero-length string is passed in for the authType parameter.
But neither of above condition is true in my case.
Not getting why. Please help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Setting access to a folder to only one user I Want to assign permissions to only a single user to a folder in windows using C#, Other users should not be able to open or change the access rights of that folder.
for example if I have 3 users - UserA ,UserB and UserC in Users group. I want to give permission to access a folder only to UserA. If I deny access to users group and allow UserA, then deny permission will take precedence and access to UserA will also be denied.
one work around to this problem is by denying Userb and Userc ,and allowing UserA to access the folder . but this has a problem if after setting the permissions a user account creates then that new account will have permission to the folder. I don't want to have this scenario.
Thanks,
Sujith
A: The default permission for anyone not mentioned in the ACL is "no access" (An Empty DACL grants no access). So, prevent the folder inheriting security from its parent, and assign permissions to UserA only.
(Of course, this doesn't prevent an administrator from taking ownership and thereafter granting permissions for themselves. Nothing can prevent that)
E.g. to create a directory, called C:\FruitBat, that's only accessible to user DOMAIN\User1:
System.Security.AccessControl.DirectorySecurity dacl = new System.Security.AccessControl.DirectorySecurity();
dacl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(@"DOMAIN\User1",
System.Security.AccessControl.FileSystemRights.FullControl,
System.Security.AccessControl.InheritanceFlags.ContainerInherit |
System.Security.AccessControl.InheritanceFlags.ObjectInherit,
System.Security.AccessControl.PropagationFlags.None ,
System.Security.AccessControl.AccessControlType.Allow));
System.IO.Directory.CreateDirectory(@"C:\FruitBat", dacl);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: android.database.sqlite.SQLiteException: near "(" this is my error:
09-27 08:16:34.547: WARN/System.err(8366): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
09-27 08:16:34.547: WARN/System.err(8366): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
09-27 08:16:34.547: WARN/System.err(8366): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
09-27 08:16:34.547: WARN/System.err(8366): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
09-27 08:16:34.547: WARN/System.err(8366): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:41)
09-27 08:16:34.547: WARN/System.err(8366): at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1149)
09-27 08:16:34.547: WARN/System.err(8366): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1802)
09-27 08:16:34.557: WARN/System.err(8366): at de.enough.appmate.dbase.CMSResource.updateItem(CMSResource.java:1168)
09-27 08:16:34.557: WARN/System.err(8366): at de.enough.appmate.dbase.CMSResourceUpdater.updateItems(CMSResourceUpdater.java:179)
09-27 08:16:34.557: WARN/System.err(8366): at de.enough.appmate.dbase.CMSResourceUpdater.loadUpdates(CMSResourceUpdater.java:102)
09-27 08:16:34.557: WARN/System.err(8366): at de.enough.appmate.dbase.CMSResourceUpdaterRunnable.run(CMSResourceUpdaterRunnable.java:32)
09-27 08:16:34.557: WARN/System.err(8366): at java.lang.Thread.run(Thread.java:1019)
and this is my code of updateItem method where the database should be updated:
this.db.execSQL("UPDATE " + CMSConstants.ITEMS + " SET ( " +
CMSConstants.ID + ", " +
CMSConstants.TITLE + ", " +
CMSConstants.IS_PAGE + ", " +
CMSConstants.IS_HIDDEN + ", " +
CMSConstants.ITEM_TYPE + ", " +
CMSConstants.ORDER_INDEX + ", " +
CMSConstants.SECTION_ID + ", " +
CMSConstants.TABLE_SECTION_NAME + ", " +
CMSConstants.TABLE_SECTION_ID + ", " +
CMSConstants.IMAGE1_FILE + ", " +
CMSConstants.IMAGE1_CAPTION + ", " +
CMSConstants.IMAGE1_DISPLAY_IN_GALLERY + ", " +
CMSConstants.CATEGORY1 + ", " +
CMSConstants.CATEGORY2 + ", " +
CMSConstants.GEO_LONGITUDE + ", " +
CMSConstants.GEO_LATITUDE + ", " +
CMSConstants.DESCRIPTION + ", " +
CMSConstants.KEYWORDS + ", " +
CMSConstants.BLOCKWORDS + ", " +
CMSConstants.CLEAN_NAME + ", " +
CMSConstants.ADDITIONAL_FIELD1_NAME + ", " +
CMSConstants.ADDITIONAL_FIELD1_VALUE + ", " +
CMSConstants.ADDITIONAL_FIELD2_NAME + ", " +
CMSConstants.ADDITIONAL_FIELD2_VALUE + ", " +
CMSConstants.ADDITIONAL_FIELD3_NAME + ", " +
CMSConstants.ADDITIONAL_FIELD3_VALUE + ", " +
CMSConstants.ADDITIONAL_FIELD4_NAME + ", " +
CMSConstants.ADDITIONAL_FIELD4_VALUE + ", " +
CMSConstants.ADDRESS_LINE1 + ", " +
CMSConstants.ADDRESS_LINE2 + ", " +
CMSConstants.ADDRESS_LINE3 + ", " +
CMSConstants.ADDRESS_LINE4 + ", " +
CMSConstants.ADDRESS_LINE5 + ", " +
CMSConstants.ADDRESS_POSTCODE + ", " +
CMSConstants.CONTACT_EMAIL + ", " +
CMSConstants.CONTACT_EMAIL_DISPLAY + ", " +
CMSConstants.CONTACT_EMAIL_SUBJECT + ", " +
CMSConstants.CONTACT_TEL + ", " +
CMSConstants.CONTACT_TEL_DISPLAY + ", " +
CMSConstants.CONTACT_WEB + ", " +
CMSConstants.CONTACT_WEB_DISPLAY + ", " +
CMSConstants.MODIFICATION_DATE + ", " +
CMSConstants.PAGE_HEADER +
" ) VALUES ( " +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,? );", bindArgs);
I don't understand where the problem is. I looked on the code and there is no problem near "(".
Hope someone can help me.
thanx
newone
EDIT:
This is my new query
this.db.execSQL("UPDATE " + CMSConstants.ITEMS + " SET " +
CMSConstants.ID + "= ?, " +
CMSConstants.TITLE + " = ?, " +
CMSConstants.IS_PAGE + " = ?, " +
CMSConstants.IS_HIDDEN + " = ?, " +
CMSConstants.ITEM_TYPE + " = ?, " +
CMSConstants.ORDER_INDEX + " = ?, " +
CMSConstants.SECTION_ID + " = ?, " +
CMSConstants.TABLE_SECTION_NAME + " = ?, " +
CMSConstants.TABLE_SECTION_ID + " = ?, " +
CMSConstants.IMAGE1_FILE + " = ?, " +
CMSConstants.IMAGE1_CAPTION + " = ?, " +
CMSConstants.IMAGE1_DISPLAY_IN_GALLERY + " = ?, " +
CMSConstants.CATEGORY1 + " = ?, " +
CMSConstants.CATEGORY2 + " = ?, " +
CMSConstants.GEO_LONGITUDE + " = ?, " +
CMSConstants.GEO_LATITUDE + " = ?, " +
CMSConstants.DESCRIPTION + " = ?, " +
CMSConstants.KEYWORDS + " = ?, " +
CMSConstants.BLOCKWORDS + " = ?, " +
CMSConstants.CLEAN_NAME + " = ?, " +
CMSConstants.ADDITIONAL_FIELD1_NAME + " = ?, " +
CMSConstants.ADDITIONAL_FIELD1_VALUE + " = ?, " +
CMSConstants.ADDITIONAL_FIELD2_NAME + " = ?, " +
CMSConstants.ADDITIONAL_FIELD2_VALUE + " = ?, " +
CMSConstants.ADDITIONAL_FIELD3_NAME + " = ?, " +
CMSConstants.ADDITIONAL_FIELD3_VALUE + " = ?, " +
CMSConstants.ADDITIONAL_FIELD4_NAME + " = ?, " +
CMSConstants.ADDITIONAL_FIELD4_VALUE + " = ?, " +
CMSConstants.ADDRESS_LINE1 + " = ?, " +
CMSConstants.ADDRESS_LINE2 + " = ?, " +
CMSConstants.ADDRESS_LINE3 + " = ?, " +
CMSConstants.ADDRESS_LINE4 + " = ?, " +
CMSConstants.ADDRESS_LINE5 + " = ?, " +
CMSConstants.ADDRESS_POSTCODE + " = ?, " +
CMSConstants.CONTACT_EMAIL + " = ?, " +
CMSConstants.CONTACT_EMAIL_DISPLAY + " = ?, " +
CMSConstants.CONTACT_EMAIL_SUBJECT + " = ?, " +
CMSConstants.CONTACT_TEL + " = ?, " +
CMSConstants.CONTACT_TEL_DISPLAY + " = ?, " +
CMSConstants.CONTACT_WEB + " = ?, " +
CMSConstants.CONTACT_WEB_DISPLAY + " = ?, " +
CMSConstants.MODIFICATION_DATE + " = ?, " +
CMSConstants.PAGE_HEADER + " = ?"
, bindArgs);
and this is the new error:
09-27 09:39:03.105: WARN/System.err(8903): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
09-27 09:39:03.105: WARN/System.err(8903): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
09-27 09:39:03.115: WARN/System.err(8903): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
09-27 09:39:03.115: WARN/System.err(8903): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1809)
09-27 09:39:03.115: WARN/System.err(8903): at de.enough.appmate.dbase.CMSResource.updateItem(CMSResource.java:1221)
09-27 09:39:03.115: WARN/System.err(8903): at de.enough.appmate.dbase.CMSResourceUpdater.updateItems(CMSResourceUpdater.java:178)
09-27 09:39:03.115: WARN/System.err(8903): at de.enough.appmate.dbase.CMSResourceUpdater.loadUpdates(CMSResourceUpdater.java:102)
09-27 09:39:03.115: WARN/System.err(8903): at de.enough.appmate.dbase.CMSResourceUpdaterRunnable.run(CMSResourceUpdaterRunnable.java:32)
09-27 09:39:03.115: WARN/System.err(8903): at java.lang.Thread.run(Thread.java:1019)
A: try this
this.db.execSQL("UPDATE " + CMSConstants.ITEMS + " SET "+CMSConstants.ID+"="+value)
i think your query is wrong..
simple update query
"UPDATE TABLE_NAME SET COLUMN_NAME=COLUMN_VALUE"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: retrieve thumbnail image of a browser bookmark I am creating my own android app widget to display browser bookmarks. & i need 2 show the thumbnail image of the bookmarks in my widget.
However the Browser.BookmarkColumns doesnt expose the "thumbnail" data.
any idea on how to get the thumbnail image ?
thanx in advance
A: It does expose the fav icon of the website. But its available in the database if that bookmark url was successfully visited at least once. Also when accessing the internal Android databases use the managedQuery() method.
Here is a snippet for accessing the fav icon from db.
Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
mCur.moveToFirst();
int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.FAVICON);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone command line Unit Tests (and File I/O) The short question is: How can I get iPhone (objective-c) file operations to work correctly from a command line Unit Test?
The long question, with explanation: This will eventually become a script to perform automated building/testing for my iPhone build, via a Hudson instance. Following makdad's link on this SO question has allowed me to run Unit tests from the command line (semi) successfully.
However, one of my tests fails. The test would call a Caching Service class to save a file, then try and retrieve it. however, file I/O appears to not work when running the tests from the command line :(.
For Reference, running the Unit tests via the Xcode GUI results in no such errors.
I am using NSFileHandle method calls to get handles for writing. if they return nil, the file is created using
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
I thought it may have to do with the spaces in the path to the simulator's cache directory. am I on the right track? if so, how would i rectify this?
Note also that the simulator needs to be NOT running already in order for this to work, the simulator is started programmatically and does not display a GUI. if it is running, the command line build fails.
A: First: 'the simulator needs to be NOT running already in order for this to work'
I have my tests running in the terminal and it doesn't matter if the simulator is on.
Maybe some build settings you have to look at are: TEST_HOST and BUNDLE_LOADER.
I leave them empty in my xcodeproj.
Note: I'm using Hudson as well with test reports and code coverage.
Second:
I have experienced failures in tests terminal and application with loading paths. This was related to the Core Data model which is loaded from a resource.
The solution was to load the file from url instead of a path:
[[NSBundle bundleForClass:[self class]] URLForResource:....];
I cannot ensure this relates to the same problem your encountering with the NSFileManager, but i can only imagine that NSBundle makes use of the NSFileManager. (So this can be related)
Third:
Do not make your tests dependent on I/O.
I find that that is not the purpose of a Unit Test. Such test may not rely on a filesystem, database, network connection, etc.
Make an file system abstraction class that you mock while running your tests.
This way your implementation is only at one place relying on the actual file system, which you can replace during testing.
You only need one test to check that abstraction.
Summary
*
*The first will improve your test setup.
*The second will hopefully solve your test problem.
*The third will reduce the occurrence of the problem and improve your code.
Hope this was helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: How to write the Stored Procedure I am having one situation,
Book Number | Book Authors | Publications | Versions
Controls i used in above fields, label in Book No., Combo box in Book Authors, Label in Publications and Combo box in Versions.
The above is my UI, if i choose the book authors from the combo box(values in combo box are retrieving from db), the values of publications and versions should retrieve from the db based upon the item i choose from the combo box. The page should not refresh. How to write the stored procedure for this.
A: It seems like you really are asking the wrong question. There are a couple good answers here for how to write a select statement (via a stored procedure, or not).
However, getting the data from the database has little to do with to putting that data into the appropriate controls on your UI, and nothing to do with making sure the page does not refresh.
If you are really interested in how to how to write a stored procedure for a simple select statement, accept @MikaelEriksson's answer, but add appropriate SET statements to minimize future upgrade issues. You will also need to modify the column and table names to reflect your actual data (of course).
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE GetBooksByAuthorID
@AuthorID int
AS
BEGIN
SELECT B.BookName,
B.BookID
FROM Books as B
WHERE B.AuthorID = @AuthorID
ORDER BY B.BookName
END
GO
If you are interested in how to bind the data to your UI, and how to do it without refreshing the UI; then you need to ask a new question about that. It should be specific to your web framework. Generally speaking, if you want web UI update without refresh, you will be using some form of AJAX.
A: If what you're trying to do is just cascading boxes, you write a SELECT query that return the appropriate rows. This is not what a stored procedure does.
SELECT * FROM `books` WHERE `author_id` = [author_id]
Stored procedures are used to process data, not select it.
A: Check this Sites to Start of:
HOW TO: Call a Parameterized Stored Procedure by Using ADO.NET and Visual C# .NET
Calling Stored procedures in ADO.NET
The C# Station ADO.NET Tutorial
Regards
A: This is how you write a stored procedure that will fetch something for you. I have of course no idea what output you want and what parameters you need so ...
create procedure GetBooksByAuthorID
@AuthorID int
as
select B.BookName,
B.BookID
from Books as B
where B.AuthorID = @AuthorID
order by B.BookName
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find GO button keycode using Javascript Anyone have idea, how to find GO button's keycode using Javascript in Android browser.
A: The 'Go', 'Enter/Return', 'Search', ... keys are all synonyms of KeyEvent.KEYCODE_ENTER
The KeyboardView only changes its appearance based on EditText inputMethod options.
All result in the character 10 / 0x0A to be produced.
Note that it will be caught and interpreted by webview internal logic unless you catch it yourself by overriding onKeyDown in your activity.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_ENTER)){
mWebView.loadUrl('javascript:handleEnterKey()');
return true;
}
return super.onKeyDown(keyCode, event);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Generating QueryString Param For Static Content Once Per Application I'm generating stylesheet/javascript links all over my website using a single extension method, so i have a place to generate querystring.
Example
http://mydomain.com/site.css?v0.0.1
The plan is when i do a new build, the content should be fetched freshly from the server. No surprises there.
However, i'm trying to figure out the best way to generate this value.
Obviously, ideally, doing something as a MSBuild task is the most ideal, but i've tried and failed that in the past.
We're using SquishIt for most static content, but for files not in the bundle (e.g ones that aren't required on every page), we need to generate the querystring param for the file.
I'm thinking i create a singleton guid on app start, then use that when generating links.
Thoughts?
A: I learned about Knapsack from Steven Sanderson's blog post about Open-source components used in learn.knockoutjs.com. I'm not quite sure, but maybe you should take a look at its quick walk-through
A: I prefer reading the assembly or application version once (either in app_start or do lazy loading in helper method) and use that for building url to my js/css. We change the version number for all releases (internal or external) so works like a charm.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Which credentials should I put in for Google App Engine BulkLoader at JAVA development server? I can't upload data to my GAE Java dev serwer. Bulkloader asks for a password, but no password matches:
D:\python_google_appengine>appcfg.py upload_data --config_file=bulkloader.yaml --filename=templates.csv --url=http://localhost:8080/remote_api --kind=EmailMessageTemplate --application=myappid --insecure
Uploading data records.
[INFO ] Logging to bulkloader-log-20110927.084025
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20110927.084025.sql3
Please enter login credentials for localhost
Email: m@gmail.com
Password for m@gmail.com:
[INFO ] Connecting to localhost:8080/remote_api
2011-09-27 08:40:44,062 WARNING appengine_rpc.py:435 ssl module not found.
Without the ssl module, the identity of the remote host cannot be verified, and
connections may NOT be secure. To fix this, please install the ssl module from
http://pypi.python.org/pypi/ssl .
To learn more, see http://code.google.com/appengine/kb/general.html#rpcssl .
Please enter login credentials for localhost
Email: Interrupted.
Then how to create credentials with a password on Java dev server or bypass password requirement?
I've read answers from here Which credentials should I put in for Google App Engine BulkLoader at development server? and comments for this issue http://code.google.com/p/googleappengine/issues/detail?id=2440 but it is all about Python dev server not Java.
A: Maybe this is temporary issue. Try redeploying application, and restart all the stuff. Use any email and empty password.
A: For development server of GAE
(1) use browser to goto http://localhost:8080/_ah/login in order check admin email. The default is test@example.com
(2) add --email=test@example.com --passin to the appcfg.py parameters and just press enter for the password prompt
(3) the application id has the prefix of dev~ for development server e.g. application=dev~myappid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to get variable data out side of when condition i declare a variable name as Result1 this variable i have used in when conditions
so that variable i want to used out side of when condition. facing issues as variable name as OUT of scope , to resolve this issue can we declare a global variable as gblresult.
how we can pass result1 content to gblresult, but i dont know how to implement. kindly suggest me some thing
A: Is this perhaps what you want?
<xsl:variable name="result">
<xsl:choose>
<xsl:when test="...">...</xsl:when>
<xsl:when test="...">...</xsl:when>
...
</xsl:choose>
</xsl:variable>
<!-- use variable result here-->
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with loading an XML file or writing to it I have a GUI application which reads data from an XML file (current_users.xml) and also writes to that XML file. GUI is placed at /var/www/bin-release and XML files are located in the directory /home/os/work2/project/
The GUI expects the XML file to be in the directory: /var/www/bin-release. So I created a symlink to /home/os/work2/project/current_users.xml in /var/www/bin-release. This with some other settings given below works fine on a number of PCs but on one particular PC, this setup does not cause the GUI to access the XML file rightly i.e. it neither reads nor writes to the XML file.
sudo ln -s /home/os/work2/current_users.xml /var/www/bin-release/current_users.xml
sudo chmod ug+rwx -R /var/www/bin-release
sudo chown $USER:www-data -R /var/www
sudo chown root:root /home/os/work2/current_user.xml
sudo chmod 666 /home/os/work2/current_users.xml
sudo usermod -a -G www-data $USER
Apache is being run by www-data as viewed via the output of ps -aux | grep apache
Warning: bad ps syntax, perhaps a bogus '-'? See http://procps.sf.net/faq.html
root 1442 0.0 0.3 36372 7528 ? Ss 11:22 0:00 /usr/sbin/apache2 -k start
www-data 1452 0.0 0.3 36972 6308 ? S 11:22 0:00 /usr/sbin/apache2 -k start
www-data 1453 0.0 0.3 36948 6300 ? S 11:22 0:00 /usr/sbin/apache2 -k start
www-data 1454 0.0 0.3 36836 6292 ? S 11:22 0:00 /usr/sbin/apache2 -k start
www-data 1455 0.0 0.2 36948 4820 ? S 11:22 0:00 /usr/sbin/apache2 -k start
www-data 1457 0.0 0.2 36948 4724 ? S 11:22 0:00 /usr/sbin/apache2 -k start
www-data 2325 0.0 0.2 36700 4656 ? S 11:24 0:00 /usr/sbin/apache2 -k start
www-data 2343 0.0 0.2 36700 4656 ? S 11:24 0:00 /usr/sbin/apache2 -k start
www-data 2344 0.0 0.2 36460 4864 ? S 11:24 0:00 /usr/sbin/apache2 -k start
tahir 6686 0.0 0.0 4012 764 pts/0 S+ 11:50 0:00 grep --color=auto apache
A: You might not have permission to enter the directory:
$ chmod +x /home/os/work2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem in adding admob ads in layout I have Admob ads Network in my app..I placed this ads Network in my relative layout..In these relative layout i have buttons..so at the bottom of the layout i put my addNetwork to display ads.Now the problem is that onClick of my button i open an dialog..In these dialog i have EditText so when i click on edit text an input keyboard is open and here the problem arise..
As soon as the input keyboard arises the layout become shrink and when the cancel the keyboard again the layout become resize..but when i remove my adsNetwork layout from that relative layout and agin do the same process than the layout doesnt shring..why these happen can anyone please suggest me..i have send my xml layout..
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:layout_marginTop="20dp" android:id="@+id/linearLayout" android:orientation="horizontal"
android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:background="#00000000"
android:gravity="center_horizontal|center_vertical" android:layout_height="wrap_content" android:layout_width="fill_parent">
<Button android:id="@+id/btn_prev_month"
android:textColor="#000000"
android:layout_width="53dp"
android:layout_height="40dp"
android:gravity="center_horizontal|center_vertical"
android:background="@drawable/prev_btn_bg_selector">
</Button>
<TextView android:id="@+id/txt_month"
android:textSize="18dp"
android:textColor="#000000"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btn_Prev_month"
android:gravity="center_horizontal|center_vertical">
</TextView>
<TextView android:id="@+id/txt_year"
android:textSize="18dp"
android:textColor="#000000"
android:layout_width="50dp"
android:layout_marginRight="5dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/txt_month"
android:gravity="center_horizontal|center_vertical">
</TextView>
<Button android:id="@+id/btn_next_month"
android:textColor="#000000"
android:layout_width="53dp"
android:layout_height="40dp"
android:layout_toRightOf="@+id/txt_year"
android:gravity="center_horizontal|center_vertical"
android:background="@drawable/next_btn_bg_selector">
</Button>
</LinearLayout>
<ViewFlipper android:id="@+id/flipview" android:layout_below="@+id/linearLayout" android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<LinearLayout android:id="@+id/liVLayout" android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
</ViewFlipper>
<LinearLayout android:id="@+id/linearLayout1" android:orientation="vertical" android:layout_marginLeft="7dp"
android:layout_marginRight="7dp" android:layout_below="@+id/flipview" android:layout_height="wrap_content"
android:layout_width="fill_parent" android:background="#00000000">
<TextView android:id="@+id/txt_status"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginTop="10dp"
android:textColor="#000000">
</TextView>
<TextView android:id="@+id/txt_notes"
android:layout_width="fill_parent" android:layout_below="@+id/txt_status"
android:layout_marginTop="5dp"
android:layout_height="wrap_content"
android:maxHeight="18dp"
android:textColor="#000000">
</TextView>
</LinearLayout>
<LinearLayout android:id="@+id/bottom_control_bar" android:layout_marginTop="8dp" android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_alignParentBottom="true">
<com.google.ads.AdView android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="XXXXXXXXX"
ads:adSize="BANNER"
ads:loadAdOnCreate="true">
</com.google.ads.AdView>
</LinearLayout>
</RelativeLayout>
A: Hi use this may be it's solve your problem:
android:windowSoftInputMode="adjustPan" in your manifest file in activity
second:
android:gravity="bottom" set in LinearLayout
<LinearLayout android:id="@+id/bottom_control_bar"
android:layout_marginTop="8dp" android:orientation="horizontal"
android:layout_width="fill_parent" android:gravity="bottom"
android:layout_height="wrap_content" android:layout_alignParentBottom="true">
<com.google.ads.AdView android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="xcxxxcxcxc"
ads:adSize="BANNER"
ads:loadAdOnCreate="true">
</com.google.ads.AdView>
</LinearLayout>
see this link :
http://android-developers.blogspot.com/2009/04/updating-applications-for-on-screen.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: App name showing incorrectly on the ticker We have an old name for the app and we want the app to show the correct name on the ticker but we have not been able to do it (it is still showing the old name). We updated the title of the url canvas and submitted it on the debugger and interestingly enough, the title is taken correctly on the https address (it is shown on the debugger page but not in the ticker) but not on the http url. Actually it says for the http that the app has problems with the meta tags. Any idea on how to fix this problem? Thanks a Lot, Gilmer
A: Go to http://developers.facebook.com/tools/debug
Enter your url in that and try to generate all the information.
If that is not showing any errors in that, then scroll down at the end of the page.
You will find block named as "URLs"
Click on the first link named as: "Graph API:".
This will solve your issue.
In future, if you are going to change any content from your page, then don't forget to do the same process once again.
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to print out registers in Linux kernel? I want to print out values of a couple of registers from the linux kernel code running on ARM. Particularly I have the following assembly in linux -
e3c52007 bic r2, r5, #7 ; 0x7
e1520003 cmp r2, r3
0a000003 beq c011fa60 <smem_find+0x40>
How do I print out the values of r2, r3 and r5 in kmsg? I do not want to use the variable names and want to get the values from registers.
A: I'm not that familiar with kernel development and easy ways to debug, but this would do the job I guess.
size_t r2, r3, r5;
asm ("str r2, %[r2]\n"
"str r3, %[r3]\n"
"str r5, %[r5]\n"
: [r2]"=m" (r2), [r3]"=m" (r3), [r5]"=m" (r5));
printk("r2=%u r3=%u r4=%u\n", r2, r3, r5);
Edit: Now with ARM assembly instead of x86 :p
A: You can call show_regs(struct pt_regs * regs). This function will diplay all the registrs on the pt_regs structure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can i select from table where tablename is specified as SqlParameter? I am trying to perform dynamic sql select where I am selecting from a table using a parameter.
SELECT null FROM @TableName
However I am getting error must declare table variable @TableName. I suspect this is because I am selecting from a table using a variable. I have not needed to do this before.
List<SqlParameter> sqlParams = new List<SqlParameter>()
{
new SqlParameter("TableName", "testtable"),
new SqlParameter("FieldName", "testfield"),
new SqlParameter("Find", "testfind"),
};
string sqlSelect = "SELECT null FROM @TableName
WHERE @FieldName LIKE '%' + @Find + '%' ";
DataTable dtSelect = SqlHelper.ExecuteDataset(sqlConn, CommandType.Text,
sqlSelect, 30, sqlParams.ToArray()).Tables[0];
//30 = timeout
How can I perform the above using dynamic sql? (no stored procedures please)
A: You cannot use parameters for things like table and column names. For those you could have a whitelist of possible values and then use string concatenation when building the SQL query.
A: You can't use parameters like that, so you have to build the query as a string. You could do that in SQL, but you can also just create the string in the C# code.
Make sure that the table name and field name are safe and trusted values, and doesn't come directly from an unsafe source like a web request.
string tableName = "testtable";
string fieldName = "testfield";
List<SqlParameter> sqlParams = new List<SqlParameter>() {
new SqlParameter("Find", "testfind"),
};
string sqlSelect =
"SELECT null " +
"FROM " + tableName + " " +
"WHERE " + fieldName + " LIKE '%' + @Find + '%' ";
A: private DataTable ExecuteDynamic(string TableName,string FieldName, string Find)
{
string sqlSelect = "SELECT * FROM " + TableName +
" WHERE " + FieldName + " LIKE '%'" + Find + "'%' ";
using (connection = new SqlConnection(Strcon))
connection.Open();
{
using (cmd = new SqlCommand(sqlSelect, connection))
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 60;
adpt = new SqlDataAdapter(cmd);
dt = new DataTable();
adpt.Fill(dt);
return (dt);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Django many to many relation on generic models I have some models which will need to have many to many relation with some images. Instead of creating each relation individually, I want to have some generic model relations that I can use for all my models. So I've created Image and ImageItem models (I'm not sure if I'm on the right track..):
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
class Image(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images')
class ImageItem(models.Model):
image = models.ForeignKey(Image)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
What I want to do is, every time I create a new image, I want to select which objects I want to assign this image to. So into the admin I need to have something like:
Image: chicago_bulls.jpg
Selected model: Player
Selected:
Michael Jordan
Scotie Pippen
or
Image: kobe_bryant.jpg
Selected model: Team
Selected:
Los Angeles Lakers
US National Team
Is my model design correct? I also want to use ModelMultipleChoiceField for that but I couldn't figure out how to do that.
A: Take a look at the docs explaining the GenericInlineModelAdmin.
If i get you right, the example does exactly what you want:
class Image(models.Model):
image = models.ImageField(upload_to="images")
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey("content_type", "object_id")
class Product(models.Model):
name = models.CharField(max_length=100)
It's a bit different from your design, as the image field is part of model that adds generic relations to all kind of other (content) objects/models.
That way you can simply attach images via the admin interface using the already mentioned InlineAdmins:
class ImageInline(generic.GenericTabularInline):
model = Image
class ProductAdmin(admin.ModelAdmin):
inlines = [
ImageInline,
]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ZipArchive::getFromName does not find filename Any idea what I am doing wrong here? It keeps dying with 'bye bye'. There is an index.php file inside the zip archive.
$zip = new ZipArchive;
$zip->open($source);
$test = $zip->getFromName('index.php');
if(!$test) {
die('bye bye');
} else {
die($test);
}
A: Well, the first thing you should do is ensure that you've opened it okay since that can fail as well:
$zip = new ZipArchive;
$rc = $zip->open($source);
if ($rc === TRUE) {
$test = $zip->getFromName('index.php');
$zip->close();
if(!$test) {
die('bye bye');
} else {
die($test);
}
} else {
die("could not open: " . $rc);
}
Other than that, make sure you are absolutely certain that your file specification is correct. If necessary, you can use getNameIndex to enumerate the entries one at a time, printing out their names in the process, something like:
$zippy = new ZipArchive();
$zippy->open($source);
for ($i = 0; $i < $zippy->numFiles; $i++) {
echo $zippy->getNameIndex($i) . '<br />';
}
$zippy->close();
And I'm assuming that I would be wasting my time telling you to check the value of $source. You may want to check, just in case.
A: As at PHP 8 this can also occur if you are busy building an archive and you try and use getFromName() on a valid file in the archive. I got false no matter what I tried.
eg.
1 create archive
2 ...add things
3 archive->getFromName("valid/archive/file/path/and/name")
Step 3 returns false every time.
However
1 create archive
2 ...add things
A close archive
B re-open archive
3 archive->getFromName("valid/archive/file/path/and/name")
Step 3 now returns the contents of the file as expected.
So inserting steps A and B made getFromName() work as expected.
Hope this helps someone not waste as much time as I just did :(
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HsqlException: data exception I am using hsqldb version 2.2.5 in my application sometimes I am getting
org.hsqldb.HsqlException: data exception: string data, right truncation.
So I want to know what are the possible reasons for that. I am not inserting any data like longvarchar in a varchar column.
http://sourceforge.net/tracker/index.php?func=detail&aid=2993445&group_id=23316&atid=378131
I searched above link but could not get proper feedback.
Given below the exception stack
This exception is not happening frequently.
So what could be the reason for that and how to set the data type length in script file to increase at run time ?
java.sql.SQLException: data exception: string data, right truncation
at org.hsqldb.jdbc.Util.sqlException(Util.java:255)
at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(JDBCPreparedStatement.java:4659)
at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(JDBCPreparedStatement.java:311)
at com.dikshatech.agent.db.NodesRuntimeTable.persistData(NodesRuntimeTable.java:151)
at com.dikshatech.agent.jobs.WorkFlowJob.execute(WorkFlowJob.java:108)
at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: org.hsqldb.HsqlException: data exception: string data, right truncation
at org.hsqldb.error.Error.error(Error.java:134)
at org.hsqldb.error.Error.error(Error.java:104)
at org.hsqldb.types.CharacterType.castOrConvertToType(CharacterType.java:523)
at org.hsqldb.types.CharacterType.convertToType(CharacterType.java:638)
at org.hsqldb.StatementDML.getInsertData(StatementDML.java:921)
at org.hsqldb.StatementInsert.getResult(StatementInsert.java:124)
at org.hsqldb.StatementDMQL.execute(StatementDMQL.java:190)
at org.hsqldb.Session.executeCompiledStatement(Session.java:1344)
at org.hsqldb.Session.execute(Session.java:997)
at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(JDBCPreparedStatement.java:4651)
A: Your field length is not large enough. I used the LONGVARCHAR data type to fix this error.
CREATE TABLE "DEMO_TABLE" ("ID" NUMBER(19,0), "MESSAGE" LONGVARCHAR);
WARNING: Rant follows...
Yep, the error message java.sql.SQLException: data exception: string data, right truncation... makes total sense only after you know what's wrong. Occasionally I find a clear, well-written error message, meant to inform users. The time it takes to write one will be returned 100 fold (or more depending on usage), but usually to others. Hence, there is too little incentive for most to spend the time. It can however come back to benefit the product, as with the Spring Framework which has generally superior error messages.
I'm sure stackoverflow.com does not mind. Poor error messages likely drive people here every minute of every day!
A: I encountered this error while using Hibernate with HSQLDB. Instead of the usual String field, the offender was a serializable field.
Hibernate mapping file was
<hibernate-mapping package="in.fins.shared">
<class name="Data">
<id name="id" column="id">
<generator class="uuid" />
</id>
<property name="date" column="Date" />
<property name="facts" column = "facts" type="serializable" />
</class>
</hibernate-mapping>
For facts field, which is set to serializable, Hibernate creates a column of type VARBINARY with maximum length 255 in HSQLDB. As serialized object size was more than this size data exception: string data, right truncation was thrown by HSQLDB.
Changing the facts column to Blob with sql-type attribute resolves the problem.
<property name="facts" type="serializable">
<column name="facts" sql-type="blob" />
</property>
A: The maximum size of a VARCHAR column is user-defined. If the inserted data is larger than this, an exception is thrown. The example below defines a table with a VARCHAR(100) column, which limits the size to 100 characters.
CREATE TABLE T (ID INT, DATA VARCHAR(100))
You can use a database manager and execute the SCRIPT command to see all your table definitions and their column size. Alternatively, SELECT * FROM INFORMATION_SCHEMA.COLUMNS shows the characteristics of each column.
You can use the ALTER TABLE table_name ALTER COLUMN col_name SET DATA TYPE to increase the size of an existing column.
A: For Hibernate/HSQLDB automatically generated schema via @Column annotation on @Entity field of type String you might need to provide length atrribute. Otherwise the length will default to 255 and long input will not fit:
@Lob
@Column(name="column_name", length = 1000)
private String description;
A: I actually faced the same problem, and got fixed relatively quickly.
In my case I've declared a DB table column column like this: description VARCHAR(50), but I was trying to insert a longer string/text in there, and that caused the exception.
Hope this will help you :)
A: I had the same problem as you describe while testing with HSQLDB.
I'm using hibernate as JPA implementation and this is my mapping class:
@Column (name = "file")
private byte[] file;
In production I'm using PostgreSQL and the problem don't shown up, but with HSQL I had to add the @Type annotation in my mapping to solve that error:
@Column (name = "file")
@Type(type = "org.hibernate.type.MaterializedBlobType")
private byte[] file;
There are many implementations of types. You can take a look at hibernate-core jar, inside the package org.hibernate.type and pick some that matches your mappings.
A: This error occurs in some scenario's but in the following scenario it is difficult
to retrieve the cause, assume following scenario:
Assume the following entity
@Entity
public class Car {
private String name;
@ManyToOne
@JoinColumn(name = "ownerId")
private Owner owner;
...
When the annotation '@ManyToOne' would be forgotten, but the annotation ' @JoinColumn(name = "ownerId")' would be present! This error would occur, which doesn't really indicate the real issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: PHP - Compare two MySQL tables Is there a PHP code that let's you compare 2 MySQL tables with each other and lets you add missing entries into one?
I have two tables. hs_hr_employee and rights. I want to add data from certain columns from the hs_hr_employee table so that they would be the same in the rights tables.
hs_hr_employee has multiple rows, whereas the rights table has 5 rows. The rights table gets the info from 4 columns from the hs_hr_employee table, emp_number, employee_id, emp_firstname, emp_lastname
Below is the code:
<?php
$connection = mysql_connect('localhost','admin','root');
if( isset($_POST['submit']) )
{
if( isset( $_POST['cb_change'] ) && is_array( $_POST['cb_change'] ))
{
foreach( $_POST['cb_change'] as $emp_number => $permission)
{
$sql = "UPDATE `rights` SET Permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'";
echo __LINE__.": sql: {$sql}\n";
mysql_query( $sql );
}
}
}
?>
<p style="text-align: center;">
<span style="font-size:36px;"><strong><span style="font-family: trebuchet ms,helvetica,sans-serif;"><span style="color: rgb(0, 128, 128);">File Database - Administration Panel</span></span></strong></span></p>
<p style="text-align: center;">
</p>
<head>
<style type="text/css">
table, td, th
{
border:1px solid #666;
font-style:Calibri;
}
th
{
background-color:#666;
color:white;
font-style:Calibri;
}
</style>
</head>
<form method="post" action="admin.php">
<?php
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('users', $connection);
//mysql_query('INSERT into rights(Emp_num, ID, Name, Surname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee');
$result = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, Permissions FROM rights");
mysql_query("INSERT INTO rights (emp_number, employee_id, emp_firstname, emp_lastname)
SELECT emp_number, employee_id, emp_firstname, emp_lastname
FROM hs_hr_employee
ON DUPLICATE KEY UPDATE employee_id = VALUES(employee_id), emp_number = VALUES(emp_number)
");
echo "<center>";
echo "<table >
<tr>
<th>Employee Number</th>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Permissions</th>
<th>Change</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['emp_number'] . "</td>";
echo "<td>" . $row['employee_id'] . "</td>";
echo "<td>" . $row['emp_firstname'] . "</td>";
echo "<td>" . $row['emp_lastname'] . "</td>";
echo "<td>" . $row['Permissions'] . "</td>";
echo "<td> <select name='cb_change[]'><option value='all'>All</option> <option value='remote'>Remote Gaming</option> <option value='landbased'>Landbased Gaming</option> <option value='general'>General Gaming</option> </select> </td>";
echo "</tr>" ;
}
#echo "<td>" . $row['Change'] . "</td>";
echo "</table>";
echo "</center>";
#$_POST['cb_permissions'];
mysql_close($connection);
?>
<p style="text-align: center;">
</p>
<p style="text-align: center;">
</p>
<p style="text-align: right;">
<input name="Save_Btn" type="button" value="Save" />
</p>
</form>
Any idea how to do it?
Thanks,
Brian
A: I'd go with an INSERT INTO SELECT here.
Assume you recognize an employee by the Social Security Number (ssn), and you use this value to update, for instance, name and birthyear:
mysql_query("
INSERT INTO hs_hr_employee (ssn, name, birthyear)
SELECT ssn, name, birthyear
FROM hs_hr_rights
ON DUPLICATE KEY UPDATE name = VALUES(name), birthyear = VALUES(birthyear)
");
You can also add a WHERE in between FROM and ON DUPLICATE. Like so:
...
FROM hs_hr_rights
WHERE birthyear IS NULL
ON DUPLICATE KEY UPDATE name = VALUES(name), birthyear = VALUES(birthyear)
...
Although, I don't see the need of copying values since in most cases you can fetch them through JOINs.
A: select * from table a where a.common not in (select b.common from table b where a.common = b.common)
And run this as well
select * from table b where b.common not in (select a.common from table a where a.common = b.common)
Not possible in php but in mysql its ans is as above
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compact command not freeing up space in MongoDB 2.0 I just installed MongoDB 2.0 and tried to run the compact command instead of the repair command in earlier versions. My database is empty at the moment, meaning there is only one collection with 0 entries and the two system collections (indices, users). Currently the db takes about 4 GB of space on the harddisk. The db is used as a temp queue with all items being removes after they have been processed.
I tried to run the following in the mongo shell.
use mydb
db.theOnlyCollection.runCommand("compact")
It returns with
ok: 1
But still the same space is taken on the harddisk. I tried to compact the system collections as well, but this did not work.
When I run the normal repair command
db.repairDatabase()
the database is compacted and only takes 400 MB.
Anyone has an idea why the compact command is not working?
Thanks a lot for your help.
Best
Alex
A: Collection compaction is not supposed to decrease the size of data files. Main point is to defragment collection and index data - combine unused space gaps into continuous space allowing new data to be stored there. Moreover it may actually increase the size of data files:
Compaction may increase the total size of your data files by up to 2GB. Even in this case, total collection storage space will decrease.
http://www.mongodb.org/display/DOCS/compact+Command#compactCommand-Effectsofacompaction
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: how to get same xmpp connection from one activity to another? i am new programmer.i would like to implement sample application for getting chat by using xmpp server.In this implementation i have created connection by using ConnectionConfiguration object as follows :
ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(sport), service);
I am passing connConfig object to XMPPConnection class by calling connect method i am getting connection and by calling login method passing with user name pand password then i am login to password.to login i am using a button.When i clicked on button i am using Intent for change the activity.One i am changing activity i would like to get the same connection in another activity.
I have written code for LoginActivity as follows:
public class LoginActivity extends Activity
{
ConnectionConfiguration connConfig ;
XMPPConnection connection;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
((Button)findViewById(R.id.login)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0)
{
connConfig =new ConnectionConfiguration(host, Integer.parseInt(sport), service);
connection = new XMPPConnection(connConfig);
connection.connect();
connection.login(uname, password);
}
});
}
}
I have written ChatPageActivity as follows:
public class ChatPage extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.chatpage);
//How to get the same XMPPConnection from LoginActivity here
}
}
how to get the same connection from LoginActivity to ChatPageActivity?
please any body help me
A: Create a new class (inside a new .java file), using the singleton pattern (http://en.wikipedia.org/wiki/Singleton_pattern), where you can keep the current active connection accessible from any point of your application.
Possible solution:
public class XMPPLogic {
private XMPPConnection connection = null;
private static XMPPLogic instance = null;
public synchronized static XMPPLogic getInstance() {
if(instance==null){
instance = new XMPPLogic();
}
return instance;
}
public void setConnection(XMPPConnection connection){
this.connection = connection;
}
public XMPPConnection getConnection() {
return this.connection;
}
}
Then, on your LoginActivity you set the connection:
XMPPLogic.getInstance().setConnection(connection);
And in the ChatPage you get it:
XMPPLogic.getInstance().getConnection().doStuff()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Problem: control Session timeout My session renews every 20 minutes. I've set timeout to 300 minutes but still it renews probably because Application Pool recycles.
I am storing UserId which is Guid in Session which returns null. Problem is when I use Membership using
Membership.GetUser().ProviderUserKey
it works fine. But obviously it makes a database call. How can I prevent this problem from happening? Why does Membership.GetUser().ProviderUserKey succeeds whereas Session doesn't?
A: In order to complete Jan's and Neil's answers, you should look at your web.config and set both timeouts (sessionState and authentication)
<sessionState timeout="300"/>
Sessionstate timeout specifies the number of minutes a session can be idle before it is abandoned. The default is 20.
<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="300" />
</authentication>
Forms timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.
A: Your session may still be alive (if you set it to 300 minutes) but the ASP.NET membership could be expiring?
Have you increased the authentication timeout too?
<authentication mode="Forms">
<forms loginUrl="Login/" timeout="180"/>
</authentication>
A: You are mixing authentication and session. These are two completely different concepts.
GetUser() return the currently authenticated user form your MemberShipProvider.
Session and authentication have different timeouts - so its valid that your session times out but the user is still authenticated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565298",
"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.