text stringlengths 8 267k | meta dict |
|---|---|
Q: evaluating Visual studio's software setup packaging tool (setup project/ Web setup project) i was in the process of evaluating different tools available for creating the setup package for a newly developed software. i came to know about the visual studio's setup project facility, but couldnt get much help on its capabilities.
Can someone tell me if this tool helps me achieve the below given features
*
*copy/paste files and folders.
*create a text file, and input certain values to it.
*make/update entries to the registery
*check for certain services running on the local/remote system
*reading certain environment variables from the system.
*running a third party application.
*what script language does it support
Other than Visual Studio, I had evaluated InstallShield which does provide support for all the above mentioned actions. But Visual Studio is already available, I was curious to find if it matches InstallShield in capability?
A: Here is the Visual Studio support:
*
*Supported
*Not supported
*Supported
*Not supported
*Not supported
*Somewhat supported ( supports prerequisites )
*No scripting support
What is not supported can be implemented through custom actions (custom code).
The custom code is in form of custom actions, which can be DLLs, batch files, executables or VBScripts, with DLLs being the method recommended by microsoft, written in C/C++.
Here is some more information on what custom actions are and how such custom actions are integrated with the installer:
Custom Actions
If you want an alternative, you can try Advanced Installer. It supports everything you need and it's cheaper than InstallShield.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android change database I'm working on an application which uses SQLite Database on Android.I have a custom DatabaseHelper class,which creates two different sqlite databases and copy them from the assets folder.The problem that I have is that I can't set which database to use in different situations.Here is how my DatabaseHelper class looks like:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper{
private static SQLiteDatabase sqliteDb;
private static DataBaseHelper instance;
private static final int DATABASE_VERSION = 1;
// the default database path is :
// /data/data/pkgNameOfYourApplication/databases/
private static String DB_PATH_PREFIX = "/data/data/";
private static String DB_PATH_SUFFIX = "/databases/";
private static final String TAG = "DataBaseHelper";
private Context context;
/***
* Contructor
*
* @param context
* : app context
* @param name
* : database name
* @param factory
* : cursor Factory
* @param version
* : DB version
*/
public DataBaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
Log.i(TAG, "Create or Open database : " + name);
}
/***
* Initialize method
*
* @param context
* : application context
* @param databaseName
* : database name
*/
public static void initialize(Context context, String databaseName) {
if (instance == null) {
/**
* Try to check if there is an Original copy of DB in asset
* Directory
*/
if (!checkDatabase(context, databaseName)) {
// if not exists, I try to copy from asset dir
try {
copyDataBase(context, databaseName);
} catch (IOException e) {
Log.e(TAG,"Database "+ databaseName+" does not exists and there is no Original Version in Asset dir");
}
}
Log.i(TAG, "Try to create instance of database (" + databaseName
+ ")");
instance = new DataBaseHelper(context, databaseName,
null, DATABASE_VERSION);
sqliteDb = instance.getWritableDatabase();
Log.i(TAG, "instance of database (" + databaseName + ") created !");
}
}
/***
* Static method for getting singleton instance
*
* @param context
* : application context
* @param databaseName
* : database name
* @return : singleton instance
*/
public static final DataBaseHelper getInstance(
Context context, String databaseName) {
initialize(context, databaseName);
return instance;
}
/***
* Method to get database instance
*
* @return database instance
*/
public SQLiteDatabase getDatabase() {
return sqliteDb;
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate : nothing to do");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "onUpgrade : nothing to do");
}
/***
* Method for Copy the database from asset directory to application's data
* directory
*
* @param databaseName
* : database name
* @throws IOException
* : exception if file does not exists
*/
public void copyDataBase(String databaseName) throws IOException {
copyDataBase(context, databaseName);
}
/***
* Static method for copy the database from asset directory to application's
* data directory
*
* @param aContext
* : application context
* @param databaseName
* : database name
* @throws IOException
* : exception if file does not exists
*/
private static void copyDataBase(Context aContext, String databaseName)
throws IOException {
// Open your local db as the input stream
InputStream myInput = aContext.getAssets().open(databaseName);
// Path to the just created empty db
String outFileName = getDatabasePath(aContext, databaseName);
Log.i(TAG, "Check if create dir : " + DB_PATH_PREFIX
+ aContext.getPackageName() + DB_PATH_SUFFIX);
// if the path doesn't exist first, create it
File f = new File(DB_PATH_PREFIX + aContext.getPackageName()
+ DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();
Log.i(TAG, "Trying to copy local DB to : " + outFileName);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
Log.i(TAG, "DB (" + databaseName + ") copied!");
}
/***
* Method to check if database exists in application's data directory
*
* @param databaseName
* : database name
* @return : boolean (true if exists)
*/
public boolean checkDatabase(String databaseName) {
return checkDatabase(context, databaseName);
}
/***
* Static Method to check if database exists in application's data directory
*
* @param aContext
* : application context
* @param databaseName
* : database name
* @return : boolean (true if exists)
*/
private static boolean checkDatabase(Context aContext, String databaseName) {
SQLiteDatabase checkDB = null;
try {
String myPath = getDatabasePath(aContext, databaseName);
Log.i(TAG, "Trying to conntect to : " + myPath);
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Log.i(TAG, "Database " + databaseName + " found!");
checkDB.close();
} catch (SQLiteException e) {
Log.i(TAG, "Database " + databaseName + " does not exists!");
}
return checkDB != null ? true : false;
}
/***
* Method that returns database path in the application's data directory
*
* @param databaseName
* : database name
* @return : complete path
*/
@SuppressWarnings("unused")
private String getDatabasePath(final String databaseName) {
return getDatabasePath(context, databaseName);
}
/***
* Static Method that returns database path in the application's data
* directory
*
* @param aContext
* : application context
* @param databaseName
* : database name
* @return : complete path
*/
private static String getDatabasePath(Context aContext, String databaseName) {
return DB_PATH_PREFIX + aContext.getPackageName() + DB_PATH_SUFFIX
+ databaseName;
}
public boolean executeQuery(String tableName,ContentValues values){
return execQuery(tableName,values);
}
private static boolean execQuery(String tableName,ContentValues values){
sqliteDb = instance.getWritableDatabase();
sqliteDb.insert(tableName, null, values);
return true;
}
public boolean updateSQL(String tableName,String key,String value){
return updateData(tableName,key,value);
}
private static boolean updateData(String tableName,String key,String value){
sqliteDb = instance.getWritableDatabase();
String where = "";
ContentValues values = new ContentValues();
values.put(key, value);
values.put(key, value);
sqliteDb.update(tableName, values, where, new String[] {"3"});
return true;
}
public boolean deleteSQL(String tableName){
return deleteData(tableName);
}
private static boolean deleteData(String tableName){
sqliteDb = instance.getWritableDatabase();
String where = "";
sqliteDb.delete(tableName, where, new String[] {"5"});
return true;
}
public Cursor executeSQLQuery(String query){
return sqliteDb.rawQuery(query,null);
}
/**
* Make queries
*
*/
}
I have two database : the first one is system.sqlite and the second one user.sqlite.
I'm initializing the first one when my app starts :
dbHelper = new DataBaseHelper(this, "system.sqlite", null, 1);
DataBaseHelper.initialize(this, "system.sqlite");
dbHelper.checkDatabase("system.sqlite");
I'm initializing the user's database the same way, when user first login in my application.
After the login I have a few non-activity classes,where I need to insert some data in both of db's :
ContentValues values = new ContentValues();
values.put("objectId", 75);
values.put("objectOid", "boom");
values.put("serverName", "shit");
values.put("locale", "en_US");
values.put("deviceId", 45);
dbHelper.executeQuery("users",values);
But the problem is that even when open my system.sqlite in the first class than close it..and try to open the user.sqlite from another class it's still trying to write to system db. Example :
dbHelper = new DataBaseHelper(context, "system.sqlite", null, 1);
dbHelper.initialize(context, "system.sqlite");
dbHelper.getWritableDatabase();
//do some work
dbHelper.close();
It's not actually working.
Any suggestions how can I get the things to work?
A: Why don't you have separate DataBaseHelper classes? Such as UserDataBaseHelper and SystemDataBaseHelper. I know this sounds simplistic, but if you had a larger project, with two databases, would you lump all the db access into one class?
A: In your DataBaseHelper class there's bunch of static fields, notably instance. They get accessed for example in initialize and execQuery methods. Since you have more than one database, I suggest you get rid of all the singleton-ish code in DataBaseHelper and see if that fixes things.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Embed an application icon using WPF and F# How to embed an application icon into application.exe using WPF and F#? I did not find it anywhere.
A: I think the approach is the same for WPF and WinForms, which in F# means manually!
Please see this answer.
You could also looks at FsEye's source for reference (it's done in WinForms), see line 39 of http://code.google.com/p/fseye/source/browse/tags/1.0.0-final/FsEye/FsEye.fsproj, the file http://code.google.com/p/fseye/source/browse/tags/1.0.0-final/FsEye/IconResource.fs, and line 23 of http://code.google.com/p/fseye/source/browse/tags/1.0.0-final/FsEye/Forms/WatchForm.fs
A: (Update: link is no longer alive -- removed)
Quote:
"Make a .rc file with the following line:
1 ICON "icon.ico"
Then compile it with rc.exe and include the .res file in your project's properties page.
You may also include .resources files in your project but the system will not pull the application icon from those."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C#, collection that holds Lists of different type I currently have a class that holds 3 dictionaries, each of which contains Lists of the same type within each dictionary, but different types across the dictionaries, such as:
Dictionary1<string, List<int>> ...
Dictionary2<string, List<double>>...
Dictionary3<string, List<DateTime>>...
Is there a way to use a different collection that can hold all the Lists so that I can iterate through the collection of Lists? Being able to iterate is the only requirement of such collection, no sorting, no other operations will be needed.
I want to be able to access the List directly through the string or other identifier and access the List's members. Type safety is not a requirement but in exchange I do not want to have to cast anything, speed is the absolutely top priority here.
So, when calculations are performed on the list's members knowledge of the exact type is assumed, such as "double lastValue = MasterCollection["List1"].Last();", whereas it is assumed that List1 is a List of type double.
Can this be accomplished? Sorry that I may use sometimes incorrect or incomplete terminology I am not a trained programmer or developer.
Thanks,
Matt
A: To do that you would have to use a non-generic API, such as IList (not IList<T>) - i.e. Dictionary<string, IList>. Or since you just need to iterate, maybe just IEnumerable (not IEnumerable<T>). However! That will mean that you are talking non-generic, so some sacrifices may be necessary (boxing of value types during retrieval, etc).
With an IList/IEnumerable appraoch, to tweak your example:
double lastValue = MasterCollection["List1"].Cast<double>().Last();
You could, of course, write some custom extension methods on IDictionary<string,IList>, allowing something more like:
double lastValue = MasterCollection.Get<double>("List1").Last();
I'm not sure it is worth it, though.
A: No, what you are trying to do is not possible; namely, the requirement for strong-typing on all of the lists without casting is what's preventing the rest.
If your only requirement is to iterate through each of the items in the list, then you could create your dictionary as a Dictionary<string, IEnumerable> (note the non-generic interface). IEnumerable<T> derives from IEnumerable which would allow you to iterate through each item in the list.
The problem with this is that you would have to perform a cast at some point either to the IEnumerable<T> (assuming you know you are working with it) or use the Cast<T> extension method on the Enumerable class (the latter being worse, as you might incur boxing/unboxing, unless it does type-sniffing, in which case, you wouldn't have a performance penalty).
I would say that you shouldn't store the items in a single list; your example usage shows that you know the type ahead of time (you are assigning to a double) so you are aware at that point in time of the specific typed list.
It's not worth losing type-safety over.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Postscript: Drawing a Gradient I'm learning Postscript I'm trying to create a method for that would draw a vertical gradient.
Here is my code:
%!PS-Adobe-3.0
%%%%%%%%%%%%%%%%%%%%%%%
% draw a RECTANGLE
/Rect {
/h exch def % height
/w exch def % width
w 0 rlineto
0 h rlineto
-1.0 w mul 0 rlineto
0 -1.0 h mul rlineto
} def
%%%%%%%%%%%%%%%%%%%%%%%
% draw a Gradient
/VGrad {
/h exch def % height
/w exch def % width
/c2 exch def %gray-end
/c1 exch def %gray-start
/index 0.0 def %loop-index
0 1 h { %loop over height
gsave
c2 c1 sub index h div mul c1 add setgray
w h index sub Rect
stroke
/index index 1.0 add def % index++
grestore
} for
} def
%%%%%%%%%%%%%%%%%%%%%%%
%test script
200 600 moveto
.1 .9 100 10 VGrad
showpage
But GS raises an error:
GPL Ghostscript 8.70 (2009-07-31)
Copyright (C) 2009 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Error: /undefinedresult in --div--
Operand stack:
0 1 2 3 4 5 0.8 5.0 0.0
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1862 1 3 %oparray_pop 1861 1 3 %oparray_pop 1845 1 3 %oparray_pop 1739 1 3 %oparray_pop --nostringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- 6 1 10 --nostringval-- %for_pos_int_continue --nostringval--
Dictionary stack:
--dict:1150/1684(ro)(G)-- --dict:0/20(G)-- --dict:75/200(L)--
Current allocation mode is local
Current file position is 588
GPL Ghostscript GPL Ghostscript 8.708.70: : Unrecoverable error, exit code 1
Unrecoverable error, exit code 1
where am I wrong ?
A: Your program will execute faster by using clever stack manipulation and CTM effects.
This is not a smooth gradient like yours, but executes much faster, and the functions are computed as one-line statements (which I just like better, can't explain why).
Also it's nice to post with usage and maybe a sample page (easy to trim when you don't need it, but when you do need it...??!!) Anyway, here's your program rewritten my way, FWIW.
As I said, the output it not as pretty in its current form. But you can modify the gradient by changing the gray-transfer function using currenttransfer and settransfer and/or change the calculation of the boxes to a logorithmic scaling, change the range and velocity of the grays. These things should be easier to see in "tighter" code. The stack comments help you to "check your understanding" at the end of each line.
Edit: I couldn't stop playing with it! I've factored out the loop and teased out some more parameters.
Edit: One more expansion. And how about a pretty picture?
%!
/box { % x y w h
4 2 roll moveto % w h
1 index 0 rlineto % w h
0 exch rlineto % w
neg 0 rlineto %
closepath
} def
/poly { % n
0.5 0 moveto
{ ? rotate 0.5 0 lineto } % n proc
dup 0 360 4 index div put % n {360/n...}
repeat
closepath
} def
% num-slices shapeproc matrix grayproc agrad -
% repeatedly (fill shape, concat matrix, transform currentgray)
/agrad {
3 dict begin /gray exch def /mat exch def /shape exch def
({ //shape exec //mat concat currentgray //gray exec setgray })
token pop exch pop end bind repeat
} def
/shapes [
{ -0.5 -0.5 1 1 box fill } %box shape
{ 0 0 0.5 0 360 arc fill } %circle shape
{ 0 0 0.5 0 180 arc fill } %fan shape
{ 5 poly fill } %pentagon
{ 6 poly fill } %hexagon
] def
/mats [
{1 index 2 exch div 1 exch sub dup matrix scale } %pyramid matrix
{1 index 2 exch div 1 exch sub 1 matrix scale } %horizontal matrix
{1 index 2 exch div 1 exch sub 1 exch matrix scale } %vertical matrix
] def
% mat-no shape-no gray0 grayF n x y w h dograd -
/dograd {
gsave
4 2 roll translate % m sh g0 gF n w h
scale % m sh g0 gF n
3 1 roll % m sh n g0 gF
1 index sub 2 index div % m sh n g0 (gF-g0)/n
[ exch /add cvx ] cvx % m sh n g0 grayproc
3 1 roll setgray % m sh grayproc n
3 -1 roll shapes exch get % m gray n shape
4 -1 roll mats exch get exec % gray n shape mat
4 -1 roll %n shape matrix gray
agrad
grestore
} def
%mat shape g0 gF n x y w h
0 4 .7 .1 20 300 400 600 800 dograd
0 0 0 1 10 100 650 200 200 dograd
1 1 0 1 20 300 650 200 200 dograd
2 2 .5 1 30 500 650 200 200 dograd
0 3 1 0 40 100 400 200 200 dograd
1 4 1 .5 50 300 400 200 200 dograd
2 1 .5 0 60 500 400 200 200 dograd
0 2 .1 .9 10 100 150 200 200 dograd
1 3 .2 .8 20 300 150 200 200 dograd
2 4 .3 .7 30 500 150 200 200 dograd
showpage
A: Ok, I found the problem: It seems that index is a reserved word. Here is a functional version:
/box
{
4 dict begin
/height exch def
/width exch def
/y exch def
/x exch def
x y moveto
width 0 rlineto
0 height rlineto
width -1 mul 0 rlineto
0 height -1 mul rlineto
end
} bind def
/gradient
{
4 dict begin
/height exch def
/width exch def
/y exch def
/x exch def
/i 0 def
height 2 div /i exch def
0 1 height 2 div {
1 i height 2.0 div div sub setgray
newpath
x
y height 2 div i sub add
width
i 2 mul
box
closepath
fill
i 1 sub /i exch def
}for
newpath
0 setgray
0.4 setlinewidth
x y width height box
closepath
stroke
end
} bind def
A: I didn't try to understand your code fully. But the error message tries to tell you that you are dividing by zero (look at the top element of the remaining operand stack: "0").
Just by adding "1" to your h variable (insert 1 add after h) makes your PostScript program run through the Ghostscript interpreter and let it draw something (though that may not look like you envisaged....).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to modify jquery tag-it plugin: limit number of tags and only allow available tags how to modify the tag-it ui plugin https://github.com/aehlke/tag-it (version v2.0) so it only allows selection of x numbers of tags and how to allow only tags that are in the "availableTags-option"?
this question (or the first part of it) is already asked and aswerd in the past but for previous version of the plug-in.
A: You can just provide this parameter to .tagit:
beforeTagAdded: function(event, ui) {
if($.inArray(ui.tagLabel, availableTags)==-1) return false;
}
where availableTags is your autocomplete array.
Regarding @snuggles query below, I believe (my limited familiarity with the json protocols notwithstanding) you could probably do something like this:
//define autocomplete source
var returnedUsers, jsonUrl = "http://[your server]/user_lookup";
$.getJSON(jsonUrl,function(json){
returnedUsers = json; // or whatever handler you need to use
});
// instantiate tagit
$("#ccList").tagit({
availableTags: returnedUsers,
beforeTagAdded: function(event, ui) {
// only allow existing values
if($.inArray(ui.tagLabel, returnedUsers)==-1) return false;
// limit length
if ($(".tagit-choice").length >= 5) return false;
});
A: Update 2013-03-13:
First, re-reading the OP, I'm now not clear on if I'm really answering the question, as they specifically asked how to modify the tag-it plugin in order to accomplish the two tweaks. If the OP really wants to modify the plug-in, that's fine, but as I said before, it seems lame that you would have to--and you don't!
So here's how to accomplish both things without modifying the plugin :)
first, you do have to have some sort of global array to put stuff into, if there's a better way to do that, lmk, but otherwise:
var returnedUsers = [];
Then:
$("#ccList").tagit({
autocomplete: {
source: function( request, response ) {
$.ajax({
url: "http://[your server]/user_lookup",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
returnedUsers = data;
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
},
error: function(xhr, status, error) {
returnedUsers = [];
}
});
}
},
beforeTagAdded: function(event, ui) {
if ($.inArray(ui.tagLabel, returnedUsers)==-1)
return false;
if ($(".tagit-choice").length >= 5)
return false;
}
});
So basically you have to point the autocomplete.source at a function in which you handle all the ajax stuff and build your own list. Note that doing this allows you some flexbility in what you return from your cgi back end (ie, it doesn't have to be an array of strings, it could be an array of hashes which you parse and build into a custom list). Also note that this would not be needed if only I could find a way to access the list of returned values from the more basic autocomplete function in the 'beforeTagAdded' event--something Jack implied was possible but did not elaborate on.
Once you've build the array of things to display you return it using the response() function. At the same time now you have a copy of that list in 'returnedUsers', which you can use in the 'beforeTagAdded' function. Also, it's simple to limit the number of tags you allow in the box by just counting how many are already in there and returning false if it's >= to that number. Not sure if that's the best way to get the count, but it definitely works.
I know this is old, and I'm sure any expert would find a million ways to do it better than me, but I haven't found anyone that's laid out how to work around this issue better than what I've outlined without actually changing the plugin, which I do not prefer to do. HTH!
A: jQuery UI Tag-it!
@version v2.0 (06/2011).
Go to file tag-it.js
And find the function createTag
And following code in the beginning.
if (that.options.maxTags) {
if ($('.tagit li').length > that.options.maxTags) {
alert('Maxmium ' + that.options.maxTags + ' tags are allowed')
return false;
}
}
And in the page
$("#myTags").tagit({
maxTags: 8
});
This will limit the tags to 8 tags. You can change the number to any to limit that much number of tags.
A: first add custom options (maxTags and onlyAvailableTags) to the plugin file like so...
options: {
itemName : 'item',
fieldName : 'tags',
availableTags : [],
tagSource : null,
removeConfirmation: false,
caseSensitive : true,
maxTags : 9999,//maximum tags allowed default almost unlimited
onlyAvailableTags : false,//boolean, allows tags that are in availableTags or not
allowSpaces: false,
animate: true,
singleField: false,
singleFieldDelimiter: ',',
singleFieldNode: null,
tabIndex: null,
onTagAdded : null,
onTagRemoved: null,
onTagClicked: null
}
next replace the _isNew function with this one...
_isNew: function(value) {
var that = this;
var isNew = true;
var count = 0;
this.tagList.children('.tagit-choice').each(function(i) {
count++;
if (that._formatStr(value) == that._formatStr(that.tagLabel(this))|| count >= that.options.maxTags) {
isNew = false;
return false;
}
if (that.options.onlyAvailableTags && $.inArray(that._formatStr(value),that.options.availableTags)==-1) {
isNew = false;
return false;
}
});
return isNew;
}
Now you can use the options when you initialize tagit. only the sampleTags are allowed with a maximum of 3 tags
$(function(){
var sampleTags = ['php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python'];
//-------------------------------
// Tag events
//-------------------------------
var eventTags = $('#s_tags');
eventTags.tagit({
availableTags: sampleTags,
caseSensitive: false,
onlyAvailableTags: true,
maxTags:3,
})
});
A: Find tagLimit in tag-it.js and set the number which you want to limit with.
I limited with 5. Default value is null.
removeConfirmation: false, // Require confirmation to remove tags.
tagLimit : 5, -
A: I improved @kaspers answer with new updated library.
make some changes in library
1. add new option in options
onlyAvailableTags : false,
*
*put check in createTag method of
if (this.options.onlyAvailableTags &&$.inArray(this._formatStr(value),this.options.autocomplete.source)==-1)
{
return false;
}
then call tagit like this. Now tag it library supports tagsLimit. So we dont need to customize it.
$(function(){
var sampleTags = ['php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python'];
//-------------------------------
// Tag events
//-------------------------------
var eventTags = $('#s_tags');
eventTags.tagit({
availableTags: sampleTags,
caseSensitive: false,
onlyAvailableTags: true,
tagLimit: 3,
})
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Should one use distances (dissimilarities) or similarities in R for clustering? I'm doing a cluster problem, and the proxy package in R provides both dist and simil functions.
For my purpose I need a distance matrix, so I initially used dist, and here's the code:
distanceMatrix <- dist(dfm[,-1], method='Pearson')
clusters <- hclust(distanceMatrix)
clusters$labels <- dfm[,1]#colnames(dfm)[-1]
plot(clusters, labels=clusters$labels)
But after I ploted the image I found that the cluster result is not the way I expecte it to be, since I know what it should look like.
So I tried simil instead, and the code is like:
distanceMatrix <- simil(dfm[,-1], method='Pearson')
clusters <- hclust(pr_simil2dist(distanceMatrix))
clusters$labels <- dfm[,1]#colnames(dfm)[-1]
plot(clusters, labels=clusters$labels)
This code computes a similarity matrix using simil, then convert it to distance matrix using pr_simil2dist, then I plot it and get the result I expected !
I'm confused about the relationship between dist and simil. According to the relationship described in the documentation, shouldn't the two code snippet has the same result?
Where am I wrong ?
Edit:
You can try my code with dfm of the following value, sorry for the bad indentation.
Blog china kids music yahoo want wrong
Gawker 0 1 0 0 7 0
Read/WriteWeb 2 0 1 3 1 1
WWdN: In Exile 0 2 4 0 0 0
ProBlogger Blog Tips 0 0 0 0 2 0
Seth's Blog 0 0 1 0 3 1
The Huffington Post | Raw Feed 0 6 0 0 14 5
Edit:
Actually the sample data is taken from a very big data frame using tail, and I get completely different matrix using dist and simil+pr_simil2dist. The full data can found here.
In case I made other silly mistakes, here's the full code of my function:
The code I use to read in data:
dfm<- read.table(filename, header=T, sep='\t', quote='')
Code for clustering:
hcluster <- function(dfm, distance='Pearson'){
dfm <- tail(dfm)[,c(1:7)] # I use this to give the sample data.
distanceMatrix <- simil(dfm[,-1], method=pearson)
clusters <- hclust(pr_simil2dist(distanceMatrix))
clusters$labels <- dfm[,1]#colnames(dfm)[-1]
plot(clusters, labels=clusters$labels)
}
Matrix using dist:
94 95 96 97 98
95 -0.2531580
96 -0.2556859 -0.4629100
97 0.9897783 -0.1581139 -0.2927700
98 0.8742800 -0.2760788 -0.1022397 0.9079594
99 0.9114339 -0.5020405 -0.2810414 0.8713293 0.8096980
Matrix using simil+pr_simil2dist:
94 95 96 97 98
95 1.25315802
96 1.25568595 1.46291005
97 0.01022173 1.15811388 1.29277002
98 0.12572004 1.27607882 1.10223973 0.09204062
99 0.08856608 1.50204055 1.28104139 0.12867065 0.19030202
You can see that corresponding elements in the two matrices add up to 1, which I think is not right. So there must be something I'm doing wrong.
Edit:
After I specify names in the read.table function to read in the data frame, the dist way and simil+pr_simil2dist way give the same correct result. So technically problem solved, but I don't know why my original way of handling data frame have anything to do with dist and simil.
Any one has a clue on that ?
A: I'm not sure what you mean by not as per expected. If I compute the distance/similarity matrix via proxy::dist() or via simil() and convert to a dissimilarity I get the same matrix:
> dist(dfm, method='Pearson')
Gawker Read/WriteWeb WWdN: In Exile ProBlogger Blog Tips Seth's Blog
Read/WriteWeb 0.2662006
WWdN: In Exile 0.2822594 0.2662006
ProBlogger Blog Tips 0.2928932 0.5917517 0.6984887
Seth's Blog 0.2662006 0.2928932 0.4072510 0.2928932
The Huffington Post | Raw Feed 0.1835034 0.2312939 0.2662006 0.2928932 0.2312939
> pr_simil2dist(simil(dfm, method = "pearson"))
Gawker Read/WriteWeb WWdN: In Exile ProBlogger Blog Tips Seth's Blog
Read/WriteWeb 0.2662006
WWdN: In Exile 0.2822594 0.2662006
ProBlogger Blog Tips 0.2928932 0.5917517 0.6984887
Seth's Blog 0.2662006 0.2928932 0.4072510 0.2928932
The Huffington Post | Raw Feed 0.1835034 0.2312939 0.2662006 0.2928932 0.2312939
and
d1 <- dist(dfm, method='Pearson')
d2 <- pr_simil2dist(simil(dfm, method = "pearson"))
h1 <- hclust(d1)
h2 <- hclust(d2)
layout(matrix(1:2, ncol = 2))
plot(h1)
plot(h2)
layout(1)
all.equal(h1, h2)
The last line yields:
> all.equal(h1, h2)
[1] "Component 6: target, current do not match when deparsed"
which is telling us that h1 and h2 are exactly the same except for the matched function call (obviously as we used d1 and d2 in the respective calls).
The figure produced is:
If you set your object up correctly, then you won't need to fiddle with the labels. Look at the row.names argument to read.table() to see how to specify a column be used as the row labels when the data are read in.
All of this was done using:
dfm <- structure(list(china = c(0L, 2L, 0L, 0L, 0L, 0L), kids = c(1L,
0L, 2L, 0L, 0L, 6L), music = c(0L, 1L, 4L, 0L, 1L, 0L), yahoo = c(0L,
3L, 0L, 0L, 0L, 0L), want = c(7L, 1L, 0L, 2L, 3L, 14L), wrong = c(0L,
1L, 0L, 0L, 1L, 5L)), .Names = c("china", "kids", "music", "yahoo",
"want", "wrong"), class = "data.frame", row.names = c("Gawker",
"Read/WriteWeb", "WWdN: In Exile", "ProBlogger Blog Tips", "Seth's Blog",
"The Huffington Post | Raw Feed"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wordpress feeds have rubbish social images in content - how do I remove? Either PHP string or Wordpress If you look at the content feed on http://minnesotatransplant.wordpress.com/feed/ for example - you'll see a pile of quite poor share and social images at the bottom of each item's content:encoded.
Does anyone know how to get rid of these or programmatically remove with PHP?
A: For anyone who's interested, I ended up doing...
$whereIsNaughtyString = strpos($contentwords, "<a rel=\"nofollow\"");
$contentTrimmed = substr($contentwords, 0, $whereIsNaughtyString);
Which got rid of all the stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android activity lifecycle state across different activities × 99416 I have four activities A,B,C and D.
I am moving from Activity A---->B--->C--->D
And from activity D i am calling activity B.
By the time i reach to activity D from A-B-C-D
The states of Activity A,B and C is onStop() state and activity D is onResume() state.
There are two scenarios ahead:
1>I press the back button and go to activity C or
2>I invoke an event and go to Activity B.
First scenario is understood wrt activity states.
D-Destroy state and C will be onrestart-onstart-onresume
Second Scenario
Activity D goes to OnStop and for Activity B-->Oncreate-Onstart-OnResume...
and Activity A and C will be on onStop() state...
I wanted to know as the state of the Activity B before the event was onStop(),
but inspite of calling the onRestart() method it has called the onCreate-onStart-onResume.
As, the Activity B was not destroyed than where did the Activity B which was originally on
onStop() state go ........And from this activity B when i move to Activity C ...it calls the onCreate-onStart-onResume for Activity C....for Activity C also the one which was onStop state has not been destroyed ......got confused with the life cycle and activity stack flow....Help me on the same...
A: You are creating new instances of the activity that's why you are seeing the flow onCreate-onStart-onResume. you need to add flag FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY, FLAG_ACTIVITY_REORDER_TO_FRONT to your activity before starting from the stack.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding profile image in cakephp I currently, have 2 database. images & users.
In my user Model I have:
var $belongsTo=array(
'Image'=>array('className'=>'Image')
);
In my image Model I have:
var $hasOne =array(
'Users'=>array('className'=>'User')
);
I want to achieve the following below:
My users database has a field 'image_id' and it is linked to my images database field 'id'.
Example:
images database id = 1
users database image_id = 1
Below is the code for the add function in my image_controller. I want to add a particular image and I want the images 'id' to be save to the users database 'image_id'. How do I achieve this?
function add() {
$this->layout = "mainLayout";
if (!empty($this->data)) {
$this->Image->create();
if ($this->Image->save($this->data)) {
$user_id = $this->User->getUserInfo($this->Auth->user('id'));
$this->data['User']['image_id'] = $user_id;
$this->Session->setFlash('The image has been saved', true);
$this->redirect(array('controller' => 'Users', 'action' => 'profile'));
} else {
$this->Session->setFlash('The image could not be saved. Please, try again.', true);
}
}
$current_user_pic =$this->User->getUserInfo($this->Auth->user('id'));
$this->set(compact('current_user_pic'));
}
A: make it User hasOne Image (Image hasOne User is just semantically weird). So when you save an image record, just set the 'user_id' to $this->Auth->user('id')) before saving.
Also, don't use var $uses = array('User','Image'); When you already set the relationship, you can access Image model through User model: $this->User->Image->save($this->data)
Edit: Ok, so remove the image_id field in users table, add user_id field to images table. If you use bake command to generate code, you might want to save your code in the models, controllers, and views for users and images, then re-bake these 2. Declare relationships: User hasOne Image and Image belongsTo User (I assume you know how to do that).
When you save the image, set $this->data['Image']['user_id'] = $this->Auth->user('id') before $this->User->Image->save($this->data)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why Jquery each function stopped working? This code of mine was working well, but now it has stopped working!! What might be wrong with it?
Am looping through table rows, using the JQuery .each function,
html:
<form method="POST" action="/post_updates/" onSubmit="return postUpdates()" >
<table id="mytable" class="table">
<thead>
<tr>
<th>col 1</th>
<th>col2 </th>
</tr>
</thead>
<tbody>
!-- rows are created dynamically --
{% for object in object_list %}
<tr>
<td id="row">{{object.id}}</td>
!-- other td's --
</tr>
{% endfor %}
</tbody>
</table>
Javascript:
<script type="text/javascript" >
function postUpdates(){
$("#mytable tr:gt(0)").each( function () {
// this code NEVER get executed
var rowid = $(this).find("#row").html();
// .. does alot of stuff with rowid!!
});
}
am sure this was working, but it just stopped. Tested it in both Chrome and Firefox!
Gath.
A: you missed some parenthesis:
$("#mytable tr:gt(0)").each( function() {
// this code NEVER get executed
var rowid = $(this).find("row").html();
});
also your selector is missing something... I am assuming by your issue that the problem is before that, but .find("row") would not generally find something.
A: Missing parens:
$("#mytable tr:gt(0)").each( function() {
^^
Update: You are using the same id with multiple elements, which is not allowed. Change id="row" to class="row" and use the selector .find(".row") instead.
A: Below is how your markup should look after the scripting engine renders it. Notice the change in the onSubmit function and also the declaration of the function before it is invoked. As you are using jquery you should probably consider using their event binding api. In this case you should use submit event
<script type="text/javascript">
function postUpdates(){
$("#mytable tr:gt(0)").each( function () {
// this code NEVER get executed
alert( $(this).find("#row").html());
// .. does alot of stuff with rowid!!
});
}
</script>
<form method="POST" action="" onSubmit="postUpdates()" >
<table id="mytable" class="table">
<thead>
<tr>
<th>col 1</th>
<th>col2 </th>
</tr>
</thead>
<tbody>
<tr>
<td id="row">test</td>
<td>test2</td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>
Hope this helps.
Demo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Log4j dailyrollingfileappender file issues We are encountering a peculiar problem.
Scenario: We have 3 servers which with multiple instances of a component all writing transactional log to a single log file.We use log4j and the servers run in Java 1.3. setAppend() is passed true and implementation is DailyRollingFileAppender
Problem: At midnight, we are expecting the current log file to roll over with a new file name and start writing to a new file. This is working well in our test setup (single server writing logs). In production, at midnight, new file is getting created where new logs are getting written but rolled over file is getting deleted
Any help will be highly appreciated as its been couple of days and we are not able to get any leads for the problem.
A: You should not log to the same file from many processes. Log4j is thread-safe all right, but it's not process-safe, if I may say so; it does not work as a shared library among different java processes. Log4j embedded in one java application has no knowledge of any other one.
With rollover it causes the problem you've just discovered: all processes run their own rollover code, blindly overwriting the previous contents (because none of them expects any).
A possible solution here: Log4j Logging to a Shared Log File
A: We ran into the same problem. The underlying problem is that there is no way to coordinate access to log file across multiple processes (in this case running on multiple servers.) This means all sorts of bad things happen: logs gets overwritten, files fail to roll etc...
My suggestion to you is to have each server write to a separate file, and then merge them in a post processing job.
A: Say you have configured DailyRollingFileAppender with daily rotation (It can be configured for rotation every hour, minute etc). Say, it is 31-Dec-2014 today and log file name is sample.log. Log rotation will happen in the following way:
*
*First log message that is received after midnight (say at 1am on 1-Jan-2015) will trigger log file rotation.
*Log file rotation will first delete any existing file with previous day suffix. (i.e. It will delete any file with name sample-2014-12-31.log. Ideally no such file should exist.).
*It will then rename current file with suffix of previous day. i.e. it renames sample.log to sample-2014-12-31.log.
*It will create new log file without suffix. i.e. new sample.log
*It will start writing into the new file sample.log.
If two instances of Log Manager points to same log file then each instance will independently repeats above steps on the same file. This can happen in any of the following scenarios:
*
*If two or more WAR file deployed in same container points to same log file.
*If two or more processes points to same log file.
*etc
Such scenario leads to the issue mentioned in the question.
*
*On a windows machine, once first process has rotated the log file and acquired handle on the new file, second log appender will fail to write logs.
*On a linux machine, Second process will delete the archive file created by first process and rename the new file (currently being used by first process) to previous day file. Thus first process will start writing logs in previous day file, second process will write logs in new file. After midnight, log file used by first process will get deleted. So, logs from first process will keep getting lost.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Retrieve has_many association as hash by property of child Is it possible to retrieve the child elements in a has_many association into a hash based on one of their properties?
For example, imagine a menu that has a single dish for each day:
class Menu
has_many :dishes
end
and
class Dish
belongs_to :menu
end
Dish has a key, day, which is one of either monday, tuesday etc. Is there some way to set up the has_many association such that Menu.dishes returns a hash similar to {:monday => 'spaghetti', :tuesday => 'tofu', ... }?
A: Sure. Something like this should suffice (assuming e.g. "spaghetti" is stored in a column called food).
class Dish
belongs_to :menu
scope :by_day { select [ :day, :food ] }
def self.by_day_hash
by_day.all.reduce({}) {|hsh,dish| hsh[dish.day] = dish.food; hsh }
end
end
class Menu
has_many :dishes
def dishes_by_day
dishes.by_day_hash
end
end
# Usage
m = Menu.where( ... )
m.dishes_by_day #=> { "monday" => "Spaghetti", "tuesday" => "Tofu" }
So what's happening here is that in Dish the by_day scope returns only two columns, day and food. It still, however, returns Dish objects rather than a Hash (because that's what scopes do), so we define a class method, by_day_hash which takes that result and turns it into a Hash.
Then in Menu we define dishes_by_day which just calls the method we made above on the association. You could just call this dishes but I think it's better to keep that name for the original association since you might want to use it for other things later on.
Incidentally (optional stuff below, skip for now if your eyes have glazed over), I might define by_day_hash like this instead:
class Dish
belongs_to :menu
scope :by_day { select [ :day, :hash ] }
def to_s
food
end
def by_day_hash
hsh = HashWithIndifferentAccess.new
by_day.reduce(hsh) {|hsh, dish| hsh[dish.day] = dish }
end
end
# Usage
m = Menu.where( ... )
m.dishes_by_day #=> { "monday" => #<Dish food: "Spaghetti", ...>, "tuesday" => #<Dish food: "Tofu", ...>, ... }
...This way you still get the full Dish object when you call e.g. by_day_hash["monday"] but the to_s method means you can just drop it into a view like <%= @menu.dishes_by_day["monday"] %> and get "Spaghetti" instead of #<Dish day: "monday", food: "Spaghetti">.
Finally, you might also notice I used HashWithIndifferentAccess.new instead of {} (Hash). HashWithIndifferentAccess is a class provided (and used everywhere) by Rails that is identical to Hash but lets you do either e.g. some_hash["monday"] or some_hash[:monday] and get the same result. Totally optional but very handy.
A: Here's a nice way to do it in modern ActiveRecords and Rubys:
# In class Menu
def foods_by_day
Hash[ dishes.pluck(:day, :food) ]
end
dishes.pluck(:day, :food) returns an array like [ ['monday', 'spaghetti'], ['tuesday', 'tofu], ... ]; Hash[] converts that array-of-arrays into a hash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Could not connect to SVN Repository. Could not resolve hostname I try connect to SVN Repository and get SvnRepositoryIOException: Could not resolve hostname: The requested name is valid, but no data of the requested type was found.
The same error when I try commit or update project or using TortoiseSVN.
We use kerio, but I think it's something else, because another computer with similar settings can connect successful. I tried everything. I am thinking reset my operating system already. Do you have any ideas?
A: If both SVN clients give the same result then it suggests the problem is somewhere else.
Some things to try:
*
*Can you ping the host? If so, what happens if you connect with a Web browser - can you browse any HTTP version of the Subversion repository that might be available?
*If you can't resolve the host, does the other host have a VPN, or some fancy settings in the hosts file to tell the PC about the repository?
*Are your authentication settings correct?
A: Solution:
It was DNS problem. My computer couldn't find DNS of repository server. I add another DNS in LAN connection settings and it works! Thank you for your help!
A: Check to see if you are operating from behind a proxy. If you are you can set these details in the Tortoise settings panel.
Have you tried connecting to another SVN server to test your tortoise?
A: I have had problems with this if IPv6 is enabled and used over a wireless router that does not support the IPv6 protocol well. Try disabling in your network properties temporarily to see if that fixes it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reading rpart Input Parameters from a Text Variable I'm using rpart to make a decision tree. For example:
fit <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis)
How do I read in the formula part from a text file and get it in a format that rpart likes? I've tried:
predictor_variables <- c("Age", "Number", "Start")
rpart_formula <- Kyphosis ~ parse(text=paste(predictor_variables, collapse="+"))
fit <- rpart(rpart_formula, data=kyphosis)
but I get an error:
invalid type (expression) for variable 'parse(text = paste(predictor_variables, collapse = "+"))'
How can I format rpart_formula so that rpart sees it correctly?
A: Use as.formula:
rpart_formula <- as.formula(
paste("Kyphosis ~ ",
paste(predictor_variables, collapse = " + "),
sep = ""
)
)
A: Try simply passing the formula as a character string:
rpart_formula <-paste("Kyphosis ~ ",paste(predictor_variables, collapse="+"))
that should be coerced to a formula by rpart.
Edit
As noted in the comments below, not all functions will do the coercion for you, so you should not rely on this behavior, but in this case rpart most certainly does.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Not able to Hide controls using setHidden property from another class? I am invoking PickerView from Employee View.
Following is code in my didSelect method of tableView in Employee class.
pickView = [[PickerView alloc] initWithNibName:@"PickerView" bundle:nil];
[pickView.pickerView setHidden:YES];
[pickView.datePicker setHidden:YES];
switch (indexPath.row)
{
case 0:
pickView.pickerArray = [[NSMutableArray alloc] initWithObjects:@"ML",@"M",@"M SL",@"ME",@"ME SL",@"S",@"SB",@"SH",@"ST",@"S SL",@"SH SL",@"ST SL",@"ND",@"CAE",@"EDW",@"NSW", nil];
pickView.title = @"Select Taxcode";
[pickView.pickerView setHidden:NO];
break;
case 1:
[pickView.datePicker setHidden:NO];
pickView.title = @"Pay Period";
break;
default:
break;
}
[self.navigationController pushViewController:pickView animated:YES];
I am not able to see the controls in PickerView. I have kept all controls Hidden from IB. Now when I click 1st cell in Employee's table View then only 1 control should be visible.
What could be the problem?
A: Try this code in Switch case. Le me know if you still have some problems with this.
switch (indexPath.row)
{
case 0:
{
pickView.pickerArray = [[NSMutableArray alloc] initWithObjects:@"ML",@"M",@"M SL",@"ME",@"ME SL",@"S",@"SB",@"SH",@"ST",@"S SL",@"SH SL",@"ST SL",@"ND",@"CAE",@"EDW",@"NSW", nil];
pickView.title = @"Select Taxcode";
[pickView.pickerView setHidden:NO];
break;
}
case 1:
{
[pickView.datePicker setHidden:NO];
pickView.title = @"Pay Period";
break;
}
default:
break;
}
A: Not sure about the exact issue but I think you can try putting your switch case after you push the view controller.
Or use some booleans to pass to the view controller and then in the viewDidAppear of PickerView process your hide / show for the controls
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: get activityInfo metaData in onCreate method I need to retrieve a value from the AndroidManifest.xml file, stored as a meta data:
<meta-data android:value="3" android:name="myInterestingValue" />
In the onCreate method, I call the following method:
private Object getMetaData(String name) {
try {
ActivityInfo ai = getPackageManager().getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
Bundle metaData = ai.metaData;
if(metaData == null) {
debug("metaData is null. Unable to get meta data for " + name);
}
else {
Object value = (Object)metaData.get(name);
return value;
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
But the metaData is always null. Is it impossible to access the metaData in the onCreate method? i.e. The activity has not been fully initialized yet.
A: You will need to use the flags GET_ACTIVITIES and GET_META_DATA.
ActivityInfo ai = getPackageManager()
.getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
A: If you are interested, android-metadata is a framework that makes it easier to get metadata from the Android manifest. The way you would get the meta-data above using android-metadata is:
int val = ManifestMetadata.get (context).getValue ("myInterestingValue", Integer.class);
Full disclosure: I'm the creator of android-metadata.
A: I've tried jasonj's answer but it doesn't work. To retrieve meta-data from manifest file, I must get the following code
ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
OR the Kotlin version:
val ai = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
val bundel = ai?.metaData
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Div background change to 12 different colours I have this code to change the background colour of a div tag upon hovering over another image. However, it only flips one div tag between two background colours. I need to have 12 images change one div tag to 12 different colours only (one colour per image as opposed to this which switches to one colour on the first hover and another colour on the second). I am really new to this so any help would be greatly appreciated.
Code:
function changeBackgroundColor(objDivID)
{
var backColor = new String();
backColor = document.getElementById(objDivID).style.backgroundColor;
// IE works with hex code of color e.g.: #eeeeee
// Firefox works with rgb color code e.g.: rgb(238, 238, 238)
// Thats why both types are used in If-condition below
if(backColor.toLowerCase()=='#eeeeee' || backColor.toLowerCase()=='rgb(238, 238, 238)')
{
document.getElementById(objDivID).style.backgroundColor = '#c0c0c0';
}
else
{
document.getElementById(objDivID).style.backgroundColor = '#eeeeee';
}
}
A: there is spaces misspelled in the if statement.
the rgb() spaces separators syntax must be the same as browser's syntax
replace if statement with the following:
if(backColor.toLowerCase()=='#eeeeee' || backColor.toLowerCase()=='rgb(238, 238, 238)')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Querying for @Embedded map in objectify for GAE Please consider following sample
@Entity
public class Abc {
@Id
private Long id;
@Unindexed
private String name;
@Embedded
private Map<String, Xyz> objs;
}
public class Xyz {
private String objName;
private String objStatus;
}
Now I want the object of Abc such that objs.get("someKey").getObjName().equals("someName") is true.
How do I make this query in Objectify? Also, if I store 'objs' as list instead of map, can I query for an object of Abc such that one of the list values have objName as 'someName'? Need help in this. Thanks
A: You should be able to query like this:
Objectify ofy = factory.begin
ofy.query(Abc.class).filter("objs.someKey.objName=", "someName")
The map keys are simple folded into the map of properties of the entity, using a dot as the separator and the name of the map field ("objs") as a prefix to avoid collisions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: JPA, transient annotation not overwriting OneToOne? I have a superclass Product and a subclass Reduction. Now I want the subclass to override a property of the superclass so it isn't persisted in the database. I excpeted it to work like this but apparently hibernate still tries to store the ProductType property of the Reduction in the database. Is there another way to fix this ?
@Entity
@Table(name="PRODUCT_INSTANCE")
public class Product {
private Integer id;
protected ProductType productType;
public Product(){
}
public Product(ProductType productType) {
this.productType = productType;
}
@OneToOne
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType type) {
this.productType = type;
}
@Transient
public ProductCategory getCategory() {
return productType.getCategory();
}
}
And the subclass:
@Entity
@Table(name="REDUCTION")
public class Reduction extends Product {
private ProductType type;
private Integer id;
public Reduction(Double percentage, Double totalPrice) {
ProductCategory reductionCat = new ProductCategory("_REDUCTION_", new Color("", 130, 90, 80));
type = new ProductType();
type.setBuyPrice(0.0);
type.setBtw(BTW.PER_0);
type.setCategory(reductionCat);
}
@Override
@Transient
public ProductType getProductType() {
return type;
}
}
A: You are looking for
@Entity
@Table(name="REDUCTION")
@AttributeOverride(name = "productType", column = @Column(name = "productType", nullable = true, insertable = false, updatable = false))
public class Reduction extends Product {
@Override
public ProductType getProductType() {
return type;
}
}
A: I solved it using a workaround, in Reduction I put
@Transient
public ProductType getProductHack(){
return type;
}
And in class Product:
@OneToOne
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType type) {
this.productType = type;
}
@Transient
public ProductType getProductHack() {
return getProductType();
}
public void setProductHack(ProductType type) {
setProductType(type);
}
It's ugly but so far this is the only option that works. Starting to wonder if the original question is a bug in hibernate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to style widget in two columns? Can someone guide me on how can I style "archive widget"
to show two columns (as in image below)?
I am new to wordpress and really don't know how to achieve this.
A: i designed my own widget something like
in my sidebar.php file by spliting categories data into two columns and then somewhere in page its stlying depending upon this data.
<?php
$catArray = explode("</li>",wp_list_categories('title_li=&echo=0&depth=1'));
$catCount = count($catArray) - 1;
$catColumns = round($catCount / 2);
for ($i=0;$i<$catCount;$i++) {
if ($i<$catColumns){
$catLeft = $catLeft.''.$catArray[$i].'</li>';
}
elseif ($i>=$catColumns){
$catRight = $catRight.''.$catArray[$i].'</li>';
}
};
?>
A: I've only been using wordpress for a few months, but it seems that there's two parts to your problem -
First I would structure your two columns in a 2-column table. Secondly, as it's possible to replace wordpress functions, I would find the function that returns the archive links (probably returning them in a list of some sort). Try modifying this function to return the archived links in the above table structure. It would probably require abit of planning to figure what months you want displayed in each columns or row, but it shouldn't be too hard). This should return straight to your .php file and it should (in theory work) :)
Again, I've only started using wordpress a few months ago, but this is what I would attempt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Inserting iframe into mysql db I am using codeigniter and at the moment I have a bit of the problem. When I insert iframe (from the youtube) into db in the view file I get row code like this:
<iframe width="420" height="315" src="http://www.youtube.com/embed/aWvcNkRJhHw" frameborder="0" allowfullscreen></iframe>
How to insert iframe into db and display it properly?
EDITED PART:
Form for inserting:
<h3>Create News</h3>
<?php echo form_open('news/create_news') ?>
<label for="title">Title</label><input type="text" name="title" class="inputBox" id="title"><br>
<label for="body">Text</label><textarea name="body" class="inputBox" id="body" rows="5"></textarea>
<label for="datepicker">Date</label><input type="text" name="date" class="inputBox" id="datepicker">
<input type="submit" name="submit" value="Create" class="submit" />
<input type="reset" class="button standard" value="Clear" />
<?php echo form_close() ?>
Function for inserting:
function create_news()
{
$data = array(
'title' => $_POST['title'],
'body' => $_POST['body'],
'date' => $_POST['date']
);
$this->db->insert('news', $data);
}
I tried to insert iframe from youtube (embed video) but it does not work very well. When I load view file I just get text instead of video ().
Controller function:
function news() {
$this->load->helper('text');
if ($this->session->userdata('is_logged_in') == true) {
$q = $this->news_model->get_all();
if ($q == false) {
$data['np'] = 'There is no news at the moment.';
} else {
$data['news'] = $q;
}
$this->pagg();
$data['main_content'] = 'admin_news';
$data['title'] = 'Admin News';
$this->load->view('admin/template', $data);
} else {
$this->index();
}
}
View file:
<div id="news">
<?php if (isset($np)) { echo '<p>' . $np . '</p>'; } ?>
<?php if (isset($news)) : ?>
<?php foreach ($news as $row) : ?>
<div class="borderBott col_12">
<h3><a href="<?php echo base_url() ?>admin/news_update/<?php echo $row['title'] . "/" . $row['id_news'] ?>" ><?php echo $row['title'] ?></a></h3>
<p class="<?php echo alternator('par', 'nepar') ?>"><?php echo word_limiter($row['body'], 50); ?></p>
<p>Date written: <?php echo $row['date'] ?></p>
<a href="#" class="delete" id="<?php echo $row['id_news'] ?>">Delete News</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
A: As NullUserException suggested, it's not a good idea to store the whole iframe tag in your database.
First and foremost: it's ugly. Your storing layout dependent data in your database. NEVER do this. What if you decide you want a different default width and height? You would need to edit all existing records in your database.
Secondly, if YouTube changes their embedded code, all your data would be rendered useless.
IMO the correct solution would be to extract the video id from the iframe and store this in your database.
However, if what I'm assuming is correct and you have a news post with an embedded video in it, you need to take a look at the BBCode mechanism. Your HTML is stored as plain text and hence not rendered correctly when simply outputting the value from your database. By making use of a mechanism such as BBCode, you define custom tags (generally enclosed by straight brackets '[]'), to be stored in your database.
Upon showing the data again all your tags are converted back to the correct HTML and you'll get your embedded video!
There are a few helpers for CodeIgniter: BBCode Helper or Another BBCode Helper. (Note: these are the actual names of the helpers, I'm not trying to be funny :) ).
In my CI applications I always made use of Smarty templating engine, which also provided BBCode helpers, so I never used any of the above.
HTH.
A: <iframe width="560" height="315" src="https://www.youtube.com/embed/IwB4idmx7oE" frameborder="0" allowfullscreen></iframe>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does Filename collision exist in TFS I have a scenario where I have one master branch and one dev branch that is taken from the master branch. The master branch contains some old versions of some dll:s which I have updated in my dev branch. Now when I try to merge my changes back from my dev branch to the master branch I get a "Filname Collision" conflict. Of course the file name will collide, I have updated the file and want to use my newer version. But for some reason I don't have take local as a resolution to the problem. All I can do i either take server, rename server or rename local. Why is that?
A: The issue is that you replaced the DLL instead of "changing" it, so the merge recognises that it is a completely separate entry in the filesystem and complains.
It's explained more fully here and here, including a resolution:
We cannot resolve this through the GUI so we will drop to the command
line and resolve the conflict appropriately. Within resolve we have
the ability to specify a new name for the target file- you can find
all the options here. The option we
will use is AcceptYoursRenameTheirs and in a namespace conflict it
accepts the contents and name of your file (source) and renames their
(target) file to a new name that is specified.
To accomplish this we will also need to use the /newname option. Here
is the command you should execute:
tf resolve a.txt /auto:AcceptYoursRenameTheirs /newname:a-old.txt
After this command succeeds you will get two pending changes: 1) a
merge, branch for the new a.txt into the target folder and 2) a rename
of a.txt to a-old.txt in target. So after checking in these changes
the merge relationship will look like: source/a.txt à target/a.txt
just as you wanted it.
If instead, you would like the opposite to take place, meaning you
need source/a.txt to map to a new name in the target folder then the
command to execute would be:
tf resolve a.txt /auto:AcceptMerge /newname:a-newname.txt
Consequently that would give you a merge relationship of source/a.txt
-à target/a-newname.txt
With the conflict resolved the developer is now free to check in the
changes brought by this merge.
A: Most of the times this happens if you delete a binary file in source control and add it later.
so i think you are using the following workflow:
*
*delete current binary file in source control
*commit
*add new binary file in source control
*merge -> file collision
because of the file delete operation tfs cannot create a relationship between the file and won't provide any solution to fix the problem.
my workflow looks like this (it's working most of the time):
*
*checkout current binary file in source control
*replace binaries in local filesystem
*commit the changed binary files
*merge -> should now detect the new binary version and now you should have your typical experience
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SQL Update with subsubquery I'm having a problem with the following update query in Oracle 11g:
update TABLE_A a set COL1 =
(SELECT b.COL2 FROM
(SELECT ROWNUM AS ROW_NUMBER, b.COL2 from TABLE_B b where COL3 = a.COL4)
WHERE ROW_NUMBER = 2
)
ORA-00904: "A"."COL4": invalid ID .
So, a.COL4 is not known in the subsubquery, but I don't have an idea how to solve this.
/Edit. What am I trying to do?
There are multiple records in TABLE_B for every record in TABLE_A. New requirements from the customer however: TABLE_A will get 2 new columns instead, while TABLE_B will be deleted. So a representation of the first record of the subquery will be written to the first new field and the same for the second one. First record is easy, since Mike C's solution can be used with ROW_NUMBER = 1.
Example rows:
TABLE_A
| col0 | col1 | col2 | col3 | col4 |
------------------------------------
| | |dummy2|dummy3| 1 |
------------------------------------
| | |dummy4|dummy5| 2 |
------------------------------------
TABLE_B
| col1 | col2 | col3 |
----------------------
| d |name1 | 1 |
----------------------
| d |name2 | 1 |
----------------------
| d |name3 | 1 |
----------------------
| d |name4 | 2 |
----------------------
TABLE_A after update
| col0 | col1 | col2 | col3 | col4 |
------------------------------------
| name1| name2|dummy2|dummy3| 1 |
------------------------------------
| name4| |dummy4|dummy5| 2 |
------------------------------------
A: Try
update TABLE_A a set COL1 =
(SELECT b.COL2 FROM
(SELECT ROWNUM AS ROW_NUMBER, b.COL2 from TABLE_B b, TABLE_A a2 where b.COL3 = a2.COL4)
WHERE ROW_NUMBER = 2
)
I'm assuming COL3 comes from table b, also why are you including selecting ROWNUM in the subquery? It can only be 2 from your WHERE clause.
A: UPDATE TABLE_A a SET COL1 =
(SELECT b.COL2 FROM
(SELECT ROWNUM AS ROW_NUMBER, b.COL2 FROM TABLE_B b, TABLE_A innerA WHERE COL3 = innerA.COL4)
WHERE ROW_NUMBER = 2
)
A: Can you eliminate one of the subqueries like this?
update TABLE_A a set COL1 =
(SELECT b.COL2 FROM TABLE_B b where COL3 = a.COL4 AND ROWNUM = 2)
A: I think this could be a possible solution to your problem but depending on the amount of data you're processing it could be really slow because there is no limiting factor for the inner statement.
update
table_a upd
set upd.col1 = (
select
sub.col2
from
(
select
rownum as row_number,
b.col2 as col2,
b.col3 as col3
from
table_a a,
table_b b
where b.col3 = a.col4
) sub
where sub.row_number = 2
and sub.col3 = upd.col4
)
A: I solved this using a temporary table, deleting data from it as table A gets filled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to convert Vector to String array in java How to convert Vector with string to String array in java?
A: here is the simple example
Vector<String> v = new Vector<String>();
String [] s = v.toArray(new String[v.size()]);
A: simplest method would be String [] myArray = myVector.toArray(new String[0]);
A: Try Vector.toArray(new String[0]).
P.S. Is there a reason why you're using Vector in preference to ArrayList?
A: Vector<String> vector = new Vector<String>();
String[] strings = vector.toArray(new String[vector.size()]);
Note that it is more efficient to pass a correctly-sized array new String[vector.size()] into the method, because in this case the method will use that array. Passing in new String[0] results in that array being discarded.
Here's the javadoc excerpt that describes this
Parameters:
a - the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
A: try this example
Vector token
String[] criteria = new String[tokenVector.size()];
tokenVector.toArray(criteria);
A: Vector.ToArray(T[])
A: Try this:
vector.toArray(new String[0]);
Edit: I just tried it out, new String[vector.size()] is slower then new String[0]. So ignore what i said before about vector.size(). String[0] is also shorter to write anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How much time Android Market take to upload saw the upload Application? I have Just Upload the Paid aaplication to the Android Market.
But i am not able to seen it right now on android Market. I think android market will first check it and then will put it on the android market.
But i want to know in how much time they will put my application on android market ?
Give your suggestion and answers.
thanks.
A: As others have mentioned, it can sometimes take a little bit of time. This is mainly due to caching and such, but you should be able to directly hit your application by hitting the fully qualified URL:
https://market.android.com/details?id=com.your.package.name
A: From experience, it might take up to a day for your app (or app updates for that matter) to show up in the market. But it will happen, no worries! Google doesn't do any sort of approval process, they just put up whatever you upload, so I'm not sure what causes the delay.
A: There is no fixed time, it may takes either 1 hour or 1 day or more than this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Storing color array for each user in database I am considering the problem of user-configurable color schemes for a website. The site currently has a collection of flat CSS files, which are selectable by users (selection is stored as a column in the user table of a SQL database). This has led to a maintenance problem, in that updating the files to extend the site's CSS is not feasible.
In particular, there is a collection of css selectors that I would like users to be able to choose color values for. That is, in pseudo-code,
body {
background-color : <% print user_bg_color %>;
}
My question is not concerned with the mechanics of implementing such CSS generation. Rather,
Is there a standard practice or best way for storing such a collection of values?
[EDIT]
If there is no standard way, what are some techniques?
[/EDIT]
Any such technique should be extendable, in the sense that further modification of the site's CSS would allow for the addition of new variables by the site admins. Currently, there are about 30 color schemes consisting of 90 variables each, and about 35,000 users.
A: I don't think there is necessarily a standard way, but what seems obvious and simple to me is a essentially many-to-many table (although your css variable names aren't necessarily stored in the database independently, unless you need to add more data than the variable name) with:
*
*user_id
*css_variable_name_or_id (id if it refers to a sql table of css values)
*value
This way you can easily select all the css for a user, or independently the user_id and css_variable_name for a user.
Put an index on user_id, at least. That should make performance decently fast. (You may don't want one on css_variable_name because of all the duplicates, but it would be worth testing both ways)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OpenGL: Convert on screen coordinate to OpenGL coordinates I draw changing bar in OpenGL ES it has coords (x,y,z).
I would like to add some changes (example: colors in bar) on Action_Down. There is getX(), but this method returns the x coordinate in pixels, but not corresponding coords in OpenGL. Is there some class to convert OpenGL coords to pixels? Or is there any formula for it?
A: I think you're looking for this:
http://www.opengl.org/sdk/docs/man2/xhtml/gluProject.xml
It takes coordinates and maps them to window coordinates, with (0, 0) at the top left.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: why does @Html.ValidationSummary("...") output a div with style=display:none instead of outputting nothing Assuming there are no Validation errors, the resultant html will be injected from a call to @Html.ValidationSummary
<div class="validation-summary-valid" data-valmsg-summary="true"><span>...</span>
<ul><li style="display:none"></li>
</ul></div>
and assuming you have the standard validation-summary-valid in your css (display: none;) the div will not be shown.
Thats fine but wouldnt everything work the same if @Html.ValidationSummary("...") output nothing instead of a 'hidden' div?
A: If the unobtrusive jquery functions are going to populate the validation summary client side, would the scripts not need a place to put the summary? Otherwise, you would have to reload the page each time and that defeats the purpose of client-side validation.
A: I assume it's so that client-side validation can show the div if validation fails on the client later on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Eclipse automatic todo task addition Is there a way in eclipse to automatically add TODO task eg:- //TODO: TO BE TESTED to the top of the function or class so that i can easily keep track of the changes yet to be tested ?
A: Do you want to add the TODO when you generate the methods/classes? Then you could use code templates for that. Like // TODO Auto-generated method stub is added when you generate a method you could put any other comment on top of a method. Window -> Preferences -> Java -> Code Style -> Code Templates
Or do you want to add the TODO to all methods/classes which currently do exist? Thats a bit harder, you could write a plugin which does that for you: Eclipse JDT
If that TODO should always be created when you have modified a class or method you could also write an eclipse plugin which monitors the CompilationUnit in the editor. See recordModifications() here
A: You can edit the code templates and include the TODO comment there. Code templates are located on the preferences dialog
Window > Preferences > Java > Code Style > Code Templates
Unfortunately, this will only help for new methods and classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: MVC3 Value cannot be null. Parameter name: value I am trying to load data of a user edit it and then save it. this has been working and im not quite sure what i changed but now i am getting the following error...
Value cannot be null.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentNullException: Value cannot be null.
Parameter name: value]
System.ComponentModel.DataAnnotations.ValidationContext.set_DisplayName(String value) +51903
System.Web.Mvc.<Validate>d__1.MoveNext() +135
System.Web.Mvc.<Validate>d__5.MoveNext() +318
System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +139
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +66
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1367
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8897857
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
public ActionResult EditDetails()
{
int id = Convert.ToInt32(Session["user"]);
S1_Customers u1_users = storeDB.S1_Customers.Find(id);
return View(u1_users);
}
[HttpPost]
public ActionResult EditDetails(S1_Customers u1_users)
{
var Pcode = "";
if (ModelState.IsValid)
{
I am not even reaching ModelState.IsValid when i click submit
A: It could most probably be that your model has a property that returns a non-nullable value, like int, DateTime, double etc. And if user is updating the entry you are probably not storing that value in a hidden field or somewhere, so when the data is returned that particular property is null. Either place that property into a hidden field or make your property nullable in a model by changing int to int?, etc.
A: Did you change any names? The form names have to map 1-1 with your Action parameters. In this case, the "name" parameter was not passed to the controller action, so it is null.
Wild guess, need more information (method signature of action)
A: You'll receive that error if you have some properties decorated by DisplayAttribute with empty Name
([DisplayAttribute(Name = "", Description = "Any description")])
A: If you use [Display(Name="")] as for properties of your model, This will cause the error you get. To solve this problem, you should avoid using empty display name attribute.
[Display(Name = "")] //this line is the cause of error
public string PromotionCode { get; set; }
A: I was getting this same error message when manually setting a @Html.TextArea, I had used the code from an @Html.TextBox(null, this.Model) in an EditorTemplate and when I did @Html.TextArea(null, this.Model) I got the error above.
Turns out you have to do @Html.TextArea("", this.Model) and it works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: What is the difference between "a{1}" and "a" in regex? Some string was matched with the following `regex
([0-9]\s+){1}
Why did author use {1} in the end of regex?
Can I safely remove it?
A: Yes, there is no difference at all. Possibly it was left over from tweaks made while the regex was being built and tested.
A: {1} limits the regex match to only one integer or space, in your example.
A: It is probably a leftover from debugging/writing the query when the author experimented with {1,2} or so.
Yes, you can remove it.
A: if it is the result of an interpreted code (log/debug coming from script for exemple) the 1 could be the value of a variable.
If it is directly in a script, {1} is the default behavior so it is the same (but take longer to work due to extra interpreation to make by the parser)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Magento wsdl. Looking for a guide Well I am new in Magento Api theme, so I don't know how to create wsdl for api2. Any good guide will be appriciated.
Added:
What I need is:
*
*How to write wsdl.xml in magento?
*How magento will understand that if I type v2_soap? wsdl array then it should take mine version of wsdl.xml for my module?
A: I was looking for the same thing
I found the answer here: http://www.magentocommerce.com/wiki/5_-_modules_and_development/web_services/overriding_an_existing_api_class_with_additional_functionality#wsdl
balexander: Your answer is really hostile!
A: Finally I found ca I was looking for:
click
Update
From comments below :
I'v managed to create v2 service, but it was more copying from catalog's wsdl.xml. But finally I'v managed to do what I asked ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Context Menu on a Group Row in RadGridView I found one old solution Here.
But GridViewExpander is obsolete in 2009. Proof Here.
How can i implement it (Context Menu on a Group Row in RadGridView) in another way?
A: No answers... =(
But i found solution.
The are two ways to solve it:
1) If you need custom style for your GridViewGroupRow - read about Templates Structure
2) If not, then just use somthing like this:
<TelerikNavigation:RadContextMenu.ContextMenu>
<TelerikNavigation:RadContextMenu Opened="RadContextMenuOpened" ItemClick="ContextMenuItemClick" x:Name="contextMenu">
</TelerikNavigation:RadContextMenu>
private void RadContextMenuOpened(object sender, RoutedEventArgs e)
{
var menu = (RadContextMenu)sender;
if (menu == null)
return;
var cell = menu.GetClickedElement<GridViewCell>();
var row = menu.GetClickedElement<GridViewRow>();
var groupRow = menu.GetClickedElement<GridViewGroupRow>();
if (cell != null && row != null)
{
if (!cell.DataColumn.IsFrozen)
{
//Code for current cell
}
}
if (groupRow != null)
{
//Code for groupRow
}
}
private void ContextMenuItemClick(object sender, RadRoutedEventArgs e)
{
if (_currentCell != null)
{
//Code for current cell
}
if (_currentGroupRow != null)
{
var menu = (RadContextMenu)sender;
var clickedItem = e.OriginalSource as RadMenuItem;
if (clickedItem != null)
{
foreach (var gridViewRow in _currentGroupRow.ChildrenOfType<GridViewRow>())
{
foreach (var gridViewCellBase in gridViewRow.Cells)
{
if (gridViewCellBase.Column.UniqueName == "PlanObject")
{
var val = gridViewCellBase.DataContext as YourObjectName;
if (val != null)
{
//.....
}
}
}
}
//....
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PhoneGap openDatabase() method returns null in iPhone/iPad 4.x application I'm trying to compile my phonegap (1.0.0) application under XCode 4.2 (Mac OS X 10.6.8).
Using 5.0 iPhone/iPad Simulator everything seems to work fine, but if I use versions under 5.0 (4.0, 4.1, 4.2, 4.3) then nor iPhone nor iPod simulators returns the database Object invoking openDatabase() method, it simply returns null (I'm using alert to retrieve the value).
Although live iPad 4.3.1 device behaves the same way. I can forget about the simulators, but I need my application to work properly on 4 and 5 iOS devices.
Here is a sample code:
<!DOCTYPE html>
<html>
<head>
<script src="phonegap-1.0.0.js"></script>
<script>
var db = window.openDatabase("TMA", "1.0", "TMA Mobile Database", 1024 * 1024 * 10);
alert(db);
</script>
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
</head>
<body>
</body>
</html>
Any ideas where the bug may dwell? May be some XCode settings or there is a version conflict?
A: The problem was resolved. openDatabase() method throws an exception (SECURITY_ERR: DOM Exception 18) and returns null when the database size over 5 MB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to store user preferences in an application where users only communicate via SMS messages? I'm developing an application in java to be hosted in google app engine where i need to store user preferences(object with 10 String variables) untill he is logged in. I will be using this data frequently(once in two minutes per user).Should i use data store with memcache or are there any other scalable way? I'm expecting very high traffic(may be 50000 people at a time).Is it ok to store 50000 objects in memcache at a time?
It's an sms application where users interact only through SMS. So i cannot use session for storing data as my traffic is routed through SMS gateway.
A: Is it O.K. to store 50,000 objects in memcache? Sure, but as others have correctly noted, it's a cache, so you're going end up storing data in the datastore, too.
Stepping back, one of the big reasons to use memcache in an interactive application is for a better user experience. You want to minimize response time by caching things might introduce a noticeable delay if you had to pull them out of slower storage.
Is that even worth doing for an SMS app? Compared to the delays in the SMS infrastructure, I'd bet that the time difference between memcache and datastore is barely measurable.
I'd keep your app as simple as possible until it works, then look for optimization opportunities. I think you'll find them more along the lines of making sure that properties you're going to use in queries are unindexed, so that your writes will be faster.
A: Store it in the session. Memcache is a cache and shouldn't be used directly for business logic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3: How to find records with field possibly equals to nil? I would like to find all SongWriters with maiden_name equals to my_maiden_name ?
Note: my_maiden_name may be nil
I tried:
SongWriter.where("maiden_name = ?", my_maiden_name)
and it works fine except the case where my_maiden_name = nil.
When my_maiden_name = nil, the generated query is:
SELECT `song_writers`.* FROM `song_writers` WHERE (maiden_name = NULL)
rather than:
SELECT `song_writers`.* FROM `song_writers` WHERE maiden_name IS NULL
How could I generalize the active record query to include the case my_maiden_name = nil ?
A: Use the Hash syntax. ActiveRecord will do the conversion for you.
SongWriter.where(:maiden_name => my_maiden_name)
When my_maiden_name is nil it will use IS NULL. Otherwise it will use =.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mockito match any class argument Is there a way to match any class argument of the below sample routine?
class A {
public B method(Class<? extends A> a) {}
}
How can I always return a new B() regardless of which class is passed into method? The following attempt only works for the specific case where A is matched.
A a = new A();
B b = new B();
when(a.method(eq(A.class))).thenReturn(b);
EDIT: One solution is
(Class<?>) any(Class.class)
A: There is another way to do that without cast:
when(a.method(Matchers.<Class<A>>any())).thenReturn(b);
This solution forces the method any() to return Class<A> type and not its default value (Object).
A: If you have no idea which Package you need to import:
import static org.mockito.ArgumentMatchers.any;
any(SomeClass.class)
OR
import org.mockito.ArgumentMatchers;
ArgumentMatchers.any(SomeClass.class)
A: How about:
when(a.method(isA(A.class))).thenReturn(b);
or:
when(a.method((A)notNull())).thenReturn(b);
A: Two more ways to do it (see my comment on the previous answer by @Tomasz Nurkiewicz):
The first relies on the fact that the compiler simply won't let you pass in something of the wrong type:
when(a.method(any(Class.class))).thenReturn(b);
You lose the exact typing (the Class<? extends A>) but it probably works as you need it to.
The second is a lot more involved but is arguably a better solution if you really want to be sure that the argument to method() is an A or a subclass of A:
when(a.method(Matchers.argThat(new ClassOrSubclassMatcher<A>(A.class)))).thenReturn(b);
Where ClassOrSubclassMatcher is an org.hamcrest.BaseMatcher defined as:
public class ClassOrSubclassMatcher<T> extends BaseMatcher<Class<T>> {
private final Class<T> targetClass;
public ClassOrSubclassMatcher(Class<T> targetClass) {
this.targetClass = targetClass;
}
@SuppressWarnings("unchecked")
public boolean matches(Object obj) {
if (obj != null) {
if (obj instanceof Class) {
return targetClass.isAssignableFrom((Class<T>) obj);
}
}
return false;
}
public void describeTo(Description desc) {
desc.appendText("Matches a class or subclass");
}
}
Phew! I'd go with the first option until you really need to get finer control over what method() actually returns :-)
A: the solution from millhouse is not working anymore with recent version of mockito
This solution work with java 8 and mockito 2.2.9
where ArgumentMatcher is an instanceof org.mockito.ArgumentMatcher
public class ClassOrSubclassMatcher<T> implements ArgumentMatcher<Class<T>> {
private final Class<T> targetClass;
public ClassOrSubclassMatcher(Class<T> targetClass) {
this.targetClass = targetClass;
}
@Override
public boolean matches(Class<T> obj) {
if (obj != null) {
if (obj instanceof Class) {
return targetClass.isAssignableFrom( obj);
}
}
return false;
}
}
And the use
when(a.method(ArgumentMatchers.argThat(new ClassOrSubclassMatcher<>(A.class)))).thenReturn(b);
A: None of the examples above worked for me, as I'm required to mock one method multiple times for different class type parameters.
Instead, this works.
//Handle InstrumentType.class
Mockito.doReturn(new InstrumentTypeMapper() {
@Override
public InstrumentType map(String sourceType) throws Exception {
return InstrumentType.Unknown;
}
}).when(mappingLoader).load(any(ServiceCode.class), argThat(new ArgumentMatcher<Class<InstrumentType>>() {
@Override
public boolean matches(Class<InstrumentType> argument) {
return InstrumentType.class.isAssignableFrom(argument);
}
}));
//Handle InstrumentSubType.class
Mockito.doReturn(new InstrumentSubTypeMapper() {
@Override
public InstrumentSubType map(String sourceType) throws Exception {
return InstrumentSubType.istNone;
}
}).when(mappingLoader).load(any(ServiceCode.class), argThat(new ArgumentMatcher<Class<InstrumentSubType>>() {
@Override
public boolean matches(Class<InstrumentSubType> argument) {
return InstrumentSubType.class.isAssignableFrom(argument);
}
}));
This is the short version:
Mockito.doReturn(new InstrumentTypeMapper() {
@Override
public InstrumentType map(String sourceType) throws Exception {
return InstrumentType.Unknown;
}
}).when(mappingLoader).load(any(ServiceCode.class), argThat((ArgumentMatcher<Class<InstrumentType>>) InstrumentType.class::isAssignableFrom));
Mockito.doReturn(new InstrumentSubTypeMapper() {
@Override
public InstrumentSubType map(String sourceType) throws Exception {
return InstrumentSubType.istNone;
}
}).when(mappingLoader).load(any(ServiceCode.class), argThat((ArgumentMatcher<Class<InstrumentSubType>>) InstrumentSubType.class::isAssignableFrom));
As you can see, I'm using custom ArgumentMatchers together with argThat, not sure if there is a shorter way that also works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "196"
} |
Q: SMTP does not send HTML message Good morning,
I'm trying to send SMTP mail with HTML message. But not this gets the message.
So I did a test. Text messages sent successfully. Html message and sends it with little success.
And server problem that is not accepting my post html?
Server Response:
220 HOST ESMTP
250-HOST
250-PIPELINING
250-SIZE 40960000
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-AUTH = PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250 8BITMIME
Response connection.:
220 HOST ESMTP
250-HOST
250-PIPELINING
250-SIZE 40960000
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250 8BITMIME
334 VXNlcm5hbWU6
334 UGFzc3dvcmQ6
235 2.7.0 Authentication successful
250 2.1.0 Ok
250 2.1.5 Ok
354 End data with .
250 2.0.0 Ok: queued as 3B74C7E40BA 221 2.0.0 Bye
My code:
private function conx(){
$this->conxe = fsockopen($smtp_serve, $port, $errno, $errstr, 30) or die('Erro log: smtp 12');
return true;
}
private function send_email($email_send, $sub, $body_m){
$this->socket("EHLO ".$smtp_serve."");
$this->socket("AUTH LOGIN");
$this->socket(base64_encode($user));
$this->socket(base64_encode($pass));
$this->socket("MAIL FROM:" .$smtp_in);
$this->socket("RCPT TO:" .$email_send);
$this->socket("DATA");
$this->socket($this->body($email_send, $sub, $body_m));
$this->socket(".");
$this->socket("QUIT");
fclose($this->socket);
}
private function body($email_send, $sub, $body_m){
$this->co = "To: ".$email_send." <".$email_send."> \r\n";
$this->co .= "From: $my_email <$my_email> \r\n";
$this->co .= "Subject: ".$sub." \r\n";
$this->co .= "$body_m \r\n";
$this->co .= "MIME-Version: 1.0 \r\n";
$this->co .= "Content-Type: text/html; \r\n";
$this->co .= "charset=\"iso-8859-1\" \r\n";
return $this->co;
}
private function socket(){
return fputs($this->conxe, $string."\r\n"); //fwrite
}
I would be very grateful for the help.
A: Try this. It's an alternatieve to the mail() function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ext.js dipatch how to? I have a question regarding using Ext.dispatch in MVC. The scenario is simple, how about for one event, I want to dispatch into two separate controller? should i duplicate ext.dispatch or ext.dispatch can receive any type of array or object for controller property?
e.g:
Ext.dispatch({ controller: ['cont1', 'cont2'], action: ['show', 'create']})
How should I do it? Thanks in advance
A: You will need to execute two different Ext.dispatch calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails, link to previous page without losing content My rails app has a basic search function that queries the database and displays a list of active records. The search results are displayed as links. When the user clicks on a link for a given search result they will be taken to a page with details of their selection and what not. I want to have a back button on this details page that will take the user back to the search results page with the search results still showing up. The way it is now the back button takes the user back to the search results page but all of the search results are gone.
A: You have to pass the query parameter(search text) to the details page where you have the back button.
Include the query parameter in the back button url as http://localhost:3000/search?query=foo
A: Capture search query information in params[:query] and take it from one page to another.
In result detail page add this:
<%= link_to 'Back', "#{:back}+#{params[:query]}", :class => 'button' %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails2 add middlware from gem I have gem with generators(one for rails3 one for rails2). And i need to add middleware layer. Rails 3 generators add it great. How can i do it in rails2 generator?
A: Rails since 2.3 is a Rack based and allows you to add custom middleware in a stack.
you need to know the middleware class_name before, then add it to config/environment.rb, like this:
config.middleware.use "CustomClass"
then check the stack:
rake middleware
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: (#210) User not visible I'm writing a facebook app in which the logged in user (a) chooses a friends from their friends list (b) and then the app posts on their friends wall (a posts to b).
I ask from the user the publish_stream permissions.
This is the code for showing the friends selector popup:
function selectFriends() {
FB.ui({
method: 'apprequests',
message: 'You should learn more about this awesome game.', data: 'tracking information for the user'
},function(response) {
if (response && response.request_ids) {
//alert(typeof(response.request_ids));
//alert(response.request_ids);
alert (response.request_ids);
len=response.request_ids.length;
alert(len);
if (len>2) {
alert("Select no more than one friend");
}
else {
user_req_id = response.request_ids[0];
postOnFirendsWall(user_req_id);
}
}
else {
alert('Post was not published.');
}
});
}
This is the postOnFirendsWall(user_req_id) method:
function postOnFirendsWall(friend_id)
{
/** Auto Publish **/
var params = {};
params['message'] = 'message';
params['name'] = 'name';
params['description'] = '';
params['link'] = 'https://www.link.com/';
params['picture'] = 'http://profile.ak.fbcdn.net/hprofile-ak-snc4/203550_189420071078986_7788205_q.jpg';
params['caption'] = 'caption';
var stam = '/'+friend_id+'/feed';
FB.api('/'+friend_id+'/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
alert(response.error);
} else {
alert('Published to stream - you might want to delete it now!');
}
});
return false;
}
But I keep getting the following error: (#210) User not visible.
Can you see why?
A: Have you verified that user A has permission to write on the wall of user B? If not, this will never work.
Also, why are you using an apprequests dialog if you want to post on a friend's wall?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Objects Pools, IoC & Factories: When and Where? Widget oPooledWidget = (Widget)oObjectPool.borrowObject();
Widget oInjectedWidget = oAppContext.getBeans("widget");
Widget oFactoryWidget = oWidgetFactory.createWidget();
Many different ways exist to instantiate classes without the new operator and a constructor, and I'm looking for the generally-accepted use cases/scenarios for when to choose one over the other.
Obviously it is not appropriate to pool objects in certain circumstances, such as when you either have no idea how big the pool could get, or when you know the pool would be huge.
But what is an appropriate scenario that calls for pooling? When does pooling offer benefits over dependency injection or factory classes?
Similarly, when would one want to choose using a factory class over dependency injection, and vice versa?
A: Dependency injection came from a time when code had gazillion of Factories. So, DI is a convinient replacement for Factories. You can call DI context as a universal Factory. Also, object pool can be a bean defined in DI context. Though object pool implements an interface that application code must use in order to keep the pool consistent. Objects retrieved from the pool have different lifecycle compared to DI context beans:
pool = appContext.getBean("connectionPool");
conn = pool.get();
try {
// .. do stuff
} finally {
conn.close();
// or
pool.release(conn);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this try-catch block valid? Newby question...
Is it valid to do:
try
{
// code which may fail
}
catch
{
Console.Writeline("Some message");
}
Or do I always have to use:
try
{
// code which may fail
}
catch (Exception e)
{
Console.Writeline("Some message");
}
A: Both blocks are valid.
The first will not have an exception variable.
If you are not going to do anything with the exception variable but still want to catch specific exceptions, you can also do:
try
{
// your code here
}
catch(SpecificException)
{
// do something - perhaps you know the exception is benign
}
However, for readability I would go with the second option and use the exception variable. One of the worst things to do with exceptions is swallow them silently - at the minimum, log the exception.
A: Yep, absolutely, such a catch block called general catch clause, see more interesting details in the C# Language Specification 4.0, 8.10 The try statement:
A catch clause that specifies neither an exception type nor an
exception variable name is called a general catch clause. A try
statement can only have one general catch clause, and if one is
present it must be the last catch clause
A: Yes, your first block of code valid. It will catch all exceptions.
A: It is. It will catch all the exception. So the two code examples do the same.
A: First one is valid, and it acts just like the second one.
http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx
The catch clause can be used without arguments, in which case it
catches any type of exception, and referred to as the general catch
clause. It can also take an object argument derived from
System.Exception, in which case it handles a specific exception.
A: As @David answered this is valid.
You could use second syntax if you want to get more infos or catch a specific exception.
E.g.
catch (Exception e)
{
Debug.Print(e.Message);
}
A: Yes it is valid.
you can always refer to this article:
Best Practices for Handling Exceptions on MSDN
A: Of course it is valid, you specify catch(Exception e) when you want to output the error message ex.Message, or to catch a custom or a concrete Exception. Use catch in your situation.
A: catch (Exception e)
{
Console.Writeline("Some message");
}
In this block you can use SqlException, etc..
catch (SqlException e)
{
Console.Writeline("Some message");
}
For this use the "(SqlException e)"
If you will use a generic menssage, use this:
catch
{
Console.Writeline("Some message");
}
or
catch (Exception)
{
Console.Writeline("Some message");
}
A: Don't forget that you can chain catch your exceptions. This will allow you to handle different scenarios based upon the exception(s) the code may throw.
try
{
//Your code.
}
catch(SpecificException specificException)
{
//Handle the SpecificException
}
catch(AnotherSpecificException anotherSpecificException)
{
//Handle AnotherSpecificException
}
catch(Exception exception)
{
//Handle any Exception
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can't post to user's wall, though I get publish_stream permission I'm implementing an app which will post to user's wall.
I specify appropriate scopes (including publish_stream) via php-sdk, display the authentication page and can confirm that my app requires publish_stream. But when the app tries to post to user wall, I get the following error message:
The user hasn't authorized the application to perform this action
Also, my app cannot get public_stream permission when I confirm the app from user's privacy setting.
I could confirm that my app's authentication of publish_stream worked well one weeks ago.
Are there any problem regarding publish_stream permission?
A: fb in your app insight to see if your app is restricted for publishing stream
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regarding uiimagepickercontroller In my application i have to upload a image and that image is taken from the ipad camera, now my query is when i choose the button "TakePicture" the cameraview opens can I resize the cameraview which captures the image.
Here is my code.
- (void) takePicture {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];
}
A: Do you mean view itself? No, the size couldn't be changed. If you mean size of taken/chosen image, user will be allowed to do resizing if you set allowsEditing to YES.
A: Dont think so, that is an internal ui call,
You might be able to put some custom overlay on the camera view as quite a few other apps do, but to resize the internal camera view is not what apple wants us to do.
But then again, it would be a nice to have as we can use that for some really cool effects!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Data Retrieving from XML file with some limitation in Java I am using XML in my project for data to be Insert/Update/Delete.
Currently i am using XPath for doing the above operations from my Java application.
I am facing a problem while retrieving the data from XML. If there are 1000 records in the XML file i want to get the data from XML file with some limit (same as limit in a MySQL select query) in the rows, for implementing the pagination in the view page. I want to display 100 records at a time, so that end-user can click on next button to see all the 1000 records.
Can anyone tell me the best way to full-fill this requirement?
Ya, we can do it with "position()" function but the problem is i want to get the data in an sorted order. position() will return the data from the XML file respective to the given number(in XML file the data may not be in an order). So i want to read the data along with order. I am not able to find the XML query for Sorting and Paginated data in XPath.
A: You can consider using JAXB instead of direct XML manipulation.
A: As you are using XPath to access your XML data, one possibility could be the position() function to get "paginated" data from the XML. Like:
/path/to/some/element[position() >= 100 and position() <= 200]
Of course you have to store the boundaries (e.g. 100 - 200 as an example) then between user requests.
Ok, if you need sorted output aswell... as far as I know there is no sort function in pure xpath (1.0/2.0). Maybe you are using a library that offers this as an extension. Or you maybe have the possibility to use an XSLT and xsl:sort. Or you use XML binding as written in the other answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to test file download with Watin / IE9? I'm trying to test file download with Watin 2.1.0 against IE9. I used the suggested code from the accepted answer to the question Downloading a file with Watin in IE9, like this:
var downloadHandler = new FileDownloadHandler(fname);
WebBrowser.Current.AddDialogHandler(downloadHandler);
link.ClickNoWait();
downloadHandler.WaitUntilFileDownloadDialogIsHandled(15);
downloadHandler.WaitUntilDownloadCompleted(200);
However, the downloadHandler.WaitUntilFileDownloadDialogIsHandled(15) call times out. What should I do?
A: IE9 no longer uses a dialog window for saving files. Instead, it uses the notification bar to prevent focus from being removed from the web site. See http://msdn.microsoft.com/en-us/ie/ff959805.aspx under "Download Manager" for reference.
Unfortunately, this means that the current FileDownloadHandler in WatiN will not work. It instantiates a "DialogWatcher" class per browser instance that is a basic message pump for any kind of child window. When child windows are encountered, the DialogWatcher checks to see if the window is specifically a dialog (which the notification bar is not). If it is a dialog, it then iterates over the registered IDialogHandler instances calling "CanHandleDialog." Even if the notification bar were a dialog, it is of a different Window Style (http://msdn.microsoft.com/en-us/library/windows/desktop/ms632600(v=vs.85).aspx), which is how WatiN detects the type of dialog.
From what I can see, there is no support yet for detecting the IE 9 notification bar and its prompts in WatiN. Until that support is added, you will not be able to automate downloading files in IE9.
A: File download dialog doesn't work in IE9 (Windows7) NetFramework 4.0.
Following code snippet might help you resolve the issue:
First you must add references UIAutomationClient and UIAutomationTypes to your test project.
After In Ie9 Tools -> View Downloads -> Options define path to your save folder.
The next method extends Browser class
public static void DownloadIEFile(this Browser browser)
{
// see information here (http://msdn.microsoft.com/en-us/library/windows/desktop/ms633515(v=vs.85).aspx)
Window windowMain = new Window(WatiN.Core.Native.Windows.NativeMethods.GetWindow(browser.hWnd, 5));
System.Windows.Automation.TreeWalker trw = new System.Windows.Automation.TreeWalker(System.Windows.Automation.Condition.TrueCondition);
System.Windows.Automation.AutomationElement mainWindow = trw.GetParent(System.Windows.Automation.AutomationElement.FromHandle(browser.hWnd));
Window windowDialog = new Window(WatiN.Core.Native.Windows.NativeMethods.GetWindow(windowMain.Hwnd, 5));
// if doesn't work try to increase sleep interval or write your own waitUntill method
Thread.Sleep(1000);
windowDialog.SetActivate();
System.Windows.Automation.AutomationElementCollection amc = System.Windows.Automation.AutomationElement.FromHandle(windowDialog.Hwnd).FindAll(System.Windows.Automation.TreeScope.Children, System.Windows.Automation.Condition.TrueCondition);
foreach (System.Windows.Automation.AutomationElement element in amc)
{
// You can use "Save ", "Open", ''Cancel', or "Close" to find necessary button Or write your own enum
if (element.Current.Name.Equals("Save"))
{
// if doesn't work try to increase sleep interval or write your own waitUntil method
// WaitUntilButtonExsist(element,100);
Thread.Sleep(1000);
System.Windows.Automation.AutomationPattern[] pats = element.GetSupportedPatterns();
// replace this foreach if you need 'Save as' with code bellow
foreach (System.Windows.Automation.AutomationPattern pat in pats)
{
// '10000' button click event id
if (pat.Id == 10000)
{
System.Windows.Automation.InvokePattern click = (System.Windows.Automation.InvokePattern)element.GetCurrentPattern(pat);
click.Invoke();
}
}
}
}
}
if you want click 'Save As' replace foreach code with this
System.Windows.Automation.AutomationElementCollection bmc = element.FindAll(System.Windows.Automation.TreeScope.Children, System.Windows.Automation.Automation.ControlViewCondition);
System.Windows.Automation.InvokePattern click1 = (System.Windows.Automation.InvokePattern)bmc[0].GetCurrentPattern(System.Windows.Automation.AutomationPattern.LookupById(10000));
click1.Invoke();
Thread.Sleep(10000);
System.Windows.Automation.AutomationElementCollection main = mainWindow.FindAll(System.Windows.Automation.TreeScope.Children
,System.Windows.Automation.Condition.TrueCondition);
foreach (System.Windows.Automation.AutomationElement el in main)
{
if (el.Current.LocalizedControlType == "menu")
{
// first array element 'Save', second array element 'Save as', third second array element 'Save and open'
System.Windows.Automation.InvokePattern clickMenu = (System.Windows.Automation.InvokePattern)
el.FindAll(System.Windows.Automation.TreeScope.Children, System.Windows.Automation.Condition.TrueCondition) [1].GetCurrentPattern(System.Windows.Automation.AutomationPattern.LookupById(10000));
clickMenu.Invoke();
//add ControlSaveDialog(mainWindow, filename) here if needed
break;
}
}
Edit:
Also if you need to automate the save as dialog specifying a path and clicking save you can do it by adding this code just before break;
private static void ControlSaveDialog(System.Windows.Automation.AutomationElement mainWindow, string path)
{
//obtain the save as dialog
var saveAsDialog = mainWindow
.FindFirst(TreeScope.Descendants,
new PropertyCondition(AutomationElement.NameProperty, "Save As"));
//get the file name box
var saveAsText = saveAsDialog
.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.NameProperty, "File name:"),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)))
.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
//fill the filename box
saveAsText.SetValue(path);
Thread.Sleep(1000);
//find the save button
var saveButton =
saveAsDialog.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.NameProperty, "Save"),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)));
//invoke the button
var pattern = saveButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
pattern.Invoke();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Fatal Runtime Error in WPF when switching between visual states I keep having this error sometimes in a particular case. It happens precisely when I am switching from a visual state to another. I assume it comes from a bad property animation but I wonder what are the conditions in which this exception occurs.
Here is the error message:
The runtime has encountered a fatal error. The address of the error was at 0x58e3ba0d, on thread 0xabc. The error code is 0x80131623. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
Thank you in advance
A: I think I found the explanation: During state transition, I was trying to collapse parts of the UI. Among these parts, there are some controls (buttons) that have several behaviors attached.
After some tests I noticed that collapsing a control that has a behavior attached seems to throw an exception. Collapsing deletes the reference to the object and the attached behavior is left with a null reference that makes it throwing an exception.
I don't know precisely what's happening, but I am pretty sure this is the cause. It seems to happen also with "hidden" visibility. So the only workaround I found for the moment is reducing the opacity of the control et setting its height to 0.
If someone found a better way to avoid this problem...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: using sockets to fetch a webpage with java I'd like to fetch a webpage, just fetching the data (not parsing or rendering anything), just catch the data returned after a http request.
I'm trying to do this using the high-level Class Socket of the JavaRuntime Library.
I wonder if this is possible since I'm not at ease figuring out the beneath layer used for this two-point communication or I don't know if the trouble is coming from my own system.
.
Here's what my code is doing:
1) setting the socket.
this.socket = new Socket( "www.example.com", 80 );
2) setting the appropriate streams used for this communication.
this.out = new PrintWriter( socket.getOutputStream(), true);
this.in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
3) requesting the page (and this is where I'm not sure it's alright to do like this).
String query = "";
query += "GET / HTTP/1.1\r\n";
query += "Host: www.example.com\r\n";
...
query += "\r\n";
this.out.print(query);
4) reading the result (nothing in my case).
System.out.print( this.in.readLine() );
5) closing socket and streams.
A: If you're on a *nix system, look into CURL, which allows you to retrieve information off the internet using the command line. More lightweight than a Java socket connection.
If you want to use Java, and are just retrieving information from a webpage, check out the Java URL library (java.net.URL). Some sample Java code:
URL ur = new URL("www.google.com");
URLConnection conn = ur.openConnection();
InputStream is = conn.getInputStream();
String foo = new Scanner(is).useDelimiter("\\A").next();
System.out.println(foo);
That'll grab the specified URL, grab the data (html in this case) and spit it out to the console. Might have to tweak the delimiter abit, but this will work with most network endpoints sending data.
A: Your code looks pretty close. Your GET request is probably malformed in some way. Try this: open up a telnet client and connect to a web server. Paste in the GET request as you believe it should work. See if that returns anything. If it doesn't it means there is a problem with the GET request. The easiest thing to do that point would be write a program that listens on a socket (more or less the inverse of what you're doing) and point a web browser to localhost:[correct port] and see what the web browser sends you. Use that as your template for the GET request.
Alternatively you could try and piece it together from the HTTP specification.
A: I had to add the full URL to the GET parameter. To make it work. Although I see you can specify HOST also if you want.
Socket socket = new Socket("youtube.com",80);
PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream())));
out.println("GET http://www.youtube.com/yts/img/favicon_48-vflVjB_Qk.png
HTTP/1.0");
out.println();
out.flush();
A: Yes, it is possible. You just need to figure out the protocol. You are close.
I would create a simple server socket that prints out what it gets in. You can then use your browser to connect to the socket using a url like: http://localhost:8080. Then use your client socket to mimic the HTTP protocol from the browser.
A: Not sure why you're going lower down than URLConnection - its designed to do what you want to do: http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html.
The Java Tutorial on Sockets even says: "URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application." Since you're not going lower than HTTP, I'm not sure what the point is of using a Socket.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Introspect parameter of type: id to decide whether it is a class or a protocol I have the following method:
-(void)SomeMethod:(id)classOrProtocol;
It will be called like this:
[self someMethod:@protocol(SomeProtocol)];
Or
[self someMethod:[SomeClass class]];
Within the method body I need to decide if |classOrProtocol| is:
Any Class(Class) OR Any Protocol(Protocol) OR Anything else
[[classOrProtocol class] isKindOfClass: [Protocol class]]
Results in a (build)error:
Receiver 'Protocol' is a forward class and corresponding @interface may not exist
So how can I tell a Protocol from a Class from anything else?
A: In Objective-C 2 (i.e. unless you use 32 bit runtime on OS X) Protocol is defined to be just a forward class, see /usr/include/objc/runtime.h. The real interface is nowhere declared. You can try to include /usr/inlcude/objc/Protocol.h by saying
#import <objc/Protocol.h>
but as is written there, no method is publicly supported for an instance of Protocol. The only accepted way to deal with Protocol instances is to use runtime functions, given in Objective-C Runtime Reference. It's not even publicly defined whether Protocol is a subclass of anything, and it's not even stated that it implements NSObject protocol. So you can't call any method on it.
Of course you can use the source code of the runtime to see what's going on. Protocol inherits from Object (which is a remnant from pre-OpenStep NeXTSTep), not from NSObject. So you can't use the familiar methods for NSObject-derived objects, including Class of NSObject-derived objects. See the opensourced implementations of Protocol.h and Protocol.m. As you see there, the class Protocol itself doesn't do anything, because every method just casts self to protocol_t and calls a function. In fact, as can be seen from the function _read_images and others in objc-runtime-new.mm, the isa pointer of a Protocol object is set by hand when the executable and libraries are loaded, and never used.
So, don't try to inspect whether an id is a Protocol or not.
If you really need to do this, you can use
id foo=...;
if(foo->isa==class_getClass("Protocol")){
...
}
But, seriously, don't do it.
A: This is not an issue 'caused by inability to determine whether it's class or protocol. The error is 'caused by missing interface of Protocol class. Make sure you import Protocol.m at the top of your implementation file where you're testing argument's type.
You can also try using NSClassFromString() function which will return Class object or nil. Do note though that if nil is returned it doesn't mean that argument is protocol. It just means that it could be undefined class too!
There is also method NSProtocolFromString which returns appropriate results - Protocol for protocol and nil for undefined protocol.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: fastest search on elements in html i have a page with many divs on which i need to implement some JavaScript functions. Is there a way to tell the browser to sort all divs by for example id so that I can find quickly an element.I generally don't know how browsers handle searching of elements, is there some sorting or not on major browsers firefox, chrome, ie? How do elements get indexed?
A: Every browser already holds a such an index on id's and classes for use with, for example, css.
You shouldn't worry about indexing the DOM, it's been done and ready for use.
If you want to hang events on elements, just do so. Either by use of 'document.getElementById(id) or document.getElementsByClassName(class) (that last one might bump into IE-issues)
A: I think jquery will help you in that case...
or with simple javascript you can getElementById, or getElementsByTagName
A: the browsers creates a tree like structure named DOM (Document Object Model), with the root being the html tag for example, then it's children, their children's children, etc..
There are functions that let's you access the DOM and find the required elements. But this is done in the browser's inner implementation. You can not change how it handles the page elements, just use the browser's API to locate elements
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JScrollPane getX() returing wrong value ? I wish to place a small Jframe right above the Button, on ActionPerformed
I directly tried to get the X (getX()) and Y(getY()) co-ordinates of the JScrollPane in which the button is added, but it always seems to return wrong co-coordinates
values returned by jScrollPane1.getLocation()
java.awt.Point[x=10,y=170]
The above values are same independent on where I place the JScrollPane on the screen.
This works if I remove the JScrollPane and directly try to get the Jpanels co-ordinates!!
A: for example
private void showDialog() {
if (canShow) {
location = myButton.getLocationOnScreen();
int x = location.x;
int y = location.y;
dialog.setLocation(x - 466, y - 514);
if (!(dialog.isVisible())) {
Runnable doRun = new Runnable() {
@Override
public void run() {
dialog.setVisible(true);
//setFocusButton();
//another method that moving Focus to the desired JComponent
}
};
SwingUtilities.invokeLater(doRun);
}
}
}
A: This nice method will help you:
// Convert a coordinate relative to a component's bounds to screen coordinates
Point pt = new Point(component.getLocation());
SwingUtilities.convertPointToScreen(pt, component);
// pt is now the absolute screen coordinate of the component
Add: I didn't realise, but like mKorbel wrote, you can simply call
Point pt = component.getLocationOnScreen();
A: Since you want to spawn a new frame right above a given component, you want to get the screen coordinates of your component.
For this, you need to use the getLocationOnScreen() method of your component.
Here is a useful code snippet :
public void showFrameAboveCmp(Frame frame, Component cmp) {
Dimension size = cmp.getSize();
Point loc = cmp.getLocationOnScreen();
Dimension frameSize = frame.getSize();
loc.x += (size.width - frameSize.width)/2;
loc.y += (size.height - frameSize.height)/2;
frame.setBounds(loc.x, loc.y, frameSize.width, frameSize.height);
frame.setVisible(true);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Displaying dynamic text I need to display some text but the text is going to change a lot and I need for it to be editable. I know I can use from input but is there any other way?
A: MDN has a nice example and MSDN - here for contenteditable
<div id="toEdit" contenteditable="true" onkeyup="doSomething(this.id);"></div>
doSomething function can manipulate the data (store/send whatever).
A: You can use ajax query and change the value of the text area.. using that.. hope this help
A: you can put a little button (or use even the text itself as a handler) so that when a user clicks, you add the input to change the text using ajax.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sharepoint 2010. Add custom background and frame for content editor webpart I need to create custom webpart with complex (few divs, or other html elements) background and borders.
How can i use default sharepoint content editor and just add predefined background and frame!?
Thanks.
A: You tagged your question with Sharepoint 2007 and 2010, the content editors are different though. This answer is for SP2010:
You can just add CSS to a custom CSS file. background-image for .ms-rte-layoutzone-inner-editable will do the image trick. If you want to add a "frame" as in border, you can add border attributes to .ms-rte-layoutzone-outer and make it e.g. red.
An example for a background image:
.ms-rte-layoutzone-inner-editable {
border-image: url(/PublishingImages/Mylogo.gif);
}
But please do your users a favor and don't include anything blinking or distracting to the content editor's background - if you wanna go for some very light grey or something like that it's OK.
For MOSS2007 you need to check the specific styles you can override.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: bug? in codesign --remove-signature feature I would like to remove the digital signature from a Mac app that has been signed with codesign. There is an undocumented option to codesign, --remove-signature, which by it's name seems to be what I need. However, I can't get it to work. I realize it is undocumented, but I could really use the functionality. Maybe I'm doing something wrong?
codesign -s MyIdentity foo.app
works normally, signing the app
codesign --remove-signature foo.app
does disk activity for several seconds, then says
foo.app: invalid format for signature
and foo.app has grown to 1.9 GB!!! (Specifically, it is the executable in foo.app/Contents/Resources/MacOS that grows, from 1.1 MB to 1.9 GB.)
The same thing happens when I try to sign/unsign a binary support tool instead of a .app.
Any ideas?
Background: This is my own app; I'm not trying to defeat copy protection or anything like that.
I would like to distribute a signed app so that each update to the app won't need user approval to read/write the app's entries in the Keychain. However, some people need to modify the app by adding their own folder to /Resources. If they do that, the signature becomes invalid, and the app can't use it's own Keychain entries.
The app can easily detect if this situation has happened. If the app could then remove it's signature, everything would be fine. Those people who make this modification would need to give the modified, now-unsigned app permission to use the Keychain, but that's fine with me.
A: A bit late, but I've updated a public-domain tool called unsign which modifies executables to clear out signatures.
https://github.com/steakknife/unsign
A: I ran into this issue today. I can confirm that the --remove-signature option to Apple's codesign is (and remains, six years after the OP asked this question) seriously buggy.
For a little background, Xcode (and Apple's command line developer tools) include the codesign utility, but there is not included a tool for removing signatures. However, as this is something that needs to be done in certain situations pretty frequently, there is included a completely undocumented option:
codesign --remove-signature which (one assumes, given lack of documentation) should, well, be fairly self-explanatory but unfortunately, it rarely works as intended without some effort. So I ended up writing a script that should take care of the OP's problem, mine, and similar. If enough people find it here and find it useful, let me know and I'll put it on GitHub or something.
#!/bin/sh # codesign_remove_for_real -- working `codesign --remove-signature`
# (c) 2018 G. Nixon. BSD 2-clause minus retain/reproduce license requirements.
total_size(){
# Why its so damn hard to get decent recursive filesize total in the shell?
# - Darwin `du` doesn't do *bytes* (or anything less than 512B blocks)
# - `find` size options are completely non-standardized and doesn't recurse
# - `stat` is not in POSIX at all, and its options are all over the map...
# - ... etc.
# So: here we just use `find` for a recursive list of *files*, then wc -c
# and total it all up. Which sucks, because we have to read in every bit
# of every file. But its the only truly portable solution I think.
find "$@" -type f -print0 | xargs -0n1 cat | wc -c | tr -d '[:space:]'
}
# Get an accurate byte count before we touch anything. Zero would be bad.
size_total=$(total_size "$@") && [ $size_total -gt 0 ] || exit 1
recursively_repeat_remove_signature(){
# `codesign --remove-signature` randomly fails in a few ways.
# If you're lucky, you'll get an error like:
# [...]/codesign_allocate: can't write output file: [...] (Invalid argument)
# [...] the codesign_allocate helper tool cannot be found or used
# or something to that effect, in which case it will return non-zero.
# So we'll try it (suppressing stderr), and if it fails we'll just try again.
codesign --remove-signature --deep "$@" 2>/dev/null ||
recursively_repeat_remove_signature "$@"
# Unfortunately, the other very common way it fails is to do something? that
# hugely increases the binary size(s) by a seemingly arbitrary amount and
# then exits 0. `codesign -v` will tell you that there's no signature, but
# there are other telltale signs its not completely removed. For example,
# if you try stripping an executable after this, you'll get something like
# strip: changes being made to the file will invalidate the code signature
# So, the solution (well, my solution) is to do a file size check; once
# we're finally getting the same result, we've probably been sucessful.
# We could of course also use checksums, but its much faster this way.
[ $size_total == $(total_size "$@") ] ||
recursively_repeat_remove_signature "$@"
# Finally, remove any leftover _CodeSignature directories.
find "$@" -type d -name _CodeSignature -print0 | xargs -0n1 rm -rf
}
signature_info(){
# Get some info on code signatures. Not really required for anything here.
for info in "-dr-" "-vv"; do codesign $info "$@"; done # "-dvvvv"
}
# If we want to be be "verbose", check signature before. Un/comment out:
# echo >&2; echo "Current Signature State:" >&2; echo >&2; signature_info "$@"
# So we first remove any extended attributes and/or ACLs (which are common,
# and tend to interfere with the process here) then run our repeat scheme.
xattr -rc "$@" && chmod -RN "$@" && recursively_repeat_remove_signature "$@"
# Done!
# That's it; at this point, the executable or bundle(s) should sucessfully
# have truly become stripped of any code-signing. To test, one could
# try re-signing it again with an ad-hoc signature, then removing it again:
# (un/comment out below, as you see fit)
# echo >&2 && echo "Testing..." >&2; codesign -vvvvs - "$@" &&
# signature_info "$@" && recursively_repeat_remove_signature "$@"
# And of course, while it sometimes returns false positives, lets at least:
codesign -dvvvv "$@" || echo "Signature successfully removed!" >&2 && exit 0
A: Here's the source for codesign which lists all options, including those not covered by the command-line -h and man page.
Also, here is Apple's tech note on recent changes in how code-signing works
A: I agree that there's something strange going on when you did --remove-signature.
However, instead of trying to un-code-sign, you should change the way your user put extra files in the Resources. Instead, designate a certain path, usually
~/Library/Application Support/Name_Of_Your_App/
or maybe
~/Library/Application Support/Name_Of_Your_App/Resources/
and ask the user to put extra files there. Then, in your code, always check for the directory in addition to the files in the Resources when you need to read a file.
A: On a second reading of this question, another thought: perhaps a better approach to accomplish what the ultimate goal of the question is would be not to remove the signatures, but to have users (via a script/transparently) re-sign the app after modification, using an ad-hoc signature. That is, codesign -fs - [app], I believe. See https://apple.stackexchange.com/questions/105588/anyone-with-experience-in-hacking-the-codesigning-on-os-x
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Writing bits to COM port in Windows - equivalent to INPORTB function I am writing a program to control a relay switch connected thru the serial (RS-232) COM1 port. The device I am using has contains two relay switches. These are either 'open' or 'closed'.
By default, both relays are open. The number 1 relay is closed by setting bit 1 in the modem control register. Number 2 relay is closed by setting bit 0 in the modem control register.
In C, this can be achieved as follows:
x = inportb(0x3FC);
x=x & ~2; //Set bit 1 to zero
x=x | 2; //Set bit 1 to one
x=x & ~1; //Set bit 0 to zero
x=x | 1; //Set bit 0 to one
C++ however, does not make COM port access so easy (or so I am led to believe). I currently have the following code, which successfully opens and closes the COM port so that it can be communicated with in C++ and Windows:
#include <windows.h>
//Initialise Windows module
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance,
LPSTR lpszArgument, int nFunsterStil)
{
//Define the serial port precedure
HANDLE hSerial;
//Initialise relay
hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
//SOME CODE MUST GO HERE
//Deactivate relay
CloseHandle(hSerial);
return 0;
}
However, I am at a loss as to how to 'set bits'. I'm still very new to C++. Any help would be gratefully appreciated.
A: You need to understand how your device works. You cannot "set bits" directly in hSerial. Having COM port opened, you can send/receive bytes. Possibly you need to send something to device using WriteFile(hSerial, ...). Maybe you need to read information from device using ReadFile(hSerial, ...). COM port is not port as it was called in DOS, this is not address or register. This is input/output stream. You work with COM port like C program works with STDIN and STDOUT - read and wrire information from/to port.
Once you understand what your device needs (this means, define communication protocol), implement it in the program. Read this article: Serial Communications http://msdn.microsoft.com/en-us/library/ff802693.aspx - everything Win32 programmer needs to know about serial communications.
A: I am presuming that C example you give is not actually on a Windows box and is from some embedded platform is that correct? As it looks like you have direct access to the COM port hardware.
It is not as such C++ that makes this more challenging it is that Windows will not give you direct access to the hardware as you have on your embedded system. It is in fact not possible to set the level of specific pins on the COM port through the standard Windows API, you would need to write a driver that runs with increased privileges to achieve that. It might be impossible to do what you are trying to without writing a driver, something I wouldn't recommend.
The best solution would be to write the embedded end to accept commands as data sent over the RS-232 rather than look for levels on specific pins. The answer from Alex Farber provides a good link to get you started with serial comms in windows.
A: Not 100% sure what you are doing here, or what you want. The data on the serial port is, well, serial and you cannot drive relays directly by sending data to the UART tx buffer on 0x3FC. That and, as pointed out by other posters, access to the IO map is privileged since W95/98/ME/otherWintendo.
There may be good news - if you only need to drive two, (high sensitivity/low current), relays, you can do it by utilising the RTS and DTR control lines. The current available from these pins is enough to drive a 12V coil via. a diode, (line shifts from +12 to -12 so you need the diode on an ordinary non-polarised relay plus, if the relay does not already contain one, another diode to clamp any back EMFs during switching).
RTS/DTR can be driven from the serial APIs without any special privilege.
I am doing this now to simulate a flow sensor switch when testing an embedded controller.
Note that the relays cannot be toggled at any great rate - the IO is very slow. I can get about 15Hz on a good day. 4*4GHz cores, 12GB of RAM and my PC can only toggle 1 bit at 15Hz!
Rgds,
Martin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Safe DateTime in a T-SQL INSERT statement Been running in problem lately with using a DateTime in a T-SQL INSERT INTO statement. Work fine on one machine but might not work on another and I guess this has to do with locale settings.
So if I have DateTime variable what is the safe way of using that in a SqlStatement string that it will always work regardless on local system settings?
Thanks
A: Use parameterized INSERT query.
Most likely, your code is assembling the SQL command string. That also makes your code vulnerable to SQL Injection.
A: You should use parameterized query as Adrian suggested.
Another possibility is to use an ISO 8601 string representation like described here which is independent of locale settings.
That would look like:
20110921 15:20:00
A: Either you use parametrized command/stored procedures where you create a parameter of type DateTime in the stored and assign it from .net code when you call the stored (so .NET and SQL will know they are working with a datetime and will never confuse/swap day and month), or you include a specific command on top of your insert commands and then format all dataetime strings with this pattern, for example:
SET DATEFORMAT dmy;
SET DATEFORMAT (Transact-SQL)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Find all classes that implement a given protocol in XCode4 Is there an easy way in XCode 4, to find all the classes that implement a given protocol?
This looks like a pretty common scenario, but I couldn't find how to do it... The only solution I've found is searching (textual search) for the protocol name in the entire project, but of course the number of results is much grater than what I need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are Anders' BUILD async demos available for download anywhere? My Google-foo seems to be lacking today.
A: Is this what you're looking for: http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wget "mirroring" pdf linked to different domain Webpage contains a link to a pdf (note the different domains).
I can use wget to directly download the pdf, but cannot seem to identify the correct wget command line options to "mirror" the webpage including this linked pdf. I tried to use combinations of options like
*
*-p
*--span-hosts
*-D
*--accept
with no success.
Can wget (or some other command line tool) be used to download linked pdf-s?
Thank
A: Try parsing http://www.yowconference.com.au/brisbane/data/35.js. (I found this url with HttpFox.) After formatting the code (for example with http://jsbeautifier.org/) it's easy to grep out the url of pdf files.
A: While the pdf link is shown in browsers, the page source does not contain the download link. So wget does not get to see/follow the link, as it doesn't really "process" the page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android FragmentVIewPager and screen re-draw issue We're having a spot of a problem with the FragmentViewPager and Fragments.
We are using the CursorLoader to populate a list within a Fragment. The view pager consists of 4 pages.
Basically when swiping from one fragment to another it works just fine, but once we pull data from a service in the context of say fragment A and swipe to fragment B then C and so on, the list within the Fragment appears to not load i.e. a blank screen, but if the screen of the device is turned off and then on the list within the Fragment displays the data.
In the onLoadFinished method of the cursor loader we reset the adapter on every refresh.
I'm stumped for a solution. Any advice?
Additional Info, I also sometimes receive this stack trace.
09-21 15:20:44.489: INFO/dalvikvm(21106):
Landroid/view/ViewRoot$CalledFromWrongThreadException;: Only the
original thread that created a view hierarchy can touch its views.
09-21 15:20:44.497: INFO/dalvikvm(21106): at
android.view.ViewRoot.checkThread(ViewRoot.java:2932) 09-21
15:20:44.497: INFO/dalvikvm(21106): at
android.view.ViewRoot.requestLayout(ViewRoot.java:629) 09-21
15:20:44.501: INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.501:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.501:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.501:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.widget.RelativeLayout.requestLayout(RelativeLayout.java:257)
09-21 15:20:44.517: INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.view.View.requestLayout(View.java:8267) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.view.View.setFlags(View.java:4641) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.view.View.setVisibility(View.java:3116) 09-21 15:20:44.517:
INFO/dalvikvm(21106): at
android.widget.AdapterView.updateEmptyStatus(AdapterView.java:713)
09-21 15:20:44.517: INFO/dalvikvm(21106): at
android.widget.AdapterView.checkFocus(AdapterView.java:697) 09-21
15:20:44.517: INFO/dalvikvm(21106): at
android.widget.AdapterView$AdapterDataSetObserver.onInvalidated(AdapterView.java:812)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
android.database.DataSetObservable.notifyInvalidated(DataSetObservable.java:43)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
android.widget.BaseAdapter.notifyDataSetInvalidated(BaseAdapter.java:54)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
android.widget.CursorAdapter$MyDataSetObserver.onInvalidated(CursorAdapter.java:391)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
android.database.DataSetObservable.notifyInvalidated(DataSetObservable.java:43)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
android.database.AbstractCursor.deactivateInternal(AbstractCursor.java:89)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
android.database.AbstractCursor.close(AbstractCursor.java:108) 09-21
15:20:44.525: INFO/dalvikvm(21106): at
android.database.sqlite.SQLiteCursor.close(SQLiteCursor.java:504)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:594)
09-21 15:20:44.525: INFO/dalvikvm(21106): at
dalvik.system.NativeStart.run(Native Method)
Thanks,
Akshay
A: We seemed to have figured out the reason why this occurs, but don't really have an explanation, maybe someone could elaborate on this.
The response from the server used a service+ResultReceiver in the fragment to notify the UI of the background httpservice completion which works fine when used in an activity, but with a fragment any hook into the UI from the handler resulted in the UI crashing, as if a UI change was made from a separate thread, with no consistent complaint in the logs, other than the occasional error as seen above. Once we used a handler in the result receiver to notify the UI of a change we don't face this problem any longer.
Akshay
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Thrift : TypeError: getaddrinfo() argument 1 must be string or None Hi I am trying to write a simple thrift server in python (named PythonServer.py) with a single method that returns a string for learning purposes. The server code is below. I am having the following errors in the Thrift's python libraries when I run the server. Has anyone experienced this problem and suggest a workaround?
The execution output:
Starting server
Traceback (most recent call last):
File "/home/dae/workspace/BasicTestEnvironmentV1.0/src/PythonServer.py", line 38, in <module>
server.serve()
File "usr/lib/python2.6/site-packages/thrift/server/TServer.py", line 101, in serve
File "usr/lib/python2.6/site-packages/thrift/transport/TSocket.py", line 136, in listen
File "usr/lib/python2.6/site-packages/thrift/transport/TSocket.py", line 31, in _resolveAddr
TypeError: getaddrinfo() argument 1 must be string or None
PythonServer.java
port = 9090
import MyService as myserv
#from ttypes import *
# Thrift files
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
# Server implementation
class MyHandler:
# return server message
def sendMessage(self, text):
print text
return 'In the garage!!!'
# set handler to our implementation
handler = MyHandler()
processor = myserv.Processor(handler)
transport = TSocket.TServerSocket(port)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
# set server
server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
print 'Starting server'
server.serve() ##### LINE 38 GOES HERE ##########
A: I had this problem while running PythonServer.py ...
I changed this line
transport = TSocket.TServerSocket(9090)
to
transport = TSocket.TServerSocket('9090')
and my server started running.
A: Your problem is the line:
transport = TSocket.TServerSocket(port)
When calling TSocket.TServerSocket which a single argument, the value is treated as a host identifier, hence the error with getaddrinfo().
To fix that, change the line to:
transport = TSocket.TServerSocket(port=port)
A: I had a similar problem. My fix is
TSocket.TServerSocket('your server ip',port)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: selecting a value from mysql table with 1 query table: config
+--------+---------+
| c_name | c_value |
+--------+---------+
| a | 1 |
| b | 2 |
| c | 1 |
+--------+---------+
i have two sql queries:
$first = mysql_fetch_array(mysql_query("SELECT c_value FROM config WHERE c_name = 'a' "));
$second = mysql_fetch_array(mysql_query("SELECT c_value FROM config WHERE c_name = 'b' "));
i have these codes:
echo $first["c_value"]; // output will be 1
echo $second["c_value"]; // output will be 2
Can i do same job with 1 sql query?
A: SELECT c_value
FROM config
WHERE c_name IN ('a', 'b')
A: $result=mysql_query("SELECT c_value FROM config WHERE c_name = 'a' OR c_name='b' ");
while($row = mysql_fetch_array($result)){
echo $row['c_value'];
}
A: SELECT c_name, c_value
FROM config
WHERE c_name IN('a', 'b');
while($row = mysql_fetch_assoc($result)){
echo $row['c_name'] . " = " . $row['c_value'] . "<br/>";
}
Output:
a = 1
b = 2
A: And use mysql_fetch_assoc if you want associative array as a result.
A: First Option:
$result=mysql_query("SELECT c_value FROM config WHERE c_name in ('a','b') ");
while($row = mysql_fetch_array($result)){
echo $row['c_value'];
}
OutPUt
1
2
You can also use this(Without using loop):
$O_Value = mysql_fetch_array(mysql_query("SELECT A.c_value as first_Value, B.c_value as second_Value FROM config A join config B on B.c_name = 'b' and A.c_name = 'a' "));
echo $O_Value["first_Value"]; // *output will be 1*
echo $O_Value["second_Value"]; // *output will be 2*
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Delegate in singleton won't work I have a singleton that downloads data from an exterior database (PTDatabaseAccsesser).
When all data has been downloaded the singleton should call on a delegate which is a subclass of UITableViewController. However, i get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFType doneDownloadingData]: unrecognized selector sent to instance...
This is how I set the delegate to the subclass of UITableViewController:
- (void)viewDidLoad {
[[PTDatabaseAccesser sharedInstance] setDelegate:self];
NSLog(@"%@", [[PTDatabaseAccesser sharedInstance] delegate]);
}
The NSLog shows that everything is correct here.
This is the code from the PTDatabaseAccsesser that calls on the delegate:
NSLog(@"%@", [self delegate]);
[[self delegate] doneDownloadingData];
The NSLog here however is showing that the delegate is of the same type as in the error message above.
This is how I create the singleton:
static PTDatabaseAccesser *sharedInstance;
+ (PTDatabaseAccesser *)sharedInstance {
@synchronized(self) {
if (!sharedInstance) sharedInstance = [[PTDatabaseAccesser alloc] init];
}
return sharedInstance;
}
+ (id)alloc {
@synchronized(self) {
sharedInstance = [super alloc];
}
return sharedInstance;
}
I have made sure that the singleton works by using breakpoints in the two method implementations above.
A: The code in the +alloc seems unnecessary and is probably the source of the error. From what I can see, sharedInstance gets its initial value in +alloc, which means that your if-condition in -sharedInstance is probably never executed and you are calling a method on an uninitialized object. Try this code instead, which also happens to be more efficient.
static PTDatabaseAccesser *sharedInstance;
+ (void) initialize
{
sharedInstance = [[PTDatabaseAccesser alloc] init];
}
+ (PTDatabaseAccesser *)sharedInstance
{
return sharedInstance;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Any Drupal Modules to help with price caculator? Ive made a booking form using Drupal 6, where bookings are a content type and you create a node of that type to make a booking.
I now need to add a price calculator. When creating a booking node, one of the CCK fields you fill in is distance. I then need the price to be calculated from the rates below, and that value to be given to another CCK field.
Rates:
0-5 km $20/ mile
5-10 km $15/ mile
10-20 km $10/ mile
20-30 km $5/ mile
So if the distance was 11km, the price would be 11 x 15 = 165. Also, the rates table needs to be editable by the site admin.
Can any Drupal modules do or at least help with this? I could probably manage to do the calculations and change the price field value with jQuery. If the table was shown on the page then jQuery could grab the values from it, and the table could be editable by the admin so the rates could be changed. Im far from a jQuery expert though....
Thanks
UPDATE - Ive asked the question in the Drupal Answers site, but im not able to move or delete this post.
https://drupal.stackexchange.com/questions/11758/any-modules-to-help-with-price-caculator
A: You may want to check out the Computer Field module.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Speed of Static Function Access Is it correct to assume that calling a static method is fast compared to the allocating and garbage collecting an integer?
Or, in other words would either fh1 or fh2 be preferable? In fh1 allocation is avoided but fh2 seems simpler. In this case the G.f() is a relatively simple method which will be called often. fh2 and fh1 will also be called often (potentially as many as 30 times per second).
Pseudo Code:
class G {
static method int f() {.......}
}
class H {
method fh1(){
somemethod1(G.f());
somemethod2(G.f());
somemethod3(G.f());
}
method fh2(){
int a = G.f();
somemethod1(a);
somemethod2(b);
.....
}
}
A: The reason I would use a static method in this particular situation is if the int value had the potential to change. In other words, if G.f() is performing some logic and the 1st invocation might be different from the 10th invocation, sure, use a static method. Static methods such as this provide a way to reduce code by reusing logic and keeping logic in a manageable state so if your logic needs to be changed, you only have to change it in one place.
That being said, in method fh1, what would be the potential for varying results if G.f() would change in the span of time it takes to call G.f() three separate times in fh1()? Probably very small, but still worth considering.
I would probably opt for fh2() for consistency. The performance difference is likely negligible.
A: 30 times per second is not often (1 million times per second is often). Hence there is no problem here, so don't optimize it.
Having said that, fh2 will be more efficient, allocation is cheaper than function calls.
A: You are not "allocating" nor "garbage collecting" an integer in your example.
Rather, in fh2, a lives on the stack and it does not need additional time to allocate/deallocate it.
How long a method call takes to completion depends entirelsy on the method's code. The call alone is fast, yet still slower than nothing. Therefore, I'd use the fh2 version.
A:
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified
© Donald Knuth
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to read values from a DB and use them with the SMTP connector in Mule 3 I would like to read some email details from the DB, and here's what my connector looks like:
<jdbc:connector name="dbConnector" dataSource-ref="dataSource">
<jdbc:query key="sqlQuery"
value="SELECT from, to, subject, body FROM email WHERE status='PENDING'" />
<jdbc:query key="sqlQuery.ack"
value="UPDATE email SET status='IN PROGRESS' WHERE id=#[map-payload:id]" />
</jdbc:connector>
I would then like to use those details to send a bunch of mails. I expect that the inbound-endpoint will be the JDBC Connector and the outbound-endpoint will be SMTP Connector, but I don't know how to store and use data I read from that table. Is there a way to do this without resorting to Java code?
A: Using transformers should be enough to achieve your goal: the inbound JDBC endpoint will give you a Map payload. From this payload you will extract the properties required by the outbound SMTP endpoint and the body of the message:
<!-- Set SMTP endpoint properties -->
<message-properties-transformer>
<add-message-property key="subject" value="#[map-payload:subject]"/>
...
</message-properties-transformer>
<!-- Set the message Body as new payload -->
<expression-transformer>
<return-argument evaluator="map-payload" expression="body"/>
</expression-transformer>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Network Connection Issue + Blackberry I am facing a network connection issue. My client has sent me following mail and I am having no idea what I should do in this condition
"One of our companies have asked if it would be possible for them to use their apps with the data going via a proxy. The hve disabled WAP on their BES so they are unable to use the application. I think in this instance the data needs to be routed through the BIS."
For using BIS , I have read that application needs to be approved by RIM and we need to append a secret String provided by the RIM to the connection URL.
For BES we append ;deviceside=false in case of simulator.
For TCP we append ;deviceside=true to the connection URL.
For Wifiwe append ;interface=wifi to the connection URL.
What should we append in the case of BIS?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: example command line and dataset for https://cwiki.apache.org/MAHOUT/itembased-collaborative-filtering.html after reading https://cwiki.apache.org/MAHOUT/itembased-collaborative-filtering.html I've identified this is EXACTLY what I would like to do... however.. I don't actually have any examples to confirm this.
Can a kind sole out there please just give me a linux cmd line (preferably with a 5 line data example) of how I can run mahout with this dataset ? It's installed exactly as per the install instructions, ie via svn and maven.
A: The command line options are spelled out right there -- what are you looking for?
Maybe you want to read up on how you run a Hadoop job on the command line, which would be the rest of the command line you want.
This is also covered in detail in Mahout in Action.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I map a tree by depth in a functional manner without recursion? Given a tree, how can I get a depth -> nodes map?
I’ve come this far in JavaScript but I’m not sure how to make the outer loop functional. I could probably do it using recursive inject but I’d rather avoid recursion.
function treeToLayers(root) {
var layers = [[root]];
var nextLayer = root.children;
while (nextLayer.length > 0) {
layers.push(nextLayer);
var lastLayer = nextLayer;
nextLayer = _(lastLayer).chain().
pluck('children').
flatten().
value();
}
return layers;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are scheduled UILocalNotifications part of iOS device backup? I mean, our app schedules a couple of local notifications. User makes a backup of the system and restores it on a new device. Will previously scheduled local notifications fire on the new system, or do we need to reschedule them again on the new system?
A: Finally I forced myself to do the test. The result:
YES - scheduled local notifications are part of backup, this means they are restored and scheduled on the new device. The restore overwrites any previously scheduled local notifications for the same app on the target device. Even icon badge number is preserved in backup and restored to the new device - showed on the icon.
A: I think that can be restore/copy to new device, or maybe you have to use new device to test this workflow ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Listbox item that stretches to width of listbox BUT not past the width I have a listbox that I want to take up the width of my window, and the list box items will stretch to the size of the listbox.
Each listbox item will be a datatemplate that has about 150 width for information and the remaining size to be a textbox for a description. I want the description texbox to stretch to remaining available size. So here is example xaml that I thought would create this layout:
<Window x:Class="test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox Margin="20,20,20,20" ItemsSource="{Binding Path=List}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="AliceBlue"
BorderThickness="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Width="20"
Content="Test" />
<ComboBox Width="130" />
<TextBox Grid.Column="1"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
However, when I type in the textbox and the text width goes past the width of the listbox, the listbox item keeps growing and the horizontal scroll bar shows up.
What I want to achieve is the max width of the textbox to go just up to the listbox and not grow wider. Anyone know how I can achieve this layout?
A: The problem is that your Listbox contains a scrollviewer, which means that its children can have any size they want, the scroll viewer will take care of that. Your ColumnDefinition practically says "Use all the unlimited space we have".
One solution that comes to my mind would be to bind the Grids Width to the ListBox ActualWidth
Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=ActualWidth}"
but propably better is Dmitrys solution.
A: Try adding ScrollViewer.HorizontalScrollBarVisibility="Disabled" to ListBox, it worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Simple Java String cache with expiration possibility I am looking for a concurrent Set with expiration functionality for a Java 1.5 application. It would be used as a simple way to store / cache names (i.e. String values) that expire after a certain time.
The problem I'm trying to solve is that two threads should not be able to use the same name value within a certain time (so this is sort of a blacklist ensuring the same "name", which is something like a message reference, can't be reused by another thread until a certain time period has passed). I do not control name generation myself, so there's nothing I can do about the actual names / strings to enforce uniqueness, it should rather be seen as a throttling / limiting mechanism to prevent the same name to be used more than once per second.
Example:
Thread #1 does cache.add("unique_string, 1) which stores the name "unique_string" for 1 second.
If any thread is looking for "unique_string" by doing e.g. cache.get("unique_string") within 1 second it will get a positive response (item exists), but after that the item should be expired and removed from the set.
The container would at times handle 50-100 inserts / reads per second.
I have really been looking around at different solutions but am not finding anything that I feel really suites my needs. It feels like an easy problem, but all solutions I find are way too complex or overkill.
A simple idea would be to have a ConcurrentHashMap object with key set to "name" and value to the expiration time then a thread running every second and removing all elements whose value (expiration time) has passed, but I'm not sure how efficient that would be? Is there not a simpler solution I'm missing?
A: Google's Guava library contains exactly such cache: CacheBuilder.
A: How about creating a Map where the item expires using a thread executor
//Declare your Map and executor service
final Map<String, ScheduledFuture<String>> cacheNames = new HashMap<String, ScheduledFuture<String>>();
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
You can then have a method that adds the cache name to your collection which will remove it after it has expired, in this example its one second. I know it seems like quite a bit of code but it can be quite an elegant solution in just a couple of methods.
ScheduledFuture<String> task = executorService.schedule(new Callable<String>() {
@Override
public String call() {
cacheNames.remove("unique_string");
return "unique_string";
}
}, 1, TimeUnit.SECONDS);
cacheNames.put("unique_string", task);
A: A simple unique string pattern which doesn't repeat
private static final AtomicLong COUNTER = new AtomicLong(System.currentTimeMillis()*1000);
public static String generateId() {
return Long.toString(COUNTER.getAndIncrement(), 36);
}
This won't repeat even if you restart your application.
Note: It will repeat after:
*
*you restart and you have been generating over one million ids per second.
*after 293 years. If this is not long enough you can reduce the 1000 to 100 and get 2930 years.
A: It depends - If you need strict condition of time, or soft (like 1 sec +/- 20ms).
Also if you need discrete cache invalidation or 'by-call'.
For strict conditions I would suggest to add a distinct thread which will invalidate cache each 20milliseconds.
Also you can have inside the stored key timestamp and check if it's expired or not.
A: Why not store the time for which the key is blacklisted in the map (as Konoplianko hinted)?
Something like this:
private final Map<String, Long> _blacklist = new LinkedHashMap<String, Long>() {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Long> eldest) {
return size() > 1000;
}
};
public boolean isBlacklisted(String key, long timeoutMs) {
synchronized (_blacklist) {
long now = System.currentTimeMillis();
Long blacklistUntil = _blacklist.get(key);
if (blacklistUntil != null && blacklistUntil >= now) {
// still blacklisted
return true;
} else {
// not blacklisted, or blacklisting has expired
_blacklist.put(key, now + timeoutMs);
return false;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I display a PDF in ROR (Ruby)? I have looked around on the internet, but do not seem able to find how to display a PDF in rails (I can only find info on how to create one).
Does anyone know what code/gem I need to display one?
A: Basically you just need to write it in the html in your view. So this simple solution worked for me:
In the 'show.hmtl.erb'
<iframe src=<%= @certificate.certificate_pdf %> width="600" height="780" style="border: none;"> </iframe>
just putting the file location in embedded ruby as the source of the iframe tag worked for me after hours and hours of searching. 'certificate' is my model, and 'certificate_pdf' is my attachment file.
A: In your controller:
def pdf
pdf_filename = File.join(Rails.root, "tmp/my_document.pdf")
send_file(pdf_filename, :filename => "your_document.pdf", :type => "application/pdf")
end
In config/environment/production.rb:
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
or
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
The config modification is required because it enables the web server to send the file directly from the disk, which gives a nice performance boost.
Update
If you want to display it instead of downloading it, use the :disposition option of send_file:
send_file(pdf_filename, :filename => "your_document.pdf", :disposition => 'inline', :type => "application/pdf")
If you want to display it inline, this question will be much more complete that I could ever be.
A: Depending where the PDF comes from, the following may help you. I have an application where I store a lot of things, and some of them have (additional) PDFs connected to the items. I store the items in the directory /public/res/<item_id>/. res means result, and item_id is the numeric id of that item in Rails.
In the view, I provide a link to the PDFs by the following (pseudo-)code as a helper method, that may be used in the view:
def file_link(key, name = nil)
res= Ressource.find(:first, :conditions => ["key = ?", key])
list = Dir["public/res/#{res.id}/*"]
file= list.empty? ? "" : list[0]
return file if file.empty?
fn = name ? name : File.basename(file)
link_to fn, "/res/#{res.id}/#{File.basename(file)}", :popup => true
end
The relevant part here is the link_to name, "/res/#{res.id}/#{File.basename(file)}" thing.
A: This may be too simple, but I had trouble finding a simple answer to my problem, so I'm posting it here. I really didn't want to add another action to my controller just to download a static file.
I just uploaded my file to S3 & used link_to referring to the path, which S3 provides after you upload the file and set the permissions (remember, everyone has to be able to upload and download it). I store lots of data for the app on S3 so it seemed like a fine choice.
<%= link_to "speaker registration form", "https://s3.amazonaws.com/gws_documents/speaker_registration.pdf" %>
A: def pdf
pdf_content = ...# create the pdf
send_data(pdf_content, :filename => "test.pdf", :type => "application/pdf")
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
} |
Q: VMTRACER and Memory i try to delete Dirty Memory and u se VMTRACE but i dont know why this code have dirty memory
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Info.plist"];
NSDictionary *dict =[[[NSDictionary alloc] initWithContentsOfFile:path] autorelease];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: My Custom Authorize Attribute always fire, even without setting in global.asax and Attributes in Controllers/Actions I Have a Custom Authorize Attribute that always fire. I remove the configuration in global.asax and have no attributes in controllers/actions. Why?
public class ValidatePermissionAttribute : AuthorizeAttribute
{
private AuthorizationContext _context;
public override void OnAuthorization(AuthorizationContext context)
{
_context = context;
base.OnAuthorization(context);
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isAuthorized = false;
//Use _context here
...
return isAuthorized;
}
}
My Global.asax:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new LogActionAttribute());
//ValidatePermissionFilterProvider validatePermissionProvider = new ValidatePermissionFilterProvider();
//validatePermissionProvider.Add("Login", "Index");
//validatePermissionProvider.Add("Erro", "*");
//FilterProviders.Providers.Add(validatePermissionProvider);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Usuario", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
DefaultModelBinder.ResourceClassKey = "ViewModelValidations";
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer(new DatabaseInitializer());
}
protected override IKernel CreateKernel()
{
return DependencyResolverFactory.Instance.Kernel;
}
}
Discover the problem:
With answer of @DarinDimitrov I discover the problem, I'm using Ninject to inject a dependcy in my Filter, this is causing to fire in every Controller:
public class ApplicationServicesModule : NinjectModule
{
public override void Load()
{
this.BindFilter<ValidatePermissionAttribute>(FilterScope.First, null);
}
}
A: Only a custom attribute doesn't do anything. There must be some code that is registering it. It could be either registered as global action filter, you could have a controller/action decorated with it or you might have your dependency injection framework which registers it as a global action filter. Right click on the ValidatePermissionAttribute and search where this class is being used. Normally VS will show you where you have registered it.
A: If your controllers derive from a custom controller base class, you might want to check that to see if the attribute is present there also. You can also try to do a solution-wide Find Usages on the attribute name ValidatePermissionAttribute to see if there's somewhere you missed it.
EDIT: looking at your global.asax, I see that you are registering LogActionAttribute -- is it possible that attribute derives from your other custom authorization attribute? I would try removing all custom registrations and filters to see if the problem persists
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Zend Ajax post to action I have a select dropdown with options:
<select id="select_privilege_section" name="select_privilege_section" onchange="">
<option value="pages">Pages</option>
<option value="forms">Forms</option>
<option value="roles">Roles</option>
<option value="cos">Change of Status</option>
</select>
I need to be able to send via ajax the option selected on change, to a specific action in a controller to be retrieved there in order to select which form related to the option it has to be displayed:
var input = $(this).val();
$.ajax ({
type: "POST",
url: location.protocol + '//' + location.host + '/role/privilege/format/html',
data: {"form": input},
success: function(data) {
console.log("Success!!");
}
});
But I am not being able to get the $_POST['form']; there
Any idea why?
thank you in advance!
A: The url you are posting to is wrong if I'm not mistaken. Try debugging it and check it is a valid url.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Physics Library for VB.Net? Hi is there any library which can interact with vb.net. I searched a little bit but I just found libraries for c#. I know it's not suitable to use vb.net for making these stuffs but I wanted to know.
Thanks.
A: A .NET library can be used by any .NET language, so long as it is CLS compliant.
I expect a physics library to be CLS compliant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gson\json deserialization error I want to parse a JSON object using GSON. Everything seems to work fine but when I'm trying to parse a more "complexed" object I'm getting a deserialization error. The object I'm trying to parse contains some primitives, a stack and a vector collection.
Is it possible that the stack\vector causing this problem? can I somehow over come this?
The Error:
Exception in thread "AWT-EventQueue-0" com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@4e76fba0 failed to deserialize json object [{"name_":"Human","points_":1,"alive_":true,"id_":0,"cssStyleClass":"pressed_p1"},{"name_":"Human","points_":0,"alive_":true,"id_":1,"cssStyleClass":"pressed_p2"}] given the type java.util.Vector<entities.Player>
at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDeserializerExceptionWrapper.java:64)
at com.google.gson.JsonDeserializationVisitor.invokeCustomDeserializer(JsonDeserializationVisitor.java:92)
at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler(JsonObjectDeserializationVisitor.java:117)
at com.google.gson.ReflectingFieldNavigator.visitFieldsReflectively(ReflectingFieldNavigator.java:63)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:120)
at com.google.gson.JsonDeserializationContextDefault.fromJsonObject(JsonDeserializationContextDefault.java:76)
at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializationContextDefault.java:54)
Request Code
Gson json = new Gson();
Multiplayer result = json.fromJson(answer.toString(), Multiplayer.class);
Code On Servlet
Gson gson = new Gson();
Multiplayer game = (Multiplayer)getServletContext().getAttribute("OnlineGame");
String responseStr = gson.toJson(game);
response.setContentType("application/json;charset=UTF-8");
out.write(responseStr);
String from toString()
{serializeNulls:false,serializers:{mapForTypeHierarchy:{Map:MapTypeAdapter,Collection:com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@596e1fb1,InetAddress:com.google.gson.DefaultTypeAdapters$DefaultInetAddressAdapter@4ce2cb55,Enum:EnumTypeAdapter},map:{Integer:IntegerTypeAdapter,URI:UriTypeAdapter,UUID:UuidTypeAdapter,BigInteger:BigIntegerTypeAdapter,URL:UrlTypeAdapter,Short:ShortTypeAdapter,Time:com.google.gson.DefaultTypeAdapters$DefaultTimeTypeAdapter@16bdb503,byte:ByteTypeAdapter,short:ShortTypeAdapter,Number:NumberTypeAdapter,double:com.google.gson.DefaultTypeAdapters$DoubleSerializer@b6e39f,GregorianCalendar:GregorianCalendarTypeAdapter,Calendar:GregorianCalendarTypeAdapter,Byte:ByteTypeAdapter,StringBuilder:StringBuilderTypeAdapter,Float:com.google.gson.DefaultTypeAdapters$FloatSerializer@6719dc16,Locale:LocaleTypeAdapter,StringBuffer:StringBufferTypeAdapter,Date:DefaultDateTypeAdapter(SimpleDateFormat),Character:CharacterTypeAdapter,float:com.google.gson.DefaultTypeAdapters$FloatSerializer@6719dc16,BigDecimal:BigDecimalTypeAdapter,Boolean:BooleanTypeAdapter,boolean:BooleanTypeAdapter,String:StringTypeAdapter,Timestamp:DefaultDateTypeAdapter(SimpleDateFormat),int:IntegerTypeAdapter,long:LongSerializer,Date:com.google.gson.DefaultTypeAdapters$DefaultJavaSqlDateTypeAdapter@52c05d3b,char:CharacterTypeAdapter,Double:com.google.gson.DefaultTypeAdapters$DoubleSerializer@b6e39f,Long:LongSerializer},deserializers:{mapForTypeHierarchy:{Map:MapTypeAdapter,Collection:com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@596e1fb1,InetAddress:com.google.gson.DefaultTypeAdapters$DefaultInetAddressAdapter@4ce2cb55,Enum:EnumTypeAdapter},map:{Integer:IntegerTypeAdapter,URI:UriTypeAdapter,UUID:UuidTypeAdapter,BigInteger:BigIntegerTypeAdapter,URL:UrlTypeAdapter,Short:ShortTypeAdapter,byte:ByteTypeAdapter,Time:com.google.gson.DefaultTypeAdapters$DefaultTimeTypeAdapter@16bdb503,short:ShortTypeAdapter,Number:NumberTypeAdapter,double:DoubleDeserializer,Byte:ByteTypeAdapter,Calendar:GregorianCalendarTypeAdapter,GregorianCalendar:GregorianCalendarTypeAdapter,StringBuilder:StringBuilderTypeAdapter,Float:FloatDeserializer,Locale:LocaleTypeAdapter,StringBuffer:StringBufferTypeAdapter,Date:DefaultDateTypeAdapter(SimpleDateFormat),Character:CharacterTypeAdapter,float:FloatDeserializer,BigDecimal:BigDecimalTypeAdapter,Boolean:BooleanTypeAdapter,boolean:BooleanTypeAdapter,String:StringTypeAdapter,Timestamp:com.google.gson.DefaultTypeAdapters$DefaultTimestampDeserializer@5328f6ee,int:IntegerTypeAdapter,long:LongDeserializer,Date:com.google.gson.DefaultTypeAdapters$DefaultJavaSqlDateTypeAdapter@52c05d3b,char:CharacterTypeAdapter,Double:DoubleDeserializer,Long:LongDeserializer},instanceCreators:{mapForTypeHierarchy:{SortedSet:DefaultConstructorCreator,Set:DefaultConstructorCreator,Queue:DefaultConstructorCreator,Collection:DefaultConstructorCreator,Map:DefaultConstructorCreator},map:{}}
A: I recommend you to use an array Player[] instead of the generic collection Vector<Player>. It's not easy to use Java generics for serializing and deserializing. If you use an array instead, you will have no problem with it.
But it had been easier to answer if you show your code for Multiplayer and Player.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: LINQ select (using entity framework) Having the following tables:
*
*Messages
*
*MessageThread
*
*MessageThreadParticipant
*
*MessageReadState
I need to get the following using LINQ (I'm using EF4 so these have knowledge of each other).
1) Get a list of TOP 1 message (from a thread), also marking if this is a new message for a given LoginId
so for example (loginId 118)
Should display a list of only 1 item with a messageID: 368 (because I participate in that conversation). Also, I need to know that this is a NEW message for LoginId 118 because MessageReadState doesn't not have an entry for me.
example2: (Login 116)
should list 4 threads because I participate in threadId's (24, 25, 26,27). With a newest message from each thread.
EDIT:
EF (if anyone using the same structure)
thanks
A: A question about LINQ (to Entities) is difficult to answer if you don't show your entities with their navigation properties. But assuming classes and navigation properties have everything you need to perform such a query I would try this:
var result = context.MessageThreadParticipants
.Where(mtp => mtp.LoginId == givenLoginId)
.Select(mtp => new
{
MessageThread = mtp.MessageThread,
NewestMessage = mtp.MessageThread.Messages
.OrderByDescending(m => m.CreateDate)
.Select(m => new
{
Message = m,
HasBeenRead = m.MessageReadStates
.Any(mrs => mrs.LoginId == givenLoginId)
})
.FirstOrDefault(),
})
.ToList();
So, entity MessageThreadParticipant must have a MessageThread property. Entity MessageThread must have a Messages collection and entity Message must have a MessageReadStates collection.
result is then a collection of anonymous objects. Every object contains:
*
*MessageThread : the thread the user with givenLoginId participates in
*NewestMessage.Message : the newest message in this thread
*NewestMessage.HasBeenRead : a boolean flag if the newest message has been read
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Ruby - mathematics operations I tried a few minutes ago simple math operation
<%=((3+2+1)/100).round(8)%>
The result is 0.06, but the result of the ruby code above is 0.0. I would expect the result should be 0.060000.
Why not?
Thanks
A: (3+2+1)/100
is 0 because the division is integer. Try
(3+2+1)/100.0
You see, if both arguments of / are integer, the result of the division is an integer (the whole part). If at least one of the arguments is floating-point, then the result is also floating-point.
A: The dreadful integer arithmetic attacks again!
When you calculate ((3+2+1)/100), since all the operands are integers, Ruby uses integer arithmetic rather than floating point arithmetic.
If you do 7/100 it will also return 0, as it's rounded down to the nearest integer, which is 0.
A: Operations involving only integer data are done in integer (and then 6/100 is 0). Converting that 0 to float later (by round) does not bring you back the already discarded fractional part.
Change either of the values to float (e.g. 3.0) and you are done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Use UTF-8 in .NET windows application
Possible Duplicate:
Unicode characters not showing in System.Windows.Forms.TextBox
I'm trying to render international languages within a textbox inside my .net windows application but it's not showing the characters properly.
I can't seem to find the setting to change the character encoding to UTF-8, can someone point me in the right direction? Thanks :)
A: System.String in .NET is already Unicode (UTF-16) encoded. MSDN states: "A string is a sequential collection of Unicode characters that is used to represent text."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Preventing user from uncheking a checkbox I have 3 checkboxes in my winforms program. I managed to make it somehow that only one of them can be selected by user. That is if user clicks one of the unchecked buttons, ofcourse that button will be checked and also the check will be removed from last checked button!
Now I want to do it somehow that user can not uncheck the checkboxes, so the only way to checkk a box will be clicking on it. is this possible? is there any property for this?
Sorry for using too much check & box :P
A: In the checkedchanged event of the checkbox write the following code.
if (!checkBox1.Checked)
{
checkBox1.Checked = true;
}
A: If you want a radio button functionality but a different look, change the appearance of a radio button.
From http://msdn.microsoft.com/en-us/library/system.windows.forms.radiobutton(v=vs.80).asp
private void InitializeMyRadioButton()
{
// Create and initialize a new RadioButton.
RadioButton radioButton1 = new RadioButton();
// Make the radio button control appear as a toggle button.
radioButton1.Appearance = Appearance.Button;
// Turn off the update of the display on the click of the control.
radioButton1.AutoCheck = false;
// Add the radio button to the form.
Controls.Add(radioButton1);
}
A: Just listen for change events and if the event tells you the checkbox has been unchecked, recheck it.
But I agree with others, this behavior is the one of RadioButtons, so use a radio button instead. You don't want to suit your personal feeling but to provide a unified user experience to the end user. That's part of the guidelines of Microsoft (and every other framework).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Remove a text link from page by JavaScript I have in my html page: <a href="link">some text</a>
How can I do it in JavaScript to find the value of A tag as "some text" and remove all the a tag and the a value ?
I want to remove <a href="link">some text</a> only if there is a value = some text
thanks!
A: Vanilla JavaScript
function removeAllByTextContent(tag, search) {
var anchors = document.getElementsByTagName(tag);
for (var i=anchors.length-1; i>=0; i--) {
var a = anchors[i],
text = a.textContent || a.innerText;
if (text == search) a.parentNode.removeChild(a);
}
}
call as:
removeAllByTextContent("a", "some text");
A: You can do this
var a = document.getElementsByTagName('a');
for(var i = 0; i < a.length; i++){
if(a[i].innerText == 'some text' || a[i].textContent == 'some text'){
a[i].parentNode.removeChild(a[i]);
}
}
Example: http://jsfiddle.net/jasongennaro/U8cZZ/1/
A: You can use the text() css selector with a framework like mootools: http://jsfiddle.net/9YPYc/
A: if you use jquery:
$('a').each(function(){if($(this).text()=="some text")$(this).remove()});
A: As you are eager to use jQuery (as said in the comment) then load jQuery file first
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
And type following code withing your script tag
$(function(){
$('a').filter(function(){
if($(this).html()=='some text') return true;
}).remove();
})
See a working a demo here http://jsfiddle.net/MbJVf/1/
A: With jQuery:
$('a[href=link]').remove();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add image view to sub class in Android? In my sub class I am trying to add an image View:
ImageView image = new ImageView(this);
But it breaks the app. I think it is because of the 'this' param.
Does my class need to extend something? At the minute it extends Activity.
A: You can do that but you need to provide this.ApplicationContext instead of this. Alternatively you could derive a View instead of an Activity and use constructor's Context argument for the ImageView constructor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why do I get a NullPointerException in ChartUtilities.writeChartAsPNG? I am trying to get a bar chart using JFreeChart.
final DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
dataSet.setValue(1.0, "OS", "Ubuntu");
dataSet.setValue(2.0, "OS", "Linux");
dataSet.setValue(1.0, "OS", "Windows");
JFreeChart jFreeChartObj = CreateBarChart.createBarChart(chartDetails);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(response.getOutputStream(), jFreeChartObj, 500, 500);
I got an error like this:
java.lang.NullPointerException
at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2291)
at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1041)
at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1224)
at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1204)
at org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:174)
at org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:120)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I prevent suds from fetching xml.xsd over the network? I'm using Python's suds library which tries to fetch xml.xsd over the network. Unfortunately, the w3c server is hammered due to other programs like mine and cannot usually serve the document.
How do I intercept suds' URL fetching to always grab a local copy of this file, even without having to download it into a long-lived cache successfully the first time?
A: The problem with fetching xml.xsd has to do with the "http://www.w3.org/XML/1998/namespace" namespace, which is required for most WSDLs. This namespace is mapped by default to http://www.w3.org/2001/xml.xsd.
You may override the location binding for this namespace to point to a local file:
from suds.xsd.sxbasic import Import
file_url = 'file://<path to xml.xsd>'
Import.bind('http://www.w3.org/XML/1998/namespace', file_url)
A: The suds library has a class suds.store.DocumentStore that holds bundled XML in a uri -> text dictionary. It can be patched like so:
suds.store.DocumentStore.store['www.w3.org/2001/xml.xsd'] = \
file('xml.xsd', 'r').read()
Unfortunately this doesn't work because DocumentStore only honors requests for the suds:// protocol. One monkey patch later and you're in business.
It would also be possible to override the Cache() instance passed to your suds Client(), but the cache deals with numeric ids based on Python's hash() and does not get the URLs of its contents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: doctrine mongodb odm query group by i have 3 collections and i want to perform query which is similar to sql query like
SELECT fp.userId, fp.orderId, productId, fp.request_Payment_ChargeTotal,
fp.createdOn, u.referrerSite, COUNT(*),
sum( fp.request_Payment_ChargeTotal ) AS total
FROM `firstdata_payment_webservice` fp, userlicenses ul, users u
WHERE u.userId = ul.userId
AND fp.response_TransactionResult = 'APPROVED'
AND fp.request_Payment_ChargeTotal > 0
AND ul.orderId = fp.orderId AND fp.createdOn
BETWEEN cast( '2011-09-10' AS DATETIME )
AND cast( '2011-09-20' AS DATETIME )
GROUP BY u.referrerSite, productId WITH ROLLUP
How can i do similar operation in doctrine mongodb odm.
A: Well, applying "JOIN" is not the intent of MongoDB. So you have to structure your data differently.
db.users
*
*id
*name
*licences (stored as Hash type)
db.orders
*
*id
*created_on (Datetime type)
*processed_on (Datetime type)
*user_id (may be a DBRef or an ObjectId type)
*products (stored as an Array type, containing objects)
*transaction (stored as Hash type, with info like datetime, webservice type and other stuff)
With MapReduce, you can count other stuff by querying the orders table.
And if you need data on the customers, do it in another query, using an array of users ObjectIds you are looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bad idea to create a folder for every user? I am wondering if it would be a bad idea to create a folder for every user. So any images for each user would be accessed with img.mysite.com/UserId/image.jpg
A: Absolutely bad idea I will say from my experience
In recent past I was working on one application which was based on social networking
And It has around 15000+ users now.
Also I am managing that site currently.
Problems with this is you will find it cool at first to manage but later it will be a issue.
Always have to keep track of permissions.
Creation and deletion of folder with respect to your database to achieve synchronisation.
Also If you are on shared hosting, many hosting providers they don't show all the folders with any File Manager.Maximum number of folder that can be seen through File Managers is 2000 with customer care support you only get access to first 10000 folder.
Also Non-Ascii name for folder will as that of database will be another issue.
Which will be a great problem for you later.
I will suggest not to go with this way for sure.
A: This could grow to be a huge number of directories, so take caution as some filesystems limit the number of subdirectories in a single directory. It is common to break up generated content into multiple directories. You could do it by date, or break up some identifier (a hash, or the image's autoincremented ID number) to create a deeper directory structure. Example:
*
*avatars/000/ (images 1-999)
*avatars/001/ (images 1000-1999)
*avatars/002/ (images 2000-2999)
AKA the directory prefix is floor(ID / 1000).
There's probably a case for abstracting your URIs from your filesystem anyway, so it doesn't really matter where the files are stored on the backend, except to you as a programmer.
A: No, it's not the best idea.
If the only purpose of the separate folders is so that you can have 'friendly' URLs in the structure you suggest, then I recommend you search for URL Rewriting instead.
If you're trying to solve some other problem, post a comment and let us know.
A: No reason why it would be an issue from a performance reason. From an organizational perspective, it's cleaner than just throwing them all together into the same folder.
A: I think this would be better format:
http://img.mysite.com/userid_imageid.jpg
Then you can do database like this:
tables users and imgs
A: Use one folder on your ftp and make a good and solid database where all photos of the same person are linked together. Not so hard :)
A: For a smaller site, it's not a terrible idea, with one caveat:
You MUST abstract the file creation/deletion handling into one mechanism!
Make sure that all your code uses this mechanism, which should be able to store and retrieve and delete, and that's it. Then, in the future, if you want to change how you store your files, you can do it really easily.
P.S. When I say all your code, I really mean all your code. For instance, I'd have any GET that matches
^img.mysite.com/(\w+)/(\w+\.jpg)$
handled by a single method, which calls the mechanism I described above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problem loading images into UITableView cell with SDWebImage I'm using SDWebImage to load images into my table cells - however the images aren't appearing until I've selected the row, when I see the image appear just as the table is being animated off the screen. When I click back from my navigation controller the image is there.
Is this likely to be just a speed issue with the web or am I missing something? This is being run on the simulator only at the moment if that makes a difference
Code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier] autorelease];
}
// Configure the cell...
NSUInteger row = [indexPath row];
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://mydomain.com/uploads/news1.png"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
Thanks
A: Fixed, it was the placeholder image not being correct. Sorry for wasting people's time...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can`t get the jquery alerts to work on webpages in the web-inf folder I am trying to implement notifications on my web project its using a mvc design pattern with EJB and JPA. Also the header and footer are in a separate file for each. The problem is that when i try to use the alerts its not working. example code from the fornecedor jsp:
<script src="js2/js/jquery.js" type="text/javascript"></script>
<script src="js2/js/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="js2/js/jquery.alerts.js" type="text/javascript"></script>
<link href="js2/css/jquery.alerts.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript">
function gback(){
document.FM.action = "<c:url value='FModificar'/>";
document.FM.method = "get";
document.FM.submit();
}
$(document).ready(function(){
$("#FElim").click(function () {
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
jAlert('success', 'Confirmed: ' + r, 'Confirmation Results');
if (r) {
document.FEliminar.action = "<c:url value='FEL'/>";
document.FEliminar.method = "get";
document.FEliminar.submit();
} else {
return false;
}
});
});
});
</script>
the code of the script:
<%-- Eliminar Fornecedor is Requested --%>
<c:if test="${fn:contains(PagesInF,'FEliminar')}">
<table id="ProductTable" class="detailsTable">
<tr class="header">
<th colspan="8" >Products</th>
</tr>
<tr class="tableHeading">
<td>ID</td>
<td>Nome</td>
<td>Endereço</td>
<td>Descrição</td>
<td>Nº de Celulare</td>
<td>Nº de Telefone</td>
<td>Email</td>
<td>Fax</td>
<td></td>
</tr>
<c:forEach var="ELForn" items="${EFornecedorList}" varStatus="iter">
<tr class="${'white'} tableRow">
<td>${ELForn.getFid()}</td>
<td>${ELForn.getFNome()}</td>
<td>${ELForn.getFEndereco()}</td>
<td>${ELForn.getFDescricao()}</td>
<td>${ELForn.getFNCel()}</td>
<td>${ELForn.getFNTel()}</td>
<td>${ELForn.getFEmail()}</td>
<td>${ELForn.getFFax()}</td>
<td>
<form action="<c:url value='FEL'/>" method="post" name="FEliminar">
<input type="hidden"
name="MEId"
value="${ELForn.getFid()}">
<input id="FElim" type="button"
value="Eliminar">
</form>
</td>
</tr>
</c:forEach>
</table>
</c:if>
<%-- END Eliminar Fornecedor is Requested --%>
here is the header jsp page code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="Css/Style.css">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<script src="/AffableBean/js/jquery-1.6.4.js" type="text/javascript"></script>
<script src="/AffableBean/js/jquery-ui-1.8.4.custom.min.js" type="text/javascript"></script>
<script src="/AffableBean/js/jquery.corners.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.rounded').corners();
$('a.categoryButton').hover(
function () {$(this).animate({backgroundColor: '#b2d2d2'})},
function () {$(this).animate({backgroundColor: '#d3ede8'})}
);
$('div.ActionBox').hover(over, out);
function over() {
var span = this.getElementsByTagName('span');
$(span[0]).animate({opacity: 0.3});
$(span[1]).animate({color: 'white'});
}
function out() {
var span = this.getElementsByTagName('span');
$(span[0]).animate({opacity: 0.7});
$(span[1]).animate({color: '#444'});
}
});
</script>
<title>Rimpex Stock Application</title>
</head>
<body>
<div id="main">
<div id="header">
<a href="<c:url value='Home'/>">
<img src="/StockWebApp/img/Letter_R_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_I_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_M_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_P_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_E_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_X_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_L_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_T_blue_Icon_64.png" id="logo" alt="Rimpex logo">
<img src="/StockWebApp/img/Letter_D_blue_Icon_64.png" id="logo" alt="Rimpex logo">
</a>
<div class="clr"></div>
<div id="Menu">
<c:if test="${fn:contains(PagesIn,'Home')}">
<ul>
<li class="active"><a href="<c:url value='Home'/>"><span class="bigText">Home</span></a></li>
<li><a href="<c:url value='Utilizador'/>"><span class="bigText">Utilizador</span></a></li>
<li><a href="<c:url value='LogOff'/>" id="LOf"><span class="bigText">Log Off</span></a></li>
<li><a href="<c:url value='About'/>"><span class="bigText">About</span></a></li>
</ul>
</c:if>
<c:if test="${fn:contains(PagesIn,'Utilizador')}">
<ul>
<li><a href="<c:url value='Home'/>"><span class="bigText">Home</span></a></li>
<li class="active"><a href="<c:url value='Utilizador'/>"><span class="bigText">Utilizador</span></a></li>
<li><a href="<c:url value='LogOff'/>"><span class="bigText">Log Off</span></a></li>
<li><a href="<c:url value='About'/>"><span class="bigText">About</span></a></li>
</ul>
</c:if>
<c:if test="${fn:contains(PagesIn,'LogOff')}">
</c:if>
<c:if test="${fn:contains(PagesIn,'About')}">
<ul>
<li><a href="<c:url value='Home'/>"><span class="bigText">Home</span></a></li>
<li><a href="<c:url value='Utilizador'/>"><span class="bigText">Utilizador</span></a></li>
<li><a href="<c:url value='LogOff'/>"><span class="bigText">Log Off</span></a></li>
<li class="active"><a href="<c:url value='About'/>"><span class="bigText">About</span></a></li>
</ul>
</c:if>
<c:if test="${fn:contains(PagesIn,'Mar')}">
<ul>
<li><a href="<c:url value='Home'/>"><span class="bigText">Home</span></a></li>
<li><a href="<c:url value='About'/>"><span class="bigText">About</span></a></li>
</ul>
</c:if>
</div>
</div>
<div id="Top1">
<c:if test="${!empty Cart}">
<div id="widgetBar">
<%-- checkout widget --%>
<div class="headerWidget">
<a href="#" class="rounded bubble">Avança a Saida</a>
</div>
<%-- shopping cart widget --%>
<div class="headerWidget" id="viewCart">
<a href="#" class="rounded bubble">
<img src="/StockWebApp/img/cart.gif" alt="shopping cart icon" id="cart">
<span class="horizontalMargin">
${cart.getNumberOfItems()} Itens
</span></a>
</div>
</div>
</c:if>
</div>
<div id="Top"></div>
<div class="clr"></div>
the alerts only work on the index page. So if anyone has any ideas please feel free to share it.
A: Hi changing the path of the JavaScript files fixed my problem.
<script src="/AffableBean/js/jquery-1.6.4.js" type="text/javascript"></script>
to
<script src="/StockWebApp/js/jquery-1.6.4.js" type="text/javascript"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Preserve orphans, NHibernate one-to-many I'm successfully using a one-to-many relationship in NHibernate apart from one thing. When I remove a child record from the collection held in the parent, I don't want it to delete the child record. I just want it to blank out the foreign key in the child record.
This is so that I can reattach the child record to a different parent later on.
Is this possible? I have tried various cascade options but they all seem to delete the child when I call Remove() on the collection.
Here's my parent mapping (a 'SectionItem')
<class name="Munch.Domain.MenuSection, Munch.Dao" table="menu_section">
<id name="Id" type="Int32">
<generator class="native" />
</id>
<property name="Position" />
<property name="Title" />
<property name="Description" />
<bag name="MenuItems" cascade="save-update">
<key column="menuSectionId"/>
<one-to-many class="MenuItem"/>
</bag>
</class>
Child object (a 'MenuItem')
<class name="Munch.Domain.MenuItem, Munch.Dao" table="menu_item">
<id name="Id" type="Int32">
<generator class="native" />
</id>
<property name="Title" />
<property name="Description" />
<property name="Type" />
<property name="Image" />
</class>
And here is a test that builds up the child collection and saves the parent/children in one go. Then I remove one child (making a note of it's id before I do) and then I try to retrieve the 'removed' child to check that it is still in the database. I would expect it to be there, but with a null foreign key back to the parent.
// Create the menu section
MenuSection ms = new MenuSection();
ms.Title = "MenuSectionTitle";
ms.Description = "Description";
ms = menuSectionDao.Save(ms);
// Create a couple of menu items
MenuItem item1 = new MenuItem();
item1.Title = "AAA";
item1.Description = "AAA Desc";
MenuItem item2 = new MenuItem();
item2.Title = "BBB";
item2.Description = "BBB Desc";
List<MenuItem> items = new List<MenuItem>();
items.Add(item1);
items.Add(item2);
// Add the items to the menu section
ms.MenuItems = items;
// Save it and check
menuSectionDao.Save(ms);
Assert.IsNotNull(ms, "Menu Section wasn't saved");
Assert.True(ms.Id > 0, "Menu Section id is not greater than zero, probably an error");
log.Debug("MenuSection saved with id " + ms.Id);
// See what's been saved
MenuSection ms2 = menuSectionDao.Find(ms.Id);
Assert.IsNotNull(ms2, "Retrieved a null value");
// Check that the menu items were saved too
Assert.IsNotNull(ms2.MenuItems);
Assert.IsTrue(ms2.MenuItems.Count == 2);
Assert.AreEqual(ms2.MenuItems[0].Title, "AAA");
Assert.AreEqual(ms2.MenuItems[1].Title, "BBB");
// Try and remove the item
int item1Id = ms2.MenuItems[0].Id;
log.Debug("Deleting item 0 with id " + item1Id);
ms2.MenuItems.RemoveAt(0);
menuSectionDao.Save(ms2);
MenuSection ms3 = menuSectionDao.Find(ms.Id);
Assert.IsTrue(ms3.MenuItems.Count == 1);
// Check we haven't deleted the menu item
MenuItem item = menuItemDao.Find(item1Id);
Assert.IsNotNull(item);
}
(the test is failing on the last line by the way)
Thanks
A: The only cascade option that deletes entities that are removed from a collection is "all-delete-orphan". So it must be something in your code that deletes the entities.
Also, make sure to set the parent reference to null when you remove an entity from the collection. NHibernate won't do this for you.
A: I don't really understand why, but I got it working in the end so thanks to everyone who has helped me.
It turns out I didn't need to many-to-one in the child, and I didn't need inverse='true' for my particular case. All I needed to do was save the child individually (using it's own DAO) just before removing it from the parent's collection.
IEnumerator childEnumerator = ms2.MenuItems.GetEnumerator();
childEnumerator.MoveNext();
MenuItem mi = (MenuItem)childEnumerator.Current;
menuItemDao.Save(mi); // This is the line I needed
ms2.MenuItems.Remove(mi);
menuSectionDao.Save(ms2);
When I save my child (mi), as far as it's concerned, it's still related to the parent at that point. I'm sure it's got something to do with Flushing but if anyone can explain clearly why this was necessary please do!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Subtract fields in the same column to get interval I have a table "@table1" and I would like recursively update on the"Amount" column from the BOTTOM to the TOP ordering by RowID. That is taking the negative values subtracting that value with value of row above, if the end result is still a negative subtract that value with the next row, replacing the previous value with 0.
DECLARE @table1 TABLE (RowID int, Amount int);
INSERT @table1 VALUES
(1,20),
(2,10),
(3,-10),
(4,10),
(5,-5),
(6,30);
Select * from @table1
RowID Amount
----------- -----------
1 20
2 10
3 -10
4 10
5 -5
6 30
Results Table
DECLARE @table1 TABLE (RowID int, Amount int);
INSERT @table1 VALUES
(1,20),
(2,0),
(3,0),
(4,5),
(5,0),
(6,30);
Select * from @table1
RowID Amount
----------- -----------
1 20
2 0
3 0
4 5
5 0
6 30
A: The only way I can think of implementing this (as a single query) would be to use something like a running total . This effectively ends up joining the Product table on itself in such a way that for each row in the "left" table, the "right" table contains all records that "come before it". This way, you could keep a running total of your updated field. Unfortunately it's quite confusing to write and performs atrociously.
Depending on your intended usage scenarios, this might be one of those rare cases where cursors are the better alternative. Writing one using cursors and table variables should be relatively trivial.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to show dialog to send email AND call phone number in Android? I am wondering if there is a way to have a "contact" button in Android and when the button is pressed a menu pops up giving you the possibility:
*
*to send an email (showing all available email accounts, send-to is a predefined email address
*or to call a predefined phone number
This should everything be in the same menu, so similar to this but also with the option to place a call:
http://mobile.tutsplus.com/tutorials/android/android-email-intent/ (sorry, as a new user I cannot post images yet...)
Is there a pre-defined function to do this or do I have to code the whole menu from scratch?
Thanks for your help,
Reto
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to reset a SOLR db? I need to reset my seacrh DB (still experimenting and do not want it to return trash).
Is it enough to simply remove all files from under the data/spellchecker and data/index directories?
A: Its simple as removal of the data folder.
you can also use -
http://host:port/solr/core/update?stream.body=<delete><query>*:*</query></delete>
However, this would clean up the complete index with no backup.
So you may want to back it up before.
A: You can post a delete query:
<delete><query>*:*</query></delete>
A: To be precise, when using data import handler you should delete always dataimport.properties from "conf" directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WiX/MSI - Custom Action - Upgrade Logic I have some sort of requirement that states that we have to set up scheduler tasks in the install phase and then, naturally, remove them in the uninstall phase.
However this scenario gets complicated when we introduce our upgrade mechanism (we just have major upgrades), where we have to preserve these scheduler tasks.
Because of the way we decided to use upgrade logic:
<RemoveExistingProducts After='InstallFinalize'/>
Our new version gets first install and then the previous versions gets uninstall, therefore unschedule action gets executed and erase scheduler tasks with this:
<Custom Action='CA_unscheduleUpdates' Before="InstallFinalize">
<![CDATA[Installed]]>
</Custom>
Is there any way to control this scenario in case we're upgrading and just don't fire the unschedule custom action? Maybe do I have something that I can control within my Custom Action C++ code?
A: You can condition the custom action execution with "Not UPGRADINGPRODUCTCODE".
http://msdn.microsoft.com/en-us/library/windows/desktop/aa372380(v=vs.85).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DIV not showing in right place I have the following page:
http://sikni8.com/mypage/text.htm
The copyright section is not showing in the right place. I would like that to be right below the white box with the text "TEXT" inside it.
I tried all different method, but none is working! any idea?
Thanx
Edit: Alright, if you visit the above website, do you see the white box expanding from the left of the page to the right? I want that box to be below the white square with the curve bottom. makes sense? If not i will post a pic. Thanx
A: Use 3 containers float:left; width:100%; for the 3 majors sections of your website.
for example: <header> for your header <div id="content"> for your content<footer> for your footer. Put your white box text into the content div and the copyright into de footer. This way, all three section will appear below each other.Hope this help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Change Gender value in SQL table I have created a table in sql server and the tabel has Information of an Employee. There is a column to determine whether the Employee is male or female. i.e Male or Female. Now I need to convert all Male to Female and all Female to Male?
The table structure is:
CREATE TABLE Employee (
FName char(50),
LName char(50),
Address char(50),
Gender char(10),
Birth_Date date)
A: Freaky.
as a basic example, something like this:
update employees
set
gender = case gender
when 'Male' then 'Female'
when 'Female' then 'Male'
else 'Other' end
A: this should work:
UPDATE dbo.Employee
SET Gender =
CASE
WHEN (Gender = 'Female')
THEN 'Male'
WHEN (Gender = 'Male')
THEN 'Female'
END
A: Use this script
UPDATE [Employee]
SET [Gender] = CASE [Gender]
WHEN 'Male' THEN 'Female'
WHEN 'Female' THEN 'Male'
END
A: update employee
set gender=case when gender='Male' then 'Female'
when gender='female' then 'male' end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.