text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Set JLabel Alignment right-left I have a JPanel that separated to 2 blocks, in south block (layout) I have add a JLabel, In the label I want to Insert a string with this rule: (Name, Date, Time, In/Out)
If my name was written in English everything was fine the problem appeared when I wrote the name in some Unicode language like Farsi, then the alignment not working as expected.
I attach 2 sample:
Right one:
Wrong one:
A: You can create two different labels next to each other. One for the name and one for the remaining part. This way, the alignment of the name label won't affect the alignment of the other label.
A: Try using Component.setComponentOrientation() on the label to force it to left-to-right order.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to get the first line of text of a Matlab M-file? I am using Matlab R2011b. I want to get the text of the first line of the active mfile in the Editor. I know I can use the following code to get all the text of the mfile as a 1xn character array (not broken into lines). However I only want the first line.
activeEditor = matlab.desktop.editor.getActive ;
activeEditor.Text ;
Any suggestions?
A: You can search for the first "newline" character, and return everything from the beginning to that position:
activeEditor = matlab.desktop.editor.getActive;
pos = find(activeEditor.Text==char(10), 1, 'first');
firstLineStr = activeEditor.Text(1:pos-1)
A: One way to do this is to select all of the text on the first line and then access the SelectedText property:
>> activeEditor = matlab.desktop.editor.getActive ;
>> activeEditor.Selection = [1 1 1 Inf];
>> activeEditor.SelectedText
ans =
This is the first line of this file
You could improve on this by storing the current selection before selecting the entire first line and then restoring the selection after the selected text is accessed. This way the cursor position is not lost.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: JNI "env->GetStaticMethodID()" crashed program I'm trying to call a Java function from C++.
This is my code so far:
#include <jni.h>
typedef struct JavaVMCreationResult {
JavaVM* jvm;
JNIEnv* env;
} JVMCreationResult;
JVMCreationResult* CreateJavaVM() {
JavaVM* jvm;
JNIEnv* env;
JavaVMInitArgs args;
JavaVMOption opts[1];
opts[0].optionString = "-Djava.class.path=C:\\MyJavaClasses";
args.version = JNI_VERSION_1_6;
args.nOptions = 1;
args.options = opts;
args.ignoreUnrecognized = JNI_TRUE;
JNI_GetDefaultJavaVMInitArgs(&args);
JNI_CreateJavaVM(&jvm, (void **) &env, &args);
JavaVMCreationResult* cres;
cres->jvm = jvm;
cres->env = env;
return cres;
}
int main() {
JVMCreationResult* cres = CreateJavaVM();
JavaVM* jvm = cres->jvm;
JNIEnv* env = cres->env;
jclass cls = env->FindClass("Main");
jmethodID mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V"); // the evil line
}
I'm using Code::Blocks with MinGW GCC on Windows 7.
The last line in the main() function crashes the Program, but the compiler does not complain about anything. (Commenting out the jmethodID mid = env->GetSta... line makes the program "not crashing")
I have uses javap -s Main to obtain the right method signature, also the class is a valid Java class.
Can you tell me why the Program crashes ? This example is just shown everywhere on the Internet but it doesn't work for me. :(
This is the Java class:
public class Main {
public static void main(String[] args) {
System.out.println("This is from Java !");
}
}
SOLUTION
I wouldn't have thought it, it seems unlogic to me that the program wasn't crashing earlier when the struct wasn't initialized. But this was really the issue.
This is the full and working code !
#include <jni.h>
#ifndef null
#define null NULL
#endif
typedef struct JavaVMCreationResult {
JavaVM* jvm;
JNIEnv* env;
} JVMCreationResult;
JVMCreationResult* CreateJavaVM() {
JavaVM* jvm;
JNIEnv* env;
JavaVMInitArgs args;
JavaVMOption opts[1];
opts[0].optionString = "-Djava.class.path=C:\\Users\\Claudia\\Desktop";
args.version = JNI_VERSION_1_6;
args.nOptions = 1;
args.options = opts;
args.ignoreUnrecognized = JNI_TRUE;
JNI_GetDefaultJavaVMInitArgs(&args);
JNI_CreateJavaVM(&jvm, (void **) &env, &args);
JVMCreationResult* cres = new JVMCreationResult();
cres->jvm = jvm;
cres->env = env;
return cres;
}
int main() {
JVMCreationResult* cres = CreateJavaVM();
JavaVM* jvm = cres->jvm;
JNIEnv* env = cres->env;
jclass cls = env->FindClass("Main");
if (cls) {
printf("Yes !\n");
}
else {
printf("No !\n");
}
jmethodID mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, mid);
printf("At end of Program.");
}
A: Your variable "cres" is a point in the CreateJavaVM call that is never initialized, so you're probably dereferencing a null or otherwise invalid pointer at that point.
One solution is to define cres (not a pointer to cres) in main, and pass a pointer to that to CreateJavaVM as a parameter, and then use the parameter inside CreateJavaVM to return the result.
Also it's a good idea to check that jvm and env get non-null values after the JNI_CreateJavaVM call, and that cls and mid are likewise non-null after the calls to FindClass and GetStaticMethodID, respectively
A: cls is probably invalid. I presume your program would have crashed earlier if 'cres' was null.
int main() {
JVMCreationResult* cres = CreateJavaVM();
if(!cres) return -1;
JavaVM* jvm = cres->jvm;
JNIEnv* env = cres->env;
jclass cls = env->FindClass("Main");
if(env->ExceptionCheck()) { // ClassNotFoundException ?
env->ExceptionDescribe();
env->ExceptionClear();
}
if(!cls) return -2; // this I think is your problem
jmethodID mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V"); // the evil line
}
Are you sure your classpath has been specified correctly ? Hopefully FindClass("Main") will find a default package class. Anyhow tell us the return value if your C/C++ main() now.
It is possible for the "JavaVM* jvm = cres->jvm;" to be optimized away, since "jvm" is never referenced and the statement "cres->jvm" has no side effects. Some commenters state it should crash on this, hmm yes maybe, if code was generated and then executed. But a decent compiler might see it is a no operation.
However the statement "JNIEnv* env = cres->env;" can not be optimized away, since the variable "env" is used later on. So we can only claim that if cres==0 then it would crash at or before this point in execution. Since "env" is used for FindClass() call then we know for sure that env!=0 and therefore cres!=0.
I would guess you have a Class Path setup issue, FindClass() is not finding your class at runtime which is causing "cls==0" to be true. Which is my answer here.
EDITED: I see what the others are claiming over 'cres' however that does not change my original diagnosis, but you still have a bug regarding 'cres', change the line to:
JavaVMCreationResult* cres = new JavaVMCreationResult;
I think you are lucky that cres is pointing somewhere (probably on the stack), you then copied the values into the local main() stack and used the values. But that doesn't make the technique correct as the initial memory that 'cres' is pointing to is random, so you are lucky that no crash occured but you did scribble on memory you should not have. By using the "cres = new JavaVMCreationResult;" this causes the pointer to be set to a known valid block of memory.
If you want compiler assistance with this problem (i.e. it should show up a warning) try with MinGW "-Wall" and "-O2" options during compile. It should warn about uninitialized use of the variable 'cres'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to focus on a new Emacs frame in Windows How to get a focus for a new Emacs frame when it has been raised from outside of Emacs (for example, from emacsclient or edit-server)? Currently, the new frame get input focus, but not display focus, i.e. you enter text, but it's somewhere behind other windows (in Windows OS terminology). There was a similar question and it's marked as answered, but with no solution, though.
Emacs 23.3.
A: The function raise-frame can bring a frame to the front.
A: What version of Emacs are you running? I used put in gnuserv-visit-hook:
(select-frame-set-input-focus (window-frame (selected-window)))
But with Emacs 23, it's the default controlled by server-raise-frame.
A: See also function select-frame-set-input-focus:
"Select FRAME, raise it, and set input focus, if possible."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Reading commands from STDIN and executing each as it is entered I'd like to adapt the code below to use a ANTLRReaderStream so I don't have to create a new parser for each line. But it needs to process each line individually, which I don't have any idea how to do currently, and I don't see any way to ask the parser whether it has data ready (or whatever would be the equivalent of String line = stdin.readLine().
main loop:
stdin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = stdin.readLine();
if (line == null) {
System.exit(0);
}
processLine(line.trim());
}
handle a single line:
public void processLine(String line) throws IOException {
try {
QuotaControlCommandsLexer lexer = new QuotaControlCommandsLexer();
lexer.setCharStream(new ANTLRStringStream(line));
CommonTokenStream tokens = new CommonTokenStream(lexer);
QuotaControlCommandsParser parser = new QuotaControlCommandsParser(tokens);
Command cmd = parser.command();
boolean result = cmd.execute();
output(result ? "1" : "0");
stdout.flush();
}
catch (RecognitionException e) {
logger.error("invalid command: " + line);
output("ERROR: invalid command `" + line + "`");
}
}
A: If using JDK1.6 we can do the main loop as the following:
Console console = System.console();
if (console != null) {
String line = null;
while ((line = console.readLine()) != null) {
processLine(line.trim());
}
} else {
System.out.println("No console available!!");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "transform: rotate" -why my background images is also moving with rotation of text? I am trying to rotate text on a background-image but my background image is also moving with text rotation why? here you can see my work
HTML code is here
<ul>
<li>
<img src="http://lorempixum.com/200/200/food" />
<h2>price is $20 only</h2>
<span class="twenty-percent rotate"/>20% </span>
</li>
</ul>
CSS work is here
.rotate {
/* Safari */
-webkit-transform: rotate(-90deg);
/* Firefox */
-moz-transform: rotate(-90deg);
/* IE */
-ms-transform: rotate(-90deg);
/* Opera */
-o-transform: rotate(-90deg);
/* Internet Explorer */
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
li{position:relative;float:left;margin:15px;background:yellow;display:inline}
.twenty-percent{
background:url(http://canadianneighborpharmacy.net/images/cnp/discount_20.png);position:absolute; right:-15px; top:-5px; width:45px; height:45px}
you can see complete example in jsfiddle also here
http://jsfiddle.net/jamna/9pH6s/7/
A: CSS transform is applied to an element, not just on the element's contents. Hence your rotated background.
If you want to rotate text without rotating the background, add an extra <div> inside your element, and place the text + transform-CSS within that element.
Suggested update:
<span class="twenty-percent">
<div class="rotate"></div>
20%
</span>
A: Your rotating the span tag which is also holding your background image.
<span class="twenty-percent rotate"/>
rotate - rotating the span(everything in it.
twenty-percent - this is also holding your background image.
A: I would suggest to wrap 20% inside one more span <span class="rotate">20%</span> and give class .rotate to it instead.
<span class="twenty-percent"/><span class="rotate">20%</span></span>
A: You have two classes, but they are the same element, so when you rotate your .rotate class you are also rotating the class .twenty-percent as they are the same element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I change the text of a element? I have a toggle button that I'm adding to an iFrame:
<script>
$('#list div').each(function(){
$(this).append('<span class="togglebutton">Maximize</span>');
});
$("span.togglebutton").click(function() {
$(this).closest("li").children("div").toggleClass("maximized");
});
</script>
How can I change the toggle between the text Maximize/Minimize when the toggleClass is maximized?
A: $("span.togglebutton").click(function() {
var $this = $(this); // cache jquerized 'this'
$this.closest("li").children("div").toggleClass("maximized");
var currentText = $this.text();
// if the text is currently "Maximize"
if (currentText === "Maximize") {
// change it to new value
$this.text("New Text");
}
else {
// change it back to "Maximize"
$this.text("Maximize");
}
});
A: Well, if you are looking for some function like toogleClass() to do that job for you, you are out of luck. AFAIK, you have to do it manually.
Do something like this
function toggleText() {
var curText = $("span.togglebutton").text();
var newText;
if(curText=="Maximize") { newText = "Minimize"; }
else { newText = "Maximize"; }
$("span.togglebutton").text(newText);
}
Now you can call it happily where you want to toggle it. Like
$("span.togglebutton").click(function() {
$(this).closest("li").children("div").toggleClass("maximized");
toggleText();
});
A: $(this).text('New Text');
OR
$(this).val('New Text');
Determine state.
if ($this.text() == 'Maximized') {
$(this).text('Minimized');
} else {
$(this).text('Maximized');
}
A: $("span.togglebutton").toggle(function() {
$(this).closest("li").children("div").addClass("maximized")
$(this).text("Maximized Text");
},function(){
$(this).closest("li").children("div").removeClass("maximized")
$(this).text("Minimized Text");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Corrupt jar file I have created a jar file in windows 7 using eclipse. When I am trying to open the jar file it says invalid or corrupt jar file. Can anyone suggest me why the jar file is invalid?
A: This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main() method and have it referenced in MANIFEST.MF.
In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.
Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe, which won't work for those kind of libary JARs.
A: This is the common issue with "manifest" in the error? Yes it happens a lot, here's a link: http://dev-answers.blogspot.com/2006/07/invalid-or-corrupt-jarfile.html
Solution:
Using the ant task to create the manifest file on-the-fly gives you and entry like:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.2
Created-By: 1.4.2_07-b05 (Sun Microsystems Inc.)
Main-Class: com.example.MyMainClass
Creating the manifest file myself, with the bare essentials fixes the issue:
Manifest-Version: 1.0
Main-Class: com.example.MyMainClass
With more investigation I'm sure I could have got the dynamic meta-file creation working with Ant as I know other people do - there must be some peculiarity in the combination of my ant version (1.6.2), java version (1.4.2_07) and perhaps the current phase of the moon.
Notes:
Parsing of the Meta-inf file has been an issue that has come-up, been fixed and then come-up again for sun. See: Bug Id: 4991229. If you can work out if this bug exists in the your (or my) version of the Java SE you have more patience that me.
A: Also, make sure that the java version used at runtime is an equivalent or later version than the java used during compilation
A: This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn't generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.
The problem occurs when you zip back the folder.
A valid Runnable/Executable JAR has the next structure:
myJAR (Main-Directory)
|-META-INF (Mandatory)
|-MANIFEST.MF (Mandatory Main-class: com.MainClass)
|-com
|-MainClass.class (must to implement the main method, mandatory)
|-properties files (optional)
|-etc (optional)
If your JAR complies with these rules it will work doesn't matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar
Once you're done try execute it on the command line using:
java -jar myJAR.jar
When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:
**myJAR (Main-Directory)
|-myJAR (creates another directory making the file corrupted)**
|-META-INF (Mandatory)
|-MANIFEST.MF (Mandatory Main-class: com.MainClass)
|-com
|-MainClass.class (must to implement the main method, mandatory)
|-properties files (optional)
|-etc (optional)
:)
A: Could be because of issue with MANIFEST.MF. Try starting main class with following command if you know the package where main class is located.
java -cp launcher/target/usergrid-launcher-1.0-SNAPSHOT.jar co.pseudononymous.Server
A: The problem might be that there are more than 65536 files in your JAR: Why java complains about jar files with lots of entries? The fix is described in this question's answer.
A: As I just came across this topic I wanted to share the reason and solution why I got the message "invalid or corrupt jarfile":
I had updated the version of the "maven-jar-plugin" in my pom.xml from 2.1 to 3.1.2.
Everything still went fine and a jar file was built. But somehow it obviously wouldn't run anymore.
As soon as i set the "maven-jar-plugin" version back to 2.1 again, the problem was gone.
A: It can be a typo int the MANIFEST.MF too, p.ex. Build-Date with two :
Build-Date:: 2017-03-13 16:07:12
A: Try use the command jar -xvf fileName.jar and then do export the content of the decompressed file into a new Java project into Eclipse.
A: If the jar file has any extra bytes at the end, explorers like 7-Zip can open it, but it will be treated as corrupt. I use an online upload system that automatically adds a single extra LF character ('\n', 0x0a) to the end of every jar file. With such files, there are a variety solutions to run the file:
*
*Use prayagubd's approach and specify the .jar as the classpath and name of the main class at the command prompt
*Remove the extra byte at the end of the file (with a hex-editor or a command like head -c -1 myjar.jar), and then execute the jar by double-clicking or with java -jar myfile.jar as normal.
*Change the extension from .jar to .zip, extract the files, and recreate the .zip file, being sure that the META-INF folder is in the top-level.
*Changing the .jar extension to .zip, deleting an uneeded file from within the .jar, and change the extension back to .jar
All of these solutions require that the structure of the .zip and the META-INF file is essentially correct. They have only been tested with a single extra byte at the end of the zip "corrupting" it.
I got myself in a real mess by applying head -c -1 *.jar > tmp.jar twice. head inserted the ASCII text ==> myjar.jar <== at the start of the file, completely corrupting it.
A: Maybe this was just a fluke but the one time I had this error, I simply had to kill all javaw.exe processes that were running in the background. The executable JAR worked after that.
A: It can be something so silly as you are transferring the file via FTP to a target machine, you go and run the .JAR file but this was so big that it has not yet been finished transferred :) Yes it happened to me..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: android - Cursor returning wrong values I'm querying some products in SQLite database, but same base in 2 differents android's versions return differents values.
Select result in database.db3 using SQLite Expert:
I create this code after select, to test:
if(cursor.moveToFirst()){
while(!cursor.isAfterLast()){
log("CDPROD:" + cursor.getString(cursor.getColumnIndex("CDPROD")));
cursor.moveToNext();
}
}
Log Result in android 2.2:
09-26 14:30:08.947: INFO/LOGG(20497): CDPROD:000000000000211934
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000211944
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212020
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212124
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000214280
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212886
Log Result in android 2.1:
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:211934
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:211944
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212020
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212124
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:214280
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212886
This is a bug in Android??
Ty
A: You need to use as the column type text not string or varchar when you create your SQLiteTables. It seems that if you put string it will trim your leading zeros. Also see SQLite Data Types.
EDIT: According to this answer: Versions of SQLite in Android, they have diffrent SQLite versions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php: date conversion to dd-mm-YYYY format I'm trying to convert this timestamp format which I got from an Oracle sql query:
19-SEP-11 02.34.51.558459 PM
I need to convert it to this format: dd-mm-YYYY.
$install_date=strtotime($install_date);
$install_date=date("d/m/Y",strtotime($install_date));
but I'm getting weird results...
Any ideas?
*** forgot to mention, the field type is TIMESTAMP and not DATETIME
A: When dealing with formats that strtotime() cannot handle (see supported date and time formats), or even if you are, then you can create a DateTime object from any format using DateTime::createFromFormat() (or it's procedural twin, date_create_from_format()) (docs).
$install_date = '19-SEP-11 02.34.51.558459 PM';
$datetime = DateTime::createFromFormat('j-M-y h.i.s.u A', $install_date);
$datetime_dmy = $datetime->format('d/m/Y');
A: If it is a datetime field in Oracle, you could use
TO_CHAR(fieldName, 'DD-MM-YYY')
In your select, then it would be formatted as it comes out of the database.
A: Do this instead:
$install_date=strtotime($install_date);
$install_date=date("d/m/Y",$install_date);
You had already converted $install_date to internal time, then you were doing it again in the second line.
Of course, you can cut it all down to one line if you like:
$install_date=date("d/m/Y",strtotime($install_date));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Safe to keep .git directory in web root? I'm wondering if it's okay keep the .git directory in the web root for a web site.
The permissions of the .git folder and subfolders is 775 and the file are 644.
I suppose I could just set zero permissions for the "others" so that they'd also get access denied?
Thanks
A: You should put a .htaccess file in the .git directory containing the following:
Order deny,allow
Deny from all
this way, no one can access the directory.
In general, there is no answer if it is ok or not. If you are making your project open source anyway than there's no real problem with that. But if it is a private project than somebody could take advantage of the object-directory to get hold of your source codes
A: If you want to apply a consistent policy, you should regard your .git directory as private, since your config may have usernames and passwords (for HTTP) and refer to your testing repositories, which presumably one wouldn't want to publicize the locations of. And maybe you don't want people to see all your development history....
A common solution, which doesn't rely on you correctly denying access to the .git directory, is to create a bare repository with a post-receive hook that deploys to a directory in your web space. Then you can deploy your latest version just by pushing to that repository. There's a description of how to set that up here, for instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Draw over a video in an iphone application I am looking for a method so that i can make an iphone application which plays video and the user be able to draw over the video that is being played..
I would really appreciate it if some one could share some information on this regard..
A: In the simplest case, you could just put a UIView with a transparent background on top of the video being played.
If you want to merge/flatten the images, it gets a bit more complicated. Can you go into more detail on exactly what you're trying to do?
A: Hey there so yes putting a UIVIew over the video is going to be your best bet and then use quartz2d for drawing over it. And then lets say you would like to take a screen shot go ahead and use this code.
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
There you are! Oh and if you wanna say put an image or a UIIMageView over the video. Its not different at all. Just add the UIImageView to the UIView thats over the video:) Enjoi!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HibernateEntityQuery and EJBQL restrictions I've just inherited some code that uses HibernateEntityQuery and EJBQL restrictions.
There's an "activity" table/entity with various fields, and the existing EJBQL restrictions look like:
private final String[] SEARCHRESTRRICTION = {
"activity.startDate >= #{activityList.startMonthBeginDate}",
"activity.startDate <= #{activityList.startMonthEndDate}",
"activity.cost >= #{activityList.minCost}"
}
The table also has seven boolean fields representing days (sun/mon/tue...) which apply for a given activity. Now I'd like to query by days- the user will select days they are interested in, and the filtered results should include activities which match any of the days chosen by the user.
For example, if the user checks mon/wed/fri, the query should return all activities for which mon = true OR wed = true OR fri = true.
The problem with EJBQL is that it applies the restrictions using AND, whereas I need to do something like:
select * from activity where
(mon = true OR wed = true OR fri = true);
Is there a way to specify a restriction in the form of "return a result if ANY of the following are true"?
A: The solution was to move the initial filtering to the setEjbql() call, which is applied prior to the setRestrictionExpressionStrings().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Div keeps wrapping when browser size shrinks How do I stop a div from wrapping/moving below when the browse is resized to the left. everything else on the page stays still except this one box. I want it to not move and force the user to use the browser left right scroll to view it.
#signup_box {
width: 363px;
height: 392px;
float: right;
margin-right: -34px;
min-width: 363px;
}
A: You're floating it. It will wrap. Try positioning it manually, something like:
#signup_box {
width: 363px;
height: 392px;
position:absolute;
right:34px;
top:0px;
min-width: 363px;
}
A: You have floated the div using float: right;, so it will adjust its position ("float") as necessary.
You can remove the float to stop this behavior, and ensure your page is wide enough to accomodate the width of this (and other relevant) elements.
A: Try overflow: scroll.
A: No, There is a simple way to do this...It can work but it is css3. But you can try:
div {
white-space: nowrap;
}
Please reply if it works for you! Thanks! By the way, It will only work if you put it in all elements or just put it in a container. This way, you can put in float without it wrapping
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to hide columns GridView when AutoGenerateColumns = "true"? I am using an Asp:GridView with AutoGenerateColumns property set to true to display all the fields.
But I am struck with a problem here.
I need to show only few columns not all..but I do not know them until run-time, like which fields to bind.
So, There are 2 sets of columns coming for me one with Prefix B_ and the other with Prefix R_
I need to show either B_ or R_ based on the radio button selection.
But I do not want to make separate call to the DB on radio button selection, So I am pulling all the data at once, when I am binding to the grid.
But the problem as I said it is showing all the columns but initially I want the grid to display only columns with prefix B_
Is there a way can I achieve this, Please do help me..
Thanks and appreciate your feedback.
A: I'd recommend loading them into two different sets of objects, and changing the value of the ItemsSource DataSource property when different radio button values are selected.
EDIT: Replaced ItemsSource with DataSource, getting my ASP.NET and WPF mixed up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I set up curl to permanently use a proxy? How can I set up "curl" to permanently use a proxy server in the terminal?
A: Many UNIX programs respect the http_proxy environment variable, curl included. The format curl accepts is [protocol://]<host>[:port].
In your shell configuration:
export http_proxy http://proxy.server.com:3128
For proxying HTTPS requests, set https_proxy as well.
Curl also allows you to set this in your .curlrc file (_curlrc on Windows), which you might consider more permanent:
http_proxy=http://proxy.server.com:3128
A: You can make a alias in your ~/.bashrc file :
alias curl="curl -x <proxy_host>:<proxy_port>"
Another solution is to use (maybe the better solution) the ~/.curlrc file (create it if it does not exist) :
proxy = <proxy_host>:<proxy_port>
A: Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:
proxy = yourproxy.com:8080
A: One notice. On Windows, place your _curlrc in '%APPDATA%' or '%USERPROFILE%\Application Data'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "116"
}
|
Q: Mongoid namespaced models and inheritance I'm trying the use namespaced models with Mongoid and can't seem to get it to work.
I have the following models: Achievement, Flag, FlagCaptured
Achievment is the base class for FlagCaptured.
app/models/achievement.rb
class Achievement
include Mongoid::Document
include Mongoid::Timestamps::Created
belongs_to :team
end
app/models/flag.rb
class Flag
include Mongoid::Document
field :name, :type => String
field :key, :type => String, :default => SecureRandom.base64
field :score, :type => Integer
belongs_to :achievement, :class_name => "Achievements::FlagCaptured"
validates :name, :presence => true, :uniqueness => true
validates :key, :presence => true, :uniqueness => true
validates :score, :presence => true, :numericality => { :only_integer => true }
def captured?
!achievement_id.nil?
end
end
app/models/achievements/flag_captured.rb
module Achievements
class FlagCaptured < Achievement
has_one :flag, :foreign_key => :achievement_id, :autosave => true
def score
self.flag.score
end
end
end
I create the FlagCaptured achievement in the console like so:
Achievements::FlagCaptured.create(:flag => Flag.first, :team => Team.first)
Now the achievement will be created and I can get it with:
Achievements::FlagCaptured.first
However, neither side of the relation is set.
So
Achievements::FlagCaptured.first.flag
is nil
and
Achievements::FlagCaptured.first.flag_id
gives a NoMethodError.
Further both:
Flag.first.achievement
Flag.first.achievement_id
are nil.
What is going on here?
I've tried everything I can think of (setting the foreign keys, specifying the class names, specifying the inverse relation) and nothing works. :(
A: Turns out that I needed to add
:autosave => true
to the relation in the FlagCaptured model and define the right foreign key
and everything is working fine now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to automatically convert email attachment filename to UTF-8 (using Mail_mimeDecode) I'm using Mail_mimeDecode to extract attachments from incoming emails. Everything was working well for a while, until I started receiving attachments with filenames encoded in KOI8, with a section header like this:
Content-Disposition: attachment; filename="=?KOI8-R?B?8NLJzM/Wxc7JxSAudHh0?="
mimeDecode does a perfectly reasonable thing and returns the filename in KOI8:
$attachmentNameInKOI8 = $part->d_parameters['filename'];
The problem is that I need it in UTF-8. In this specific example, I can run the following to do the conversion:
$attachmentNameInUTF8 = iconv('KOI8', 'UTF-8', $attachmentNameInKOI8);
But without trying to parse the message manually, I don't know when the name is in KOI8 and when it's not. I'm also worried that some other encoding will come through soon, so I need a way to handle anything that might come my way.
I had read that mb_detect_encoding is not reliable, and in fact I could not get it to detect the string as KOI8.
Is there a way to tell mimeDecode to do the translation for me? I looked at the sourcecode of mimeDecode.php:_decodeHeader() and I can see that it parses the encoding but then does nothing with it, which seems a wasted opportunity.
UPDATE: To be clear, this is only a problem with headers and not with bodies because mimeDecode exposes the charset of the body, so it's very easy to run iconv yourself like this:
$bodyutf = iconv($textpart->ctype_parameters['charset'], 'UTF-8', $textpart->body);
A: Adding a line to _decodeHeader() before the replace seems to do the trick:
$text = iconv($charset, 'UTF-8', $text);
$input = str_replace($encoded, $text, $input);
Seems weird that they didn't build some such option into the original class, doesn't it?
NOTE: I've since noticed that Subject lines and other headers can also be encoded the same way as filenames (RFC2047). It appears that adding the iconv line into _decodeHeader addresses all these cases.
Weird that such a feature wasn't already built into mimeDecode--this can't be a rare problem.
EDIT: I now understand that the point of mimeDecode having an option for decode_headers=false is to get the raw values so you can decode them yourself. This seems such a waste given that there's no point to having mimeDecode decode your headers ever if you can't trust that it's going to return a string in an expected charset (it would make more sense for it to accept a charset as a parameter to decode to; or null means no decoding... I have a feeling they're unlikely to change it for little me.) So the point is you need to do your own decoding. Unfortunately it's not as simple as a straight call to imap_utf8() or imap_mime_header_decode(). You could either take the _decodeHeader() function from mimeDecode and modify it or use something like this:
http://www.php.net/manual/en/function.imap-mime-header-decode.php#71762
EDIT #2: Unbelievably, the mimeDecode guys already incorporated my suggestion into their latest svn:
https://pear.php.net/bugs/bug.php?id=18876
On that version, you can now set decode_headers='UTF-8' and mimeDecode will do all the work for you. Wow!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Integrating a Ruby/Rails app into a Java app. I have a Ruby/Rails app, which is standard Rails CRUD, with some jQuery and no AJAX.
I have a Java web app with which I would like to integrate the Ruby/Rails app. The Rails app uses the same database as the Java web app and (safely) shares a few tables, and I will put the Rails app into a WAR file using a JRuby/Warbler and the deploy it to a separate Tomcat on the same physical server. The Java app runs on port 80, and the Rails app runs on port 3000 on the same server.
In the UI of the Java app, there is a place to put the new UI of the Ruby app. It is in the form of a few blank "div" tags on a few skeleton pages, and some accompanying screen real estate. I don't want to finagle with the Java UI code as much as possible, and get away with the minimum needed.
Is there a way to run the UI of the Ruby app as within two or three div's to which I have access? Ideally, can I point each div to load up one entry point in my Rails app (URL) and then have it load other pages as needed?
Do I have to worry about back buttons?
Are there any other questions I should ask to solve this problem?
Cheers, Jay
A: iframes in the divs might get you there fastest if the Rails port is also visible to the outside. If it isn't, then perhaps it can be configured to work on some /subpath under port 80, though that might lead to a little bugfixing if your Rails code has assumptions about it being at /.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: jQuery form validation logic I have the following code:
function showError(l, msg) {
$('#'+l).css({'color':'red'});
$('#error').html(msg).fadeIn(500);
}
$(document).ready(function(){
$('#form').submit(function() {
if($('#username').val() == '') {
showError('labelUser', 'Please enter a username');
return false;
}
if($('input[type=password]')[0].value != $('input[type=password]')[1].value) {
showError('labelPassword', 'Password does not match');
return false;
}
// etc...
$('label').css({'color':'black'});
$('#error').html('').fadeOut(200);
return true;
});
});
I have in my form a total of 10 fields (name, first name, email etc...). As you can see in my script (//etc...), I repeat the SAME case over and over if a field is valid or not.
I think repeating the showError and return false is not a good solution.
Is there an easier way (or better) to use validate data? Thank you
A: Use the jQuery Validation Plugin.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
It does this type of thing without writing any code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C# Splitting Strings on `#` character just wondering for example, if I had the string:
Hello#World#Test
How would I remove the # and then have Hello, World and Test in three seperate strings, for example called:
String1 and String2 and String3
A: You can have them in an array of strings doing something as easy as this:
string[] s = "Hello#World".Split('#');
s[0] contains "Hello", and s[1] contains "World"
See here for more information on split: http://msdn.microsoft.com/en-us/library/b873y76a.aspx
A: String.Split("#".ToCharArray()) will return a string[] with two elements.
Element0 will be "Hello", and Element1 will be "World"
A: This is one way
"hello#world".Split('#');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: Strange program and debugger if statement behavior This is a sanity check because I've lost mine.
I have a method IsCaptured() which compares an enum state member to a given value and returns a bool. I use this in conjunction with a mouse threshold check to determine if a drag begin message should be sent and a drag operation begun. The problem is this is being triggered on mouse move when it shouldn't be. I've added trace messages as follows:
TRACE(L"%s\n", (IsCaptured()) ? L"true" : L"false");
CPoint delta = pt - m_trackMouse;
static CPoint thresh(GetSystemMetrics(SM_CXDRAG), GetSystemMetrics(SM_CYDRAG));
if (IsCaptured() &&
abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y)
{
TRACE(L"%s\n", (IsCaptured()) ? L"true" : L"false");
// Send message to enter drag mode
bool bDrag = ::SendMessage(m_trackWnd, WM_DD_BEGIN, ::GetDlgCtrlID(m_trackWnd), (LPARAM)(void*)&m_info) != 0;
// ...
}
Now the strange part, the output:
false
false
The method is implemented like so and m_dragState is set to NONE until there is a button down intercepted:
enum { NONE, CAPTURED, DRAGGING };
bool IsCaptured() const { return m_dragState == CAPTURED; }
I've tried rebuilding the entire solution to no avail. I'm running VS2010 Debug 64-bit and the program is a single threaded MFC app. What the $@#! is going on here?
A: There's nothing strange in your output. && has higher precedence than ||, which is why your
if (IsCaptured() &&
abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y)
is interpreted as
if ((IsCaptured() && abs(delta.x) >= thresh.x) ||
abs(delta.y) >= thresh.y)
I.e. if the abs(delta.y) >= thresh.y condition is met, then the result of the entire if condition does not depend on your IsCaptured() at all.
The compiler does not care that you "expressed" your intent in line breaks. Operator precedence matters. Line breaks don't.
What you apparently were intending to do was
if (IsCaptured() &&
(abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y))
Note the placement of extra braces around the operands of || subexpression.
A: Think of this as:
(IsCaptured() && abs(delta.x) >= thresh.x || abs(delta.y) >= thresh.y)
this:
(false && true) || true
Your IsCaptured() doesn't have to be true to progress, so it can quite possibly be false in both printouts.
A: You should probably make sure first that the two false's do not refer both to the first trace line.
If the second trace line is actually printing false here, you probably have a classic race condition on your hands and need to protect against it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Php for a bilingual site Is it possible using php, for a user to click on a english/french toggle button, that would then read the current url, and match it to the french version of the page?
Thank you for your time.
A: When the users clicks the button, populate a session variable with the selected language:
session_start();
$_SESSION['language'] = 'FR'; // Or 'EN', etc
Then use templates to store your language-specific information. When you load the template, include the language code
// Load a template
Template::load( '<page_name>', $_SESSION['language'] );
// Where the `load()` method looks something like this:
public function load( $page_name, $language ) {
// Construct the path to the template
$file_handle = fopen( PATH_TO_TEMPLATES . $language . "/" . $page_name );
// Do something with the template here.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: AdPlus & WinDbg: difference between taking a dump with AdPlus and with WinDbg? The task - when the application crashes, it is required to find the crash cause.
I saw recommendations to take the crash dump with AdPlus and then load it into WinDbg for analysis.
What I do is attach WinDbg to a process and wait for the program crash to debug once WinDbg shows the exception.
Is there any advantages in using AdPlus instead of directly attaching WinDbg to the process?
A: In your case, there's no advantage in creating a dump using AdPlus. If you can attach WinDbg and debug on the target machine, having the complete heap at hand, that's the best you can get.
In general, AdPlus is merely a VB script that wraps CDB, which is a console debugger. When you use it, CDB effectively debugs your program, the same way WinDbg does. The gain you get from using AdPlus is the easy configuration and notification options. Also, since it's designed to create dumps, it does that nicely - creates a per dump folder etc. But that's just convenience - as far as your basic need of finding the bug goes, in your case I'd stick with WinDbg.
A: I would say ADPlus is only better for non-technical person.
For developers, load process into WinDbg is much more convenient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XML declaration encoding What does it actually do? On my very basic level of understanding XML is just a formatted text. So there is no binary<->text transformation involved.
I highly suspect that the only difference between UTF-8 and ASCII encoding is that ASCII encoding will make XML writer work harder by converting all the non-ASCII characters into XML entities as opposed to just reserved XML characters. So ASCII encoded XML can still contain UTF-8 characters, except it is going to be slightly longer and uglier.
Or is there some other function to it?
Update:
I perfectly understand how individual characters are converted into byte(s) by means of encoding. However XML is just text markup and at no point does that.
The question really is why XML encoding value is stored in the XML? Or what is the case where XML reader would need to know which encoding was used for any particular XML document?
A: See Appendix F in the XML specification, "Autodetection of Character Encodings".
In particular, "XML encoding value is stored in the XML" because, by default, XML processors must assume the content is in UTF-16 or UTF-8, in the absence of external metadata found outside of the XML document. The XML declaration is designed for such cases where such metadata is not present.
Another advantage to how XML handles encodings is that this way, an XML processor
need support only two encodings, namely UTF-8 and UTF-16. If the processor discovers,
either in external metadata or in the XML declaration, that the document is in an encoding
it does not support, it can fail sooner than it would if it continues to read the document (long
after the declaration) and encounters an unexpected byte sequence for the encoding
detected using implementation-dependent heuristics.
A: I'd highly, HIGHLY recommend reading The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). You're saying XML is "just text" as if that makes everything simple, but even knowing that it's text as opposed to some structured binary format doesn't mean you know exactly how to read it or what characters are therein.
This isn't a "go read the manual!" answer, I believe establishing this baseline on how difficult text can be will help explain why the XML declaration exists.
why does XML declaration need encoding in the first place?
This is one of the ideas addressed in the article, but it's worth stressing here: All text has an encoding. There is no such thing as 'Plain Text'. ASCII is an encoding, even if we don't think about it most of the time. Historically we've often stuck our head in the sand and assumed everything is ASCII, but this isn't feasible in today's day & age. The XML declaration's encoding helps us out, where has a .txt file has nothing to indicate what its encoding is.
A: Yes, an XML file is a text file, i.e. a sequence of characters. A file is a sequence of bytes. So how are individual characters encoded, i.e. converted into a sequence of bytes? There are several ways to encode characters into bytes; the "encoding" declaration indicates which one is used.
As such, the "encoding" declaration plays a very significant role: one absolutely needs to know which encoding is used to be able to merely read the characters from a file. If no encoding is specified, XML has a set of default encodings, depending on the presence of a “byte order marker” (BOM). If there is no BOM, the default encoding is UTF-8.
ASCII is one of the simplest forms of encoding. It can only represent a span of 128 basic Latin characters. UTF-8 is more elaborate; it can represent all of the Unicode character set. So you're right, if you're using ASCII, you're obliged to use XML entities to represent the huge amount of characters that exist in Unicode but not in ASCII.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to jQuery select all links on a page that are NOT contained within a certain div Suppose I have product links on a page, some products are within a recommendation div:
<a href="some_url?pid=abc"><img src ... ></a>
<a href="some_url?pid=abc">ABC Product Name...</a>
<a href="some_url?pid=def">
.... more product links
<div class="recommendations">
<a href="some_url?pid=uvw"> ...
<a href="some_url?pid=xyz"> ...
</div>
I need to construct unique list of pids for recommended and non-recommended urls like this:
recommended_pids = ["uvw","xyz"];
non_recommened_pids = ["abc","def"];
I know I can git the list of all pid on a page like this:
$('a[href*="pid="]').each(function() {
//get just the pid part
var link = this.href;
var pid = link.split('pid=')[1].split('&')[0];
pids.push(pid);
});
And I can get the list of recommended pids on a page using selector like this:
$('div.recommended a[href*="pid="]')
Sort and uniq each array then subtract all elements then do array subtraction to get the list of non-recommended pids.
But is there a way to use other jQuery filters to get the list of pids NOT contained within the recommended div without resorting to writing an array subtract function?
A: Well, there's always .filter():
var $pidLinks = $('a[href*="pid="]');
// recommended links
$pidLinks.filter('div.recommendations > a');
// non-recommended links
$pidLinks.filter(':not(div.recommendations > a)');
Somewhat gratuitous jsFiddle
For what it's worth, @Jayendra's solution is simpler and probably better, unless you need to get both lists - in which case I believe that using .filter() should have better performance if you cache the original selection of all links.
A: Use not
$("a:not(.recommendations a)").each(function(index){
alert(this.id);
});
A: Inside the each function you could do this:
if( $(this).parents(".recommendations").length ) {
recommended_pids.push(pid);
} else {
non_recommened_pids.push(pid);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is system-wide Mercurial installation enough in a shared enviroment? I am learning how I can install Mercurial on our team system, but I am not experienced enough to make some decision.
For our team, we have a server machine used as a repository. Every team member also has her/his own Linux RedHat installed machine. However, we do not do anything on our local terminals and we do everything on the server. Every member has a user directory on the server such as /home/Cassie, /home/john, ... and we save all our code and work there. When we turn on the local terminals, the GNOME system shows our personal files on the server not the local machine. Whenever everyone click the terminal application on desktop, it connects to her own home directory. Thus, we do not need to use SSH command to connect to the server. It is like the school multi-users system. Everyone has a user account and she logs into her own account to do her own work. I hope I can install a shared repository on that server and every one can do push, pull, etc. all kind of commands there.
1) Since we use a shared environment, does it mean that I need to install Mercurial on only the server and that is enough for everyone to do "commit", "push", "pull", etc. commands?
2) By installing only system-wide Mercurial, does it eliminate the ability to do local commit? If I would like to let everyone still have the "local commit" ability, how should I do it?
3) I have searched online. Some people mentioned that for a shared network server, it is impossible to have locks for any two users if they are trying to access the same file at the same time. Does it imply my situation?
In sum, we do all the work on the server. I hope to find a plan to have Mercurial control on a repository shared by everyone when everyone still has local commit ability and the repository still has some locks protection if any two users try to access a file at the same time. If this scenario is feasible, can I just install the Mercurial on the server or I need to install Mercurial for both servers and users machines? If it is impossible for the scenario, would someone please suggest me a plan to have version control for our system?
A:
1) Since we use a shared environment, does it mean that I just need to install the Mercurial on the server and it is enough for everyone to do "commit","push","pull"..etc commands ?
If your users are logging into a shell on the server in order to do their work, then yes it is sufficient to have Mercurial installed only on the server.
2) By installing only system-wide Mercurial, does it eliminate the ability to do local commit ? If I would like to let everyone still have the "local commit" ability, how should I do it ?
Your users will presumably checkout from a shared "root" repository into their own home directory in order to work on the code. They will have a "local" copy of the repo in their home directory and will push into the shared root repository.
3) I have searched online. Some people mentioned that for a shared network server, it is impossible to have locks for any two users if they are trying to access the same file at the same time. Does it imply my situation ?
As long as your users are working within their own local copies of the repo, they will not interfere with one another. The only time a conflict may arise is when committing back to the shared root repository -- in which case the user will need to merge their changes and resolve any conflicts.
I would recommend reading carefully through Joel Spolsky's excellent Hg Init tutorial for a better understanding of how Mercurial handles "central" and "local" copies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Controlling the URL for an Axis2 web service Can the format of the URL for an Axis2 web service be configured when using the code-first approach (where Axis2 is generating the URL)? In particular, we would like to leave the port name out of the URL.
We have a web service that was built with Axis2 using the code-first approach. That means the WSDL is generated from the Java classes and their annotations.
The web service URL is currently:
http://www.example.com/services/AvailabiltyService.AvailabilityServicePort
But we would like the URL to be shortened to:
http://www.example.com/services/AvailabiltyService
The <service> element of the generated WSDL currently looks like this:
<service name="AvailabilityService">
<port name="AvailabilityServicePort" binding="tns:AvailabilityServicePortBinding">
<soap:address location="http://www.example.com/services/AvailabilityService.AvailabilityServicePort/"/>
</port>
</service>
From what I understand, the URL is determined as follows:
*
*The "/services/" portion is specified in the web.xml file. The pattern "/services/*" is specified in the web.xml file to route all requests matching that pattern to the AxisServlet.
*The "AvailabiltyService" portion is the service name. It defaults to the value of the "name" parameter of the @WebService annotation with the word "Service" appended to it. This can be overridden by including a "serviceName" parameter on the @WebService annotation. In our case, we have included the "serviceName" parameter on the @WebService annotation with the value "AvailabilityService".
*The "AvailabiltyServicePort" portion is the port name. It defaults to the service name with the word "Port" appended to it. This can be overridden by including a "portName" parameter on the @WebService annotation. In our case, we have not included the "portName" parameter on the @WebService annotation.
I realize we would have control over the URL if we used the contract-first approach, where we would write the WSDL ourselves, but we prefer to stay with the code-first approach.
Thank you for your time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sending multiple emails efficiently I have reached a point where I will have to send email notifications to my users, fro any event they have subscribed to. My service is not large, but nothing stops it from becoming one, thus I would like to be prepared.
Currently, I am handling those emails using Spring's mail sender in a fairly synchronous manner (grabbing a bunch of subscribed email addresses from a collection and sending them a mail) However, one can see how unusable this approach may soon become. Thus I am striving for a little bit more parallelism.
Multiple threads may help the situation unless there are too many of them at the same time. I guess |I will need something like an in-memory queue, which could send batches of emails at certain intervals, opening a new thread. Threads which are finished will eb collected in a thread pool and reused.
Suggestions? Perhaps my approach is too complex. Perhaps Spring already offers a way to alleviate the blocking and synchronism. I'd be glad to know.
A: Rather than send one email to each user, just send a single email to all of the users at once. In other words, make one mail and add every user to the destination list. Then your SMTP server will worry about duplicating it and sending copies to each person.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SQLite Count where query I use a simple sql lite query to fetch the count value from a table.
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME, null);
if (cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
This works good
But when I add a where clause to the select query
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME + "WHERE name in (" + k + ")", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
process stops unexpectedly.......
A: You're missing a space in front of the WHERE: ... + TABLE_NAME + "WHERE name ...
But there's a lot wrong with your code:
*
*Why do you use rawQuery() when there's nice methods like query(table, columns, selection, selectionArgs, groupBy, having, orderBy) that spare you from building query strings at risk of SQL injection? Even rawQuery() takes query arguments as second parameter.
*Where do you close your Cursor? You'll leak memory this way.
*What happens if cursor.moveToFirst() returns false and you execute the line after your if-block? This will crash.
A: Check the value of that k variable, it might be not valid for sql IN operator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Fixed positioning an ad in IE Can skip to the edit for a more up to date explanation.
I can't seem to set an ad that gets written out via document.write() to a fixed position. It works fine in all other browsers besides IE, and that includes IE9.
Here is an example: http://htinteractive.com/bottom_bar/demo.html
Any suggestions would be highly appreciated. I'm running out of ideas.
Thank you.
Edit:
I've narrowed the problem down to the following IE issue I'm having. To simplify it down...
<style type="text/css">
#temp1
{
position:fixed;
bottom:0;
height:100px;
width:100px;
border:solid 2px red;
}
</style>
<!--WORKS IN IE-->
<div id="temp1">
<script type="text/javascript">
document.write("<scr" + "ipt type=\"text/javascript\">\nif(typeof(cachebuster) == \"undefined\"){var cachebuster = Math.floor(Math.random()*10000000000)}\nif(typeof(dcopt) == \"undefined\"){var dcopt = \"dcopt=ist;\"} else {var dcopt = \"\"}\nif(typeof(tile) == \"undefined\"){var tile = 1} else {tile++}\ndocument.write('<scr'+'ipt src=\"http://ad.doubleclick.net/adj/shz.bloomington/home;pos=728x90_1;' + dcopt + ';tile=' + tile + ';sz=728x90;ord=' + cachebuster + '?\"></scr'+'ipt>');\n</scr" + "ipt>");
</script>
</div>
<!--FAILS TO FIX POSITION IN IE-->
<script type="text/javascript">
document.write('<div id="temp1">');
document.write("<scr" + "ipt type=\"text/javascript\">\nif(typeof(cachebuster) == \"undefined\"){var cachebuster = Math.floor(Math.random()*10000000000)}\nif(typeof(dcopt) == \"undefined\"){var dcopt = \"dcopt=ist;\"} else {var dcopt = \"\"}\nif(typeof(tile) == \"undefined\"){var tile = 1} else {tile++}\ndocument.write('<scr'+'ipt src=\"http://ad.doubleclick.net/adj/shz.bloomington/home;pos=728x90_1;' + dcopt + ';tile=' + tile + ';sz=728x90;ord=' + cachebuster + '?\"></scr'+'ipt>');\n</scr" + "ipt>");
document.write('</div>')
</script>
Anyways, I really need the 2nd method to work, and I'm pulling my hair out trying to figure out how.
Thanks.
A: Maybe IE needs the temp1 DIV to be ended before writing the script element:
<script type="text/javascript">
document.write('<div id="temp1"><' + '/div>');
document.write("<scr" + "ipt type=\"text/javascript\">\nif(typeof(cachebuster) == \"undefined\"){var cachebuster = Math.floor(Math.random()*10000000000)}\nif(typeof(dcopt) == \"undefined\"){var dcopt = \"dcopt=ist;\"} else {var dcopt = \"\"}\nif(typeof(tile) == \"undefined\"){var tile = 1} else {tile++}\ndocument.write('<scr'+'ipt src=\"http://ad.doubleclick.net/adj/shz.bloomington/home;pos=728x90_1;' + dcopt + ';tile=' + tile + ';sz=728x90;ord=' + cachebuster + '?\"></scr'+'ipt>');\n</scr" + "ipt>");
</script>
EDIT (in response to your comment):
Since you want the ad script to go inside the div, you will have to put document.write aside and create the script programmatically, so you can simply call appendChild to put it into the div:
<script type="text/javascript">
document.write('<div id="temp1"><' + '/div>');
if(typeof(cachebuster) == "undefined") {
var cachebuster = Math.floor(Math.random() * 10000000000);
}
if(typeof(dcopt) == "undefined") {
var dcopt = "dcopt=ist;";
} else {
var dcopt = "";
}
if(typeof(tile) == "undefined") {
var tile = 1;
} else {
tile++;
}
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://ad.doubleclick.net/adj/shz.bloomington/home;pos=728x90_1;"
+ dcopt
+ ";tile=" + tile
+ ";sz=728x90;ord=" + cachebuster + "?";
divTemp.appendChild(script);
</script>
Please note that I cannot be 100% sure I did not make some typo while reformatting the script, with all those escaped sequences...
A: Not tested, but seems like it should work:
<script>
(function(){
var w = window,
d = document,
s = d.createElement('script'),
div = d.createElement('div'),
el = [].slice.call(d.getElementsByTagName('script'), -1),
baseUrl = 'http://ad.doubleclick.net/adj/shz.bloomington/home;pos=728x90_1;';
// end var block
if(!("cachebuster" in w)){
cachebuster = Math.floor(Math.random()*10000000000);
}
dcopt = "dcopt" in w ? "" : "dcopt=ist;";
tile = "tile" in w ? tile+1 : 1;
div.id = 'temp1';
div.appendChild(s);
el.parentNode.inserBefore(div, el);
s.src = baseUrl + dcopt + ';tile=' + tile + ';sz=728x90;ord=' + cachebuster + '?';
})();
</script>
A: It looks like the script tags are not embedding the ad inside your DIV as you would expect.
According to IE Developer tools, the ad is outside of your DIV and therefore doesn't get the positioning.
Using your example code changing #temp1 to just an A positions your ad where you want it.
The problem is just that your ad is not receiving the style. If you have the option of getting your ad to come back with an ID then you could probably base your style on that or alternatively use DOM manipulation to get your ad in the right spot.
The deeper issue, getting the ad script to render its content inside your DIV I'm just not sure about.
Update:
I believe the difference to IE is the method of using the SCRIPT tag. Using the src attribute to load script from another location seems to break the node tree.
Here's some evidence:
http://jsfiddle.net/wuqVw/1/
http://jsfiddle.net/wuqVw/2/
In the first example you can see that the ad is inside of the DIV whereas in the second it is below. There is probably some rule in IE that says SCRIPT tags with src attributes belong in the HEAD so it's putting them outside your DIV.
A: check to see if your HTML has DTD format
A: This resource might help
http://ryanfait.com/resources/fixed-positioning-in-internet-explorer/
You can also use browser specific hacks or you can specify a different document:
<!--[if lte IE 9]>
A: When writing script with an "src" attribute, some browsers parse the following inline code before actually running the external script. The result of the external script will be written outside of the div, because the inline code creates it, this was true for a lot of browsers a while back.
There's no simple way to overcome this, either put the div in the html, or in the external script.
A: What happens if you put following on top of your page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to do unit test for view in ASP.NET MVC Is there any way that can I write a unit test for Views in my ASP.NET MVC application?
I need to validate the button names, title, etc. stuff using such tests.
A: We've used Coded-UI Tests for ASP.NET web applications. If you have the appropriate Visual Studio version, this may be on option. Ideally for MVC you can also write a lot of these tests against the controllers, which is baked in, but since you asked about Views I'm sharing the Coded UI link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Log output from unrar.exe to a text file (Batch script) I am writing a batch script that extracts files and would now like to log the output from unrar.exe to a text file. The output I have in mind are things like failure due to corrupted archives etc. or simply that the operation was successful.
Any ideas on how to solve this?
Thanks in advance!
A: You use redirection:
unrar > logfile.txt
To also redirect stderr:
unrar > logfile.txt 2>&1
A: Just the STDOUT
unrar>"output.txt"
Only the errors (ERROUT)
unrar 2>"errors.txt"
Both STDOUT and ERROUT
unrar 2>&1 "both.txt"
Or both in separate files:
unrar 2>"errors.txt" >"output.txt"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Validate an html document that I wrote with document.write() Ok first off let me state that I know I should never do this under any circumstances for a real site. Ok. That's out of the way.
One of my coworkers was going off that Javascript is not a "real" programming language (his definition of "real" seems to be "it compiles"), because it depends on other languages to do its thing.
I told him I could write a website using nothing but javascript.
I am sure that this can be done, using document.write('') to get the doctype, and some script to create a dom and styles... but the problem is since the page is validated without JS, it can't show him that what the browser is looking at does in fact validate.
Anyone know of a way I can validate the actual source the browser is using instead of the javascript that initially loaded?
A: Load the site in Firefox with Firebug installed. Fire up the "HTML" view and rightclick on the <html> node and select "copy HTML".
A: If you really want to demonstrate that JS is a "real" language, then you would probably be better off not using a browser as the foundation. A node.js server would allow you to generate an HTML document (using document.write if you like, but DOM is an option (and people have used client side libraries to manipulate a document in node.
Since the JS runs on the server, you can get the actual source from the browser via view-source or point the validator directly at the URI (so long as it is either public or you install a local copy of the validator)
A: The closest you get using JavaScript:
var generatedHTML = document.documentElement.innerHTML;
//Retrieves everything within the (missing)HTML tags.
//The only missing parts are DOCTYPE and the <html> itself
var txt = document.createElement("textarea");
txt.style.cssText = "width:99%;height:99%;position:fixed;z-index:999;top:0;left:0";
txt.value = generatedHTML;
txt.ondblclick = function(){this.parentNode.removeChild(this)};
//Adding a simple function to easily remove the textarea once finished
document.body.appendChild(txt);
Bookmarklet (I have slightly adjusted the code to be compact):
javascript:void(function(){var t=document.createElement("textarea");t.style.cssText = "width:99%;height:99%;position:fixed;z-index:999;top:0;left:0";t.value=document.documentElement.innerHTML;txt.ondblclick=function(){t.parentNode.removeChild(t)};document.body.appendChild(t)})()
*
*Focus the generated textarea
*Manually add the DOCTYPE + <html> tags
*Copy the contents of the textarea to the validator at: http://validator.w3.org/#validate-by-input
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JS/CSS - Show semi-transparent layer over webpage for JS disabled users My Description
I have a website application that relies heavily on Javascript and JQuery. If the user has JS disabled in their browser settings, the website does not function as well as it should, although it still works.
I would like to stop people seeing my website that have JS disabled, but without redirecting them to a non-javascript page. I would like to alert my user that JS should be enabled in a well presented CSS method.
If JS is disabled, I would like to show a semi-transparent/white CSS layer, displayed on top of my webpage with a width of 100% and a height of 100%, with some kind words to describe the issue to my user, and possibly instructions to enable JS.
My Plan
*
*Have a semi-transparent CSS layer 100% x 100% to cover my webpage, on
every page.
*Have an on-load Javascript function, that when the page loads, it
removes the layer. So if there is no Javascript found, it won't
remove the layer.
My Question
Is this the best way to accomplish this? If it is, can you help me with the Javascript function that would close the CSS layer, on-load, or explain to me what the function should include to make this work? My Javascript sucks...
A: Add the layer in a noscript tag, and style the noscript tag, add your text in the noscript tag.
#noscript {top:0; left:0; height:100%; width:100%; opacity: 0.5; background: white;}
A: That sounds like a workable solution.
Hiding the layer is pretty simple.
$(function () {
$("#layerId").hide();
});
Setting up the layer so it looks right is where the work really is.
A: Put your HTML markup for the disabled warning in the <noscript> tag, then style as desired.
W3Schools
A: A common technique for this kind of thing (Modernizr uses this approach) is to do something like the following.
Start with this in your CSS...
#my-warning-message {display:block; width:...}
.js #my-warning-message {display:none;}
Then, in your JS...
$('html').addClass('js');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the difference between setattr() and object.__setattr__()? I know that you can't call object.__setattr__ on objects not inherited from object, but is there anything else that is different between the two? I'm working in Python 2.6, if this matters.
A: Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that.
Original Answer*
setattr(instance, name, value) is syntactic sugar for instance.__setattr__(name, value)**.
You would only need to call object.__setattr__(...) inside a class definition, and then only if directly subclassing object -- if you were subclassing something else, Spam for example, then you should either use super() to get the next item in the heirarchy, or call Spam.__setattr__(...) -- this way you don't risk missing behavior that super-classes have defined by skipping over them directly to object.
* applies to Python 3.0+ classes and 2.x new-style classes
**There are two instances where setattr(x, ...) and x.__setattr__(...) are not the same:
*
*x itself has a __setattr__ in it's private dictionary (so x.__dict__[__setattr__] = ... (this is almost certainly an error)
*x.__class__ has a __getattribute__ method -- because __getattribute__ intercepts every lookup, even when the method/attribute exists
NB
These two caveats apply to every syntactic sugar shortcut:
*
*setattr
*getattr
*len
*bool
*hash
*etc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Is it possible to mask a View in android? Is it possible to mask views? For example, if I have a design that calls for a List View to be visible within an oval shaped opening. Is there a way to create a mask for a view? Is it called something else? Because all the references I find to masking in the android docs are talking about masking a canvas object or drawable. But I don't think making a drawable of an interactive object like a list View would be a good approach. Is this just a limitation to deal with for now?
A: Yes, it is - you have to override the drawing method of your view - i.e:
......
final Path path = new Path();
path.addRoundRect(new RectF(0,0,getWidth(),getHeight()),10,10,Direction.CW);
......
@Override
protected void dispatchDraw(Canvas canvas){
canvas.clipPath(path);
super.dispatchDraw(canvas);
}
this will draw your view only in the boundaries set by path.
A: Yes, you can even mask complete layouts.
Shameless selfplug
<com.christophesmet.android.views.maskableframelayout.MaskableFrameLayout
android:id="@+id/frm_mask_animated"
android:layout_width="100dp"
app:porterduffxfermode="DST_IN"
app:mask="@drawable/animation_mask"
android:layout_height="100dp">
<ImageView android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/unicorn"/>
You can find it here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Rails 2.3.5 having trouble with form_for and fields_for I am trying to add addresses to a user model via a form submit but i am having trouble. A user:
class User < ActiveRecord::Base
has_many :addresses
end
can add an address to his account via the accounts page, which is controlled by the accounts controller.
class AccountsController < ApplicationController
def addresses
@user = current_user
@addresses = @user.addresses
default_country = Country.find Spree::Config[:default_country_id]
@countries = Checkout.countries.sort
@states = default_country.states.sort
end
end
In the view "/accounts/addresses", i have a form that I am trying to submit:
<% form_for @user do |user_form| %>
<% user_form.fields_for :address do |address_form| %>
<%= address_form.text_field :firstname, :class => 'required', :value=>"" -%>
<%= address_form.text_field :lastname, :class => 'required', :value=>"" -%>
<%= address_form.text_field :business_name, :class => 'required', :value=>"" -%>
<%= address_form.text_field :address1, :class => 'required', :value=>"" -%>
<%= address_form.text_field :address2, :value=>"" %>
<%= address_form.text_field :city, :class => 'required', :value=>"" -%>
...
<%= address_form.submit %>
<% end -%>
<% end %>
I am looking at the one-to-many fields_for code here:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
but the problem is i have multiple addresses but only want to submit one address at a time. What do i need to add to the user/address model and/or accounts controller so I can successfully create an address and add it to the user model when I submit that form? If there is an easier way to accomplish this, please let me know.
A: You need accepts_nested_attributes_for
class User < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
And your form could be
<% form_for @user do |user_form| %>
<% user_form.fields_for :addresses do |address_form| %>
<%= address_form.text_field :firstname, :class => 'required' -%>
<%= address_form.text_field :lastname, :class => 'required' -%>
<%= address_form.text_field :business_name, :class => 'required' -%>
<%= address_form.text_field :address1, :class => 'required' -%>
<%= address_form.text_field :address2 %>
<%= address_form.text_field :city, :class => 'required' -%>
...
<%= address_form.submit %>
<% end -%>
<% end %>
This would let you edit all existing addresses, if you need to add 1 to the list, you could
@user.addresses.build in your controller action to populate an empty one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FileSystemWatcher C# permission problem I'm over a domain, reading the path \\machinecap\platform\in.
The platform is a share, wich leads to E:\cappuccino\platform locally. The application is a Windows Service made in C# .NET 2.0, wich make use of FileSystemWatcher to read the path \\machinecap\platform\in for files created and renamed.
I have "Full Control" permissions since \\machinecap\platform (including all sub-dirs), but only this, no access to any folder else in the server (is a Windows Server 2003).
The problem is that when a file arrives at the server, the service fall down, and no (descent) message is logged in Event Viewer. Trying to trace the problem, I made a loggon in the server and tried to run mannually all the steps that the application does. I can create files in the "in" folder, however I cannot delete these files... a error message is shown: "E:\ is not accessible. Access is denied."
Of course I don't have any access to E:\ root folder, only to E:\cappuccino\platform... is this the problem? Do I really have to give read access to E:\ in order I can read E:\cappuccino\platform?
MORE INFO
Exception message:
Unhandled Exception: System.BadImageFormatException: Could not load file or assembly 'Oracle.DataAccess, Version=2.112.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies.
An attempt was made to load a program with an incorrect format.
File name: 'Oracle.DataAccess, Version=2.112.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342'
at TestRiskStore.ArisReportReader.CreateOrRename(Object source, FileSystemEventArgs e)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Please note that I'm using Oracle.DataAccess component.. I think the problem is related to this, not sure.... any idea how to solve this problem?
A: I've found the problem: my machine is 32 bits, the server is 64 bits, and I was compiling the application to run on any platform. The problem is that the OracleDataAccess components that it was installed on the server is for 32 bits, so the assemblies were installed only on GAC_32 folder. Thus when the application try to run on 64 bits mode it doesn't find the assemblies.
So I just recompiled the application as x86 (32 bits), and it worked. Now the application runs on 32 bit mode and it look for the assemblies in the correct folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NHibernate on DB2 session.get() throws System.IndexOutOfRangeException I'm following the NHibernate getting started tutorial: "Your first NHibernate based application". I'm at the point where I create a Product object then use Session.get() to prove I can read the object.
It works fine with SQL Server Ce, but I'm getting an exception when I try to use DB2. (The SQL Server Ce version works - that is. There are some minor changes between the versions like int instead of GUID for the Id.)
I'm very experienced with Hibernate and SQL databases. This is my first experience with NHibernate and DB2. (Coming from the Java world). I'd appreciate any suggestions, especially from the (evidently few) people who are using NHibernate on DB2.
Rob
The full exception is
Test method Examples.DB2.NHibernateExamples.Can_add_new_product threw
exception: NHibernate.Exceptions.GenericADOException: could not load
an entity: [Examples.DB2.Domain.Product#1][SQL: SELECT product0_.Id as
Id1_0_, product0_.Name as Name1_0_, product0_.Category as
Category1_0_, product0_.Discontinued as Disconti4_1_0_ FROM Product
product0_ WHERE product0_.Id=?] ---> System.IndexOutOfRangeException:
Invalid index 0 for this DB2ParameterCollection with Count=0.
This is happening in the Get(...) call in the following code:
[TestInitialize]
public void TestInitialize()
{
TestFixtureSetup();
SetupContext();
}
[TestMethod]
public void Can_add_new_product()
{
var product = new Product { Id = 1, Name = "Apple", Category = "Fruits"};
using (ISession session = _sessionFactory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(product);
transaction.Commit();
}
}
using (ISession session = _sessionFactory.OpenSession())
{
//var query = session.CreateQuery("from Product");
//var products = query.List<Product>();
//Assert.AreEqual(1, products.Count);
var fromDb = session.Get<Product>(product.Id);
Assert.IsNotNull(fromDb);
Assert.AreNotSame(product, fromDb);
Assert.AreEqual(product.Name, fromDb.Name);
Assert.AreEqual(product.Category, fromDb.Category);
}
}
private void TestFixtureSetup()
{
_configuration = new Configuration();
_configuration.Configure();
_configuration.AddAssembly(typeof (Domain.Product).Assembly);
_sessionFactory = _configuration.BuildSessionFactory();
}
private void SetupContext()
{
new SchemaExport(_configuration).Execute(true, true, false);
}
The exception seems to indicate that the Id paramter isn't being passed to the DB2 query. If I uncomment the three lines before the Get(), it works fine since the row is already cached and the Get() doesn't actually go to the database.
Here is the definition of Product.cs:
using System;
namespace Examples.DB2.Domain
{
class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Category { get; set; }
public virtual bool Discontinued { get; set; }
}
}
Here is Product.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Examples.DB2"
namespace="Examples.DB2.Domain">
<class name="Product">
<id name="Id">
<generator class="native" />
</id>
<property name="Name" />
<property name="Category" />
<property name="Discontinued" type="YesNo"/>
</class>
</hibernate-mapping>
Here is hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.DB2Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.DB2Driver</property>
<property name="connection.connection_string">Database=SAMPLE; UID=DEV; PWD=password</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
I'm working in Visual Studio 2010 Premium on Windows 7. I'm using DB2 Express-C 9.7.4.
A: Ok,
I found the answer ... not exactly sure of the solution yet, but in the final release of NHibernate they added a call to AdoNet\AbstractBatcher.cs called RemoveUnusedCommandParameters. This procedure calls Driver.RemoveUnusedCommandParameters.
My solution for now is just to comment out this call and let the function do nothing.
I will bring this up with the nhusers group and see if there is a better long term solution.
thanks
dbl
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What's a good pattern for a java unit test that ensures that you are properly closing files? I have an issue in my codebase where we are not properly closing file handles, or probably streams. We eventually get a TooManyOpenFiles exception under very heavy load. Based on the output of lsof, we are pretty sure we know where the leak is (in our logging system), but my question is: how can I write a unit test that checks, when it's complete, that resources have been closed properly? Is there a way to query the JRE to find out how many files are currently open? Can I somehow intercept file operations so I can monitor them?
I suspect I will have to instrument my code in order to manage all the file I/O, count references, and make sure they are getting closed that way, but if anyone knows of a top-down solution akin to those ideas I mentioned above, that would be a huge help!
A: You can use aspect-oriented programming (AOP) tool like AspectJ to add code to count open/closed files to FileInputStream and FileOutputStream. This is fairly easy to do (details depend on the tool, of course) robust and noninvasive.
A: Since you are talking about Tests, PowerMock http://code.google.com/p/powermock/ might do the trick. It makes it possible to mock static methods and constructors if I am not mistaken. So you could mock/spy on the constructors and on the close methods or what ever you need for freeing the resources.
I try to avoid it in my tests but in the case which you describe it might be worth the hassle.
A: Looks like you can watch this via JMX.
Someone posted code here:
http://java-monitor.com/forum/showthread.php?t=130
You'll have to enable JMX in your JVM if you haven't already.
A: You could write your own "library" for the normal IO classes, FileInputStream, etc. That tracks (in test) what caller opened it, if it's still open, a global list, etc. Have it wrap a "real" FileInputStream.
Then use that everywhere in your code instead of a "normal" FileInputStream et al.
Then at the end of your unit test you assert WrappedFileInputStreams.assertAllWereClosed or what have you.
Another option would be to write your methods so they accept FileinputStream as a parameter somehow, then call them, then assert your parameter comes out "closed now" after the method ends.
Or if you know you'll be on linux, do a system call to lsof and it should not list any files as location '(deleted)'. https://unix.stackexchange.com/a/64737/8337
For some reason on OS X it's not that easy, it doesn't show "(deleted)" but you could still detect if the file is gone by looping over lsof -p ... and checking if each file is actually there on the file system...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Why do I need to turn off security validation? I'm working on building a webpart that creates a site, adds some lists based on user input, and sets the theme for the site. I can do this whole operation from a console app running on the server just fine, but when I do this from the webpart I get a secrutiy validation error when I try to set the theme. I can get around this by turning off security validation for the entire web app through central admin, but I'd rather not go down that route. This is currently what I'm running -
SPSecurity.RunWithElevatedPrivileges(delegate()
{
newWeb = web.Webs.Add(siteName, siteName, description, 1033, "STS#1", true, false);
newWeb.AllowUnsafeUpdates = true;
ReadOnlyCollection<ThmxTheme> managedThemes = null;
managedThemes = ThmxTheme.GetManagedThemes(newWeb.Site);
foreach (ThmxTheme theme2 in managedThemes)
{
if (theme2.Name == "oked")
{
theme2.ApplyTo(newWeb, true);
break;
}
}
});
I've tried several different flavors of this, but all with the same result. Thanks!
A: This can happen if you are doing update operation on GET request.
Did you check out this
http://blogs.technet.com/b/speschka/archive/2011/09/14/a-new-twist-on-an-old-friend-quot-the-security-validation-for-this-page-is-invalid-quot-in-sharepoint-2010.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails console log - how to customize what is printed in the console When I run rails s it loads up and everything works. When I browse to a page several lines of information are printed. Mostly this is the webpage getting the assets for the page. I really don't need to see this and have it clutter my screen. Is there a way to customize what gets printed in console?
Thanks
A: For assets pipeline messages it seems that you can't (yet). See How to disable logging of asset pipeline (sprockets) messages in Rails 3.1? and the rails issue on Github
You can do it in part by using these lines (credits) in your development.rb file
config.after_initialize do |app|
app.assets.logger = Logger.new('/dev/null')
end
A: For Rails 3.1, inside config/environments/development.rb, set the following to false:
config.assets.debug = false
Your logs will show you everything you want to see minus the assets.
A: You can configure the logging detail of the rails dev server by setting config.log_level in environments/development.rb. Setting it to :warn will get rid of most of the logging (you can always send your own messages with whatever log level you want so they still get printed).
http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels
http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: how to pass a parameter to actionlink from a script I have a script:
function FindSerial() {
var textBoxValue = $("#clientSerial1").val();
return textBoxValue;
};
My actionlink is :
@Html.ActionLink("talks", "ClientTalks", "Talk", new { id ="FindSerial()" }, null)
I want to use the function in order to get id ; how can it be done?
A: @Jalai Amini is right. You will need to handle it with jquery. Something like this:
@Html.ActionLink("talks", "ClientTalks", "Talk", new { id="talklink"})
<script>
$(function () {
$('#talklink').click(function () {
document.location.href = $(this).attr("href") + "?id=" + FindSerial();
}
});
</script>
Something to consider:
In this way you are creating the url in the client side, so it can't use the mvc routes. In my example, it will be putting the id as a querystring parameter, but it could be another thing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are CSS selectors case-sensitive? I was recently updating a CMS site and a tab-navigation plugin had inserted the following markup:
<li id="News_tab">...
I've always written my CSS selectors in lowercase so when I tried to style this with #news_tab, it wouldn't apply, but #News_tab worked.
After all these years I'm surprised that I haven't run into this before, so I've always been under the impression that CSS was case-insensitive. Has CSS always been case-sensitive and I just haven't noticed thanks to my consistent code style?
A: Class and ID attributes are case sensitive.
A: CSS itself is case insensitive, but selectors from HTML (class and id) are case sensitive:
CSS recommendation on case sensitivity
HTML recommendation, id attribute (note the [CS])
A: http://www.w3.org/TR/CSS2/syndata.html
All CSS syntax is case-insensitive within the ASCII range (i.e., [a-z] and [A-Z] are equivalent), except for parts that are not under the control of CSS
From the docs website.
Follow-up for selectors:
http://www.w3.org/TR/CSS2/selector.html
The case-sensitivity of document language element names in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML they are case-sensitive.
A: CSS4 (CSS Selector Level 4) adds support for case-insensitive match (ASCII only).
input[value='search' i]
It's the "i" at the end which would do the trick...
Check my other answer for details which browser supports this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: SQL: Matching multiple columns value I have a database set up so that the username (username) and id (id) are stored in the members table.
I have another table that records reports and I record each column in the table (fid), who reported it (rid) and who they were reporting (id) which both match to the user's id in the members table.
How could I get a query to pull the username for both the rid and id?
My current query is
SELECT selfreport.fid, selfreport.rid,
selfreport.id, members.username as username
FROM members, selfreport
WHERE members.id = selfreport.id
ORDER BY fid
but this only gets the username for who they were reporting. How can I get it to pull the username for both?
A: You need to join to your members table twice. Try something like this:
SELECT selfreport.fid,
selfreport.rid,
selfreport.id,
COALESCE(WhoReported.username, 'Not Specified') AS WhoReportedUN,
COALESCE(ReportedTo.username, 'Not Specified') AS ReportedToUN
FROM selfreport
LEFT JOIN members WhoReported ON WhoReported.id = selfreport.id
LEFT JOIN members ReportedTo ON ReportedTo.id = selfreport.rid
ORDER BY fid
A: You need to join members twice:
SELECT selfreport.fid,
selfreport.rid,
selfreport.id,
m1.username AS ReportToUsername,
m2.username AS ReporteeUsername
FROM selfreport
INNER JOIN members m1
ON m1.id = selfreport.id
INNER JOIN members m2
ON m2.id = selfreport.rid
ORDER BY fid
Since you were doing an implicit join in your original query, I believe INNER JOIN will suit you well. However, if it's possible to have null values in selfreport.id or selfreport.rid, you should use LEFT JOIN instead.
A: Do not use implicit SQL '89 joins they are an antipattern.
Use explicit join syntax instead.
SELECT s.fid, s.rid, s.id, m1.username as username, m2.username as rusername
FROM selfreport S
INNER JOIN members m1 ON (m1.id = s.id)
INNER JOIN members m2 ON (m2.id = s.rid)
ORDER BY s.fid
If id or rid is optional, use a left join.
SELECT
s.fid, s.rid, s.id
, COALESCE(m1.username, 'nobody') as username
, COALESCE(m2.username, 'nobody') as rusername
FROM selfreport S
LEFT JOIN members m1 ON (m1.id = s.id)
LEFT JOIN members m2 ON (m2.id = s.rid)
ORDER BY s.fid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Spring Request Mapping Mis I am using Spring mapping. And have the following mapping code. The problem is there are like 20 possible misspelling for these and others that need to be accounted for. Rather than add a RequestMapping for each url which would be like 30 or 40, is there a way to simply redirect these. I know the way I am doing is not clean and would appreciate advice on how to keep my request mappings to a minium. Thanks.
@RequestMapping("/protect")
public String protect(Model model) {
QuickResponse qr = createQR();
model.addAttribute("qr", qr);
return "qr_general";
}
A: I am unsure as to what can be misspelled, but I am thinking you are referring to the path that is being mapped to.
The @RequestMapping annotation's default value member takes String[], so you should be able to put all of your mappings in one location:
@RequestMapping({"/protect", "/protekt", "/proteckt", "/protext"})
public String protect(Model model) {
QuickResponse qr = createQR();
model.addAttribute("qr", qr);
return "qr_general";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem adding to ListView within a Relative layout I'm fairly new to android development and I'm having some issues adding an item to the ListView I have. The application is suppose to, upon clicking the "Add" button, bring up a EditText that takes in the name of the class then it is suppose to add to the list the class name. The problem I'm running into is after I finish entering the class name and try to hit Add (My positiveButton of my AlertDialog.Builder) it does a force close. This is the code I have so far:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:text="Add Class"
android:layout_width="wrap_content"
android:id="@+id/addClassBtn"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="wrap_content"
android:id="@+id/removeClassBtn"
android:text="Remove Class"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/addClassBtn"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/classList"
android:layout_below="@+id/addClassBtn"
android:layout_alignParentLeft="true"
/>
</RelativeLayout>
and my java file:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button add = (Button)findViewById(R.id.addClassBtn);
@SuppressWarnings("unused")
final Button remove = (Button)findViewById(R.id.removeClassBtn);
final EditText et = new EditText(getApplicationContext());
final ListView lv = (ListView)findViewById(R.id.classList);
final AlertDialog alert;
final ArrayList<String> classes = new ArrayList<String>();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, R.id.classList, classes);
lv.setAdapter(adapter);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(et);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
classes.add(et.getText().toString());
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alert = builder.create();
add.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
alert.show();
}
});
}
Any suggestions as to what I'm doing wrong or a possible fix would be greatly appreciated.
Here is the logcat of what happens:
09-26 18:12:14.345: DEBUG/AndroidRuntime(879): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
09-26 18:12:14.357: DEBUG/AndroidRuntime(879): CheckJNI is ON
09-26 18:12:14.455: DEBUG/AndroidRuntime(879): --- registering native functions ---
09-26 18:12:14.915: INFO/ActivityManager(58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.ClassList/.ClassListMCPActivity }
09-26 18:12:14.935: INFO/ActivityManager(58): Start proc com.example.ClassList for activity com.example.ClassList/.ClassListMCPActivity: pid=885 uid=10036 gids={}
09-26 18:12:14.985: DEBUG/AndroidRuntime(879): Shutting down VM
09-26 18:12:14.985: DEBUG/dalvikvm(879): Debugger has detached; object registry had 1 entries
09-26 18:12:14.995: INFO/AndroidRuntime(879): NOTE: attach of thread 'Binder Thread #3' failed
09-26 18:12:15.745: INFO/ActivityManager(58): Displayed activity com.example.ClassList/.ClassListMCPActivity: 817 ms (total 817 ms)
09-26 18:12:20.915: DEBUG/dalvikvm(258): GC_EXPLICIT freed 71 objects / 3424 bytes in 101ms
09-26 18:12:25.996: WARN/KeyCharacterMap(885): No keyboard for id 0
09-26 18:12:25.996: WARN/KeyCharacterMap(885): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
09-26 18:12:28.905: DEBUG/dalvikvm(226): GC_EXPLICIT freed 100 objects / 4168 bytes in 107ms
09-26 18:12:29.766: DEBUG/AndroidRuntime(885): Shutting down VM
09-26 18:12:29.766: WARN/dalvikvm(885): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): FATAL EXCEPTION: main
09-26 18:12:29.775: ERROR/AndroidRuntime(885): java.lang.NullPointerException
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:353)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.AbsListView.obtainView(AbsListView.java:1315)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.ListView.onMeasure(ListView.java:1109)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.View.measure(View.java:8171)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.RelativeLayout.measureChild(RelativeLayout.java:563)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:378)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.View.measure(View.java:8171)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.View.measure(View.java:8171)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.View.measure(View.java:8171)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.View.measure(View.java:8171)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.os.Looper.loop(Looper.java:123)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at java.lang.reflect.Method.invoke(Method.java:521)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-26 18:12:29.775: ERROR/AndroidRuntime(885): at dalvik.system.NativeStart.main(Native Method)
09-26 18:12:29.785: WARN/ActivityManager(58): Force finishing activity com.example.ClassList/.ClassListMCPActivity
09-26 18:12:30.327: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{44fd7988 com.example.ClassList/.ClassListMCPActivity}
09-26 18:12:40.979: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{44fd7988 com.example.ClassList/.ClassListMCPActivity}
09-26 18:12:45.955: INFO/Process(885): Sending signal. PID: 885 SIG: 9
09-26 18:12:45.965: INFO/ActivityManager(58): Process com.example.ClassList (pid 885) has died.
09-26 18:12:45.965: INFO/WindowManager(58): WIN DEATH: Window{44fcdd78 com.example.ClassList/com.example.ClassList.ClassListMCPActivity paused=false}
09-26 18:12:45.965: INFO/WindowManager(58): WIN DEATH: Window{4501a6a0 com.example.ClassList/com.example.ClassList.ClassListMCPActivity paused=false}
09-26 18:12:45.995: WARN/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 885 uid 10036
09-26 18:12:48.557: WARN/KeyCharacterMap(115): No keyboard for id 0
09-26 18:12:48.557: WARN/KeyCharacterMap(115): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
A: the issue is related to the adapter. Take a look at this example
android helloview
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Handling hardware resources when testing with Jenkins I want to setup Jenkins to
1) pull our source code from our repository,
2) compile and build it
3) run the tests on an embedded device
step 1 & 2 are quite easy and straight forward with Jenkins
as for step 3,
we have hundreds of those devices in various versions of them, and I'm looking for a utility (preferable in python) that can handle the availability of hardware devices/resources.
in such manner that one of the steps will be able to receive which of the device is available and run the tests on it.
A: What I have found, is that the best thing to do, is have something like jenkins, or if you're using enterprise, electric commander, manage a resource 'pool' the pool is essentially virtual devices, but they have a property, such that you can call into a python script w/ either an ip-address or serial port and communicate w/ your devices.
I used it for automated embedded testing on radios. The python script managed a whole host of tests, and commander would go ahead and choose a single-step resource from the pool, that resource had an ip, and would pass it into the python script. test would then perform all the tests and the stdout would get stored up into commander/jenkins ... Also set properties to track pass/fail count as test was executing
//main resource gets single step item from pool, in the main resource wrote a tiny script that asked if the item pulled from the pool had the resource name == "Bench1" .. "BenchX" etc.
basically:
if resource.name=="BENCH1":
python myscript.py --com COM3 --baud 9600
...
etc.
the really great feature about doing it this way, is if you have to disconnect a device, you don't need to deliver up script changes, you simply mark the commander/jenkins resource as disabled, and the main 'project' can still pull from what remains in your resource pool
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Edit of Javascript required to add fade in/fade out effect please Is it possible to add a fade in fade out effect to this javascript? At the moment it just loads an image to another div upon hover of first div but with no effect. Thanks in advance.
<script language="javascript" type="text/javascript">
function changeDisplay(bgImageURL)
{
var displayDiv = document.getElementById("displayDiv");
// draw popup image in the div
displayDiv.innerHTML =
'<a class="popup1" href="#v"><img src="' + bgImageURL+ '" alt="" /></a>';
// show the display in case it was hidden before
displayDiv.style.visibility = "visible";
}
function hideDisplay()
{
var displayDiv = document.getElementById("displayDiv");
// hide it when the mouse rolls off the thumbnail
displayDiv.style.visibility = "hidden";
}
</script>
A: Using jQuery
http://api.jquery.com/fadeIn/
<div id="fade"></div> <!-- make sure this is initially hidden -->
<script type="text/javascript">
$('#fade').fadeIn('slow', function() {
// When animation is complete, it runs this function
});
</script>
fadeOut: http://api.jquery.com/fadeOut/
A: simple change in your existing code
include jquery plugin before your javascript code and change
display function
displayDiv.style.visibility = "visible"; to displayDiv.fadeIn('slow');
hide function
displayDiv.style.visibility = "visible"; to displayDiv.fadeOut();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic Sieve Algorithms for Prime Generation I'm implementing the Sieve of Eratosthenes, for an explanation of this see http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. However I would like to adapt it to generate M primes, not the primes 1 through N. My method of doing this is simply to create a large enough N such that all M primes are contained in this range. Does anyone have any good heuristics for modeling the growth of primes? In case you wish to post code snippets I am implementing this in Java and C++.
A: To generate M primes, you need to go up to about M log M. See Approximations for the nth prime number in this Wikipedia article about the Prime Number Theorem. To be on the safe side, you might want to overestimate -- say N = M (log M + 1).
Edited to add: As David Hammen points out, this overestimate is not always good enough. The Wikipedia article gives M (log M + log log M) as a safe upper bound for M >= 6.
A:
This approximation of the nth prime is taken from wikipedia; therefore you'll just need to allocate an array of m*log(m)+m*log(log(m)); an array of m*log(m) will be unsufficient.
A: Another alternative is a segmented sieve. Sieve the numbers to a million. Then the second million. Then the third. And so on. Stop when you have enough.
It's not hard to reset the sieve for the next segment. See my blog for details.
A: Why not grow the sieve dynamically? Whenever you need more primes, re-allocate the seive memory, and run the sieve algorithm, just over the new space, using the primes that you have previously found.
A: Lazy evaluation comes to mind (such as Haskell and other functional languages do it for you). Although you a writing in an imperative language, you can apply the concept I think.
Consider the operation of removing the remaining cardinal numbers from the candidate set. Without actually touching the real algorithm (and more importantly without guessing how many numbers you will create), execute this operation in a lazy manner (which you will have to implement, because you're in an imperative language), when and if you try to take the smallest remaining number.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Concurrency accessing a shared resource I am writing a Java application, that access to a configuration file stored as a shared resource in a Windows server. The app is thought to be used by around 500 employees, so it made me think about concurrency.
Related to the implementation, I access to the file through JCIFS library, then I used an inputStream to read and treat it. I guess VM have nothing to do with this nor application code, so I point out to the OS, in this case windows.
I don't know where or how must be treated this issue or even if I have to.
In other hand, we are talking about a remote file, but what happens if the file is located in our filesystem? In this case, VM has something to say hasn't it? How many different input streams can be opened over a file? and output streams?
I know that these are not concrete questions, so it must be difficult to answer them. But any help, comment or advices would be very appreciated.
Thanks in advance!!
A:
In other hand, we are talking about a remote file, but what happens if the file is located in our filesystem?
Its still an InputStream.
In this case, VM has something to say hasn't it?
It can if you want to, but generally not.
How many different input streams can be opened over a file?
Limited by the OS, usually thousands.
and output streams?
The same. But if you write to a file with more than one process the results could be a mess, but you are more likely to get the output from just one program. (But you wouldn't know which without re-reading it)
A: Is the file going to be written to while your application is consuming it? If its not then I can't imagine it being a problem. Think about multiple editors with the same file open at the same time - no harm no foul till someone makes a change and writes it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Segmentation fault Here is my code.
#include<stdio.h>
int main(int argc,char** argv)
{
FILE* fp;
fp=fopen(argv[1],"r");
struct element{
int value;
char activity;
};
typedef struct element element;
element a;
printf("%d",feof(fp));
}
Now if I don't give the last printf command it does not give me a segmentation fault, but if I give it printf it gives me a seg fault. Why?
I got the answer to my prev problem, now i have another problem
i had .txt appended to my input file in my makefile. Now i have another problem. on command make it gives error.
0make: *** [a.out] Error 1
why?
A: Check the return value of fopen (well, check the return value of any call), it probably failed to open the file.
A: Because you do not specify the file in a command line arguments, or because the file you have specified there could not be opened for some reason. In that case, fopen returns NULL, and when you pass that NULL to feof it crashes the program. You have to check return values and error codes, especially when functions may return NULL.
The correct code may look something like this:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
FILE *fp;
if (argc < 2)
{
fprintf (stderr, "Please specify the file name.\n");
return EXIT_FAILURE;
}
fp = fopen(argv[1], "r");
if (fp == NULL)
{
perror ("Cannot open input file");
return EXIT_FAILURE;
}
printf ("%d\n", feof (fp));
return EXIT_SUCCESS;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Make a custom java object Parcelable in Android I am trying to send an object of type MyCustomObject to another activity via an intent. I know, to make the class Parcelable, I should do public class MyCustomObject implements Parcelable, but I am not sure how custom object arrays work in parcelable. Here's what I have got so far.. Also, do I need to make the Search class implements Parcelable too?
Here is my updated answer I now get a null object when I do intent.getParcelableExtra(search). Maybe I am not creating the search array properly?
public class MyCustomObject implements Parcelable{
public Search search[];
public MyCustomObject(Parcel in){
in.readArray(MyCustomObject.class.getClassLoader());
}
@Override
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags){
dest.writeArray(search)
}
public static final Parcelable.Creator<MyCustomObject> CREATOR = new Parcelable.Creator<MyCustomObject>(){
@Override
public MyCustomObject createFromParcel(Parcel source){
return new MyCustomObject(source);
}
@Override
public MyCustomObject[] newArray(int size){
return new MyCustomObject[size];
}
}
public static class Search implements Parcelable{
public int rank;
public String title;
public String[] imageURL;
public Search(Parcel in){
rank = in.readInt();
title = in.readString();
String[] url = new String[4];
in.readStringArray(url);
url = imageURL
}
@Override
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags){
dest.writeInt(rank);
dest.writeString(title);
dest.writeStringArray(imageURL);
}
public static final Parcelable.Creator<Search> CREATOR = new Parcelable.Creator<Search>(){
@Override
public Search createFromParcel(Parcel source){
return new Search(source);
}
@Override
public Search[] newArray(int size){
return new Search[size];
}
}
}
}
A: A couple of things. First, your Search object will need to implement Parcelable as well. Next, you need to create a static field called CREATOR that implements Parcelable.Creator<MyCustomObject>. This will have a method called createFromParcel that returns an instance of MyCustomObject. That is where you read data out of a parcel and create a new instance of MyCustomObject. This is essentially the opposite of writeToParcel. This all applies to Search as well since you must make it implement Parcelable. In summary:
*
*Make Search implement Parcelable
*Implement Search.writeToParcel
*Create a static field in Search called CREATOR that implements Parcelable.Creator<Search>
*Implement the createFromParcel method of Search.CREATOR
*Create a static field in MyCustomObject called CREATOR that implements Parcelable.Creator<MyCustomObject>
*Implement the createFromParcel method of MyCustomObject.CREATOR
A: when you readArray from Parcel, you want to read a Search[] array. Not the MyCustomObject.
public MyCustomObject(Parcel in){
in.readArray(MyCustomObject.class.getClassLoader());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: matplotlib strings as labels on x axis I am building a small tool for data analysis and I have come to the point, where I have to plot the prepared data. The code before this produces the following two lists with equal length.
t11 = ['00', '01', '02', '03', '04', '05', '10', '11', '12', '13', '14', '15', '20', '21', '22', '23', '24', '25', '30', '31', '32', '33', '34', '35', '40', '41', '42', '43', '44', '45', '50', '51', '52', '53', '54', '55']
t12 = [173, 135, 141, 148, 140, 149, 152, 178, 135, 96, 109, 164, 137, 152, 172, 149, 93, 78, 116, 81, 149, 202, 172, 99, 134, 85, 104, 172, 177, 150, 130, 131, 111, 99, 143, 194]
Based on this, I want to built a histogram with matplotlib.plt.hist. However, there are a couple of problems:
1. t11[x] and t12[x] are connected for all x. Where t11[x] is actually a string. It represents a certain detector combination. For example: '01' tells that the detection was made in the 0th segment of the first detector, and 1st segment of the second detector. My goal is to have each entry from t11 as a labeled point on the x axis. The t12 entry is going to define the hight of the bar above the t11 entry (on a logarithmic y axis)
How does one configure such an x axis?
2. This is all very new to me. I could not find anything related in the documentation. Most probably because I did not know what to search for. SO: Is there an "official" name for what I am trying to achieve. This would also help me alot.
A: Use the xticks command.
import matplotlib.pyplot as plt
t11 = ['00', '01', '02', '03', '04', '05', '10', '11', '12', '13', '14', '15',
'20', '21', '22', '23', '24', '25', '30', '31', '32', '33', '34', '35',
'40', '41', '42', '43', '44', '45', '50', '51', '52', '53', '54', '55']
t12 = [173, 135, 141, 148, 140, 149, 152, 178, 135, 96, 109, 164, 137, 152,
172, 149, 93, 78, 116, 81, 149, 202, 172, 99, 134, 85, 104, 172, 177,
150, 130, 131, 111, 99, 143, 194]
plt.bar(range(len(t12)), t12, align='center')
plt.xticks(range(len(t11)), t11, size='small')
plt.show()
A: For the object oriented API of matplotlib one can plot custom text on the x-ticks of an axis with following code:
x = np.arange(2,10,2)
y = x.copy()
x_ticks_labels = ['jan','feb','mar','apr']
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
# Set number of ticks for x-axis
ax.set_xticks(x)
# Set ticks labels for x-axis
ax.set_xticklabels(x_ticks_labels, rotation='vertical', fontsize=18)
A: In matplotlib lingo, you are looking for a way to set custom ticks.
It seems you cannot achieve this with the pyplot.hist shortcut. You will need to build your image step by step instead. There is already an answer here on Stack Overflow to question which is very similar to yours and should get you started: Matplotlib - label each bin
A: Firstly you need to access the axis object:
fig, ax = plt.subplots(1,1)
then:
ax.set_yticks([x for x in range(-10,11)])
ax.set_yticklabels( ['{0:2d}'.format(abs(x)) for x in range(-10, 11)])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
}
|
Q: How to insert circle on secon tab on tabfolder, how to access second tab how to draw a circle on second tab ? becouse i have, buttons on every tab, how i can sepperate them?
package shelllab;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final Display display = new Display();
final Shell shell = new Shell (display);
shell.setLayout(new FillLayout());
shell.setText("ShellExample");
shell.setSize(700,500);
final Color blue = display.getSystemColor(SWT.COLOR_BLUE);
Menu bar = new Menu (shell, SWT.BAR);
shell.setMenuBar (bar);
MenuItem f1 = new MenuItem (bar, SWT.CASCADE);
f1.setText ("&Файл");
MenuItem f2 = new MenuItem (bar, SWT.CASCADE);
f2.setText ("&О программе");
Menu s1 = new Menu (shell, SWT.DROP_DOWN);
f1.setMenu (s1);
MenuItem item = new MenuItem (s1, SWT.PUSH);
MenuItem item2 = new MenuItem (s1, SWT.PUSH);
MenuItem item3 = new MenuItem (s1, SWT.PUSH);
final TabFolder tabFolder = new TabFolder (shell, SWT.BORDER);
Rectangle clientArea = shell.getClientArea ();
tabFolder.setLocation (clientArea.x, clientArea.y);
tabFolder.setSize(400, 500);
for (int i=0; i<3; i++) {
TabItem item1 = new TabItem (tabFolder, SWT.NONE);
}
f2.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
MessageDialog.openWarning(shell, "Внимание", "Демонстрация работы с shell - лаба №2");
}
});
item.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
//System.exit(0);
GC gc = new GC(tabFolder);
Rectangle bounds = tabFolder.getBounds();
gc.setBackground(display.getSystemColor(SWT.COLOR_CYAN));
gc.fillOval(50,50,200,200);
}
});
item2.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
tabFolder.getItem(0).setText("This is example 1");
Button b1 = new Button(tabFolder, SWT.PUSH);
b1.setSize(180, 40);
b1.setText("Выбрать цвет для tabfolder2");
b1.setLocation(5, 25);
Button b12 = new Button(tabFolder, SWT.PUSH);
b12.setSize(180, 40);
b12.setText("Выбрать цвет для tabfolder3");
b12.setLocation(5, 80);
final Combo c = new Combo(tabFolder, SWT.READ_ONLY);
c.setBounds(250, 35, 100, 20);
String items[] = { "red", "blue", "green"};
c.setItems(items);
final Combo c2 = new Combo(tabFolder, SWT.READ_ONLY);
c2.setBounds(250, 90, 100, 20);
String items2[] = { "red", "blue", "green"};
c2.setItems(items2);
b1.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
//tabFolder.setForeground(blue);
if (c.getText().equals("red"))
{
//tabFolder.getItem(2).setControl(tabFolder);
}
}
});
//tabFolder.getItem(0).setData(b1);
}
});
item.setText("Выход Ctrl+Q");
item.setAccelerator (SWT.MOD1 + 'Q');
item2.setText("Пример №1 Ctrl+1");
item2.setAccelerator (SWT.MOD1 + '1');
item3.setText("Пример №2 Ctrl+2");
item3.setAccelerator (SWT.MOD1 + '2');
tabFolder.getItem(0).setText("Example1");
tabFolder.getItem(1).setText("Example2");
tabFolder.getItem(2).setText("Example3");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
how to draw a circle on second tab ? because i have, buttons on every tab, how i can separate them?
is it any, SWT "form designer" for free downloading?
this is filling :
GC gc = new GC(tabFolder);
Rectangle bounds = tabFolder.getBounds();
gc.setBackground(display.getSystemColor(SWT.COLOR_CYAN));
gc.fillOval(50,50,200,200);
A: There aren't lot of SWT designers, but WindowBuilder pro is a good choice (and it's free).
To second part of your question, check SWT documentation for TabFolder, especially the methods
TabItem[] getItems() - returns an array of TabItems which are the items in the receiver
TabItem[] getSelection() - returns an array of TabItems that are currently selected in the receiver
TabItem getItem(int index) - returns the item at the given, zero-relative index in the receiver
By those you can obtain the TabItem you want (e.g. the second tab), and then use it for your GC instance creation. Your circle will then be only on selected tab..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Most efficient jQuery selectors Which of the following selectors is most efficient in jQuery? Or is there any real difference?
*
*input[type=text]
*[type=text]
*input:text
*:text
Of course, an ID selector on the element would be best because the interpreter can use getElementById(), but I'm trying to understand the general differences in the above selectors.
A: Here's a quick test case I set up (note that I've added the necessary quotes around the attribute name selectors). It looks like the first method is fastest, which is expected really (because the others imply a universal * selector), followed by [type='text'], and in last place is :text.
In reality, the difference is so minimal it doesn't really matter which you choose.
Here's a screenshot (edit - I've added in the 4th method after seeing the update to the question):
A: Breaking it down:
input[type=text]
// and
[type=text]
Are both attribute selectors. The first one being faster because the lookup of the attribute is already narrowed down to input elements.
input:text
:text
Are jQuery extensions. From the :text selector docs:
Because :text is a jQuery extension and not part of the CSS
specification, queries using :text cannot take advantage of the
performance boost provided by the native DOM querySelectorAll()
method. For better performance in modern browsers, use [type="text"]
instead.
So these selectors are slower (whereas narrowing it down to input elements will be faster here as well).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server Replication not replicating Foreign Keys I am replicating several tables to a database on the same server as the source database.
Those tables have several foreign keys between them. When I look at the replicated tables, they do not have the foreign keys on them.
So, here are my questions:
*
*Should replication be copying these foreign keys by default?
*If not, how can I get them to replicate?
*If so, what would cause them to not replicate?
NOTE:
My source database has TableA and TableB. TableA has a primary key of AId. TableB has a foreign key on that column. And I am doing a transactional replication of both TableA and TableB.
A: OK, I came across something, but it would depend on what type of replication you are using.
I am using transactional replcation. Find the publication you are using here,
(Management Studio) Replication -> Local Publications -> (Publication)
Right click the publication and select properties, then under articles right click 'Tables' and select the option 'Set Properties of All Table Articles'.
In there the first item is 'Copy foreign key constraints'.
Haven't tried it, but I expect it to work.
You can apply these settings per table too if you right click a single table and select the option 'Set Properties of This Table Article'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Java Annotation Processors: Usage & Applications I'm relatively new to Java EE development and although I understand what annotations are, and how to use them, I am having difficulty "seeing the forest through the trees" when it comes to understanding why anyone would need to write and process their own annotations.
Under what circumstances would you even need a custom annotation?
I'm sure they are crucial somehow, I'm just don't see their usefulness for some reason.
Thanks for any nudges in the right direction!
A: There are a lot of usages for custom annotations. You might think that it's hard to find the reason why we would create one because many have been defined in other framework. In order to basically answer your own question, you should ask "What happened if those frameworks didn't exist, would I need to create my custom use of annotations?" The likely answer would be yes. The following are some of few examples:
*
*If JAX-RS does not exists, you would probably think how to use annotations to signify the REST operation for the method such as the one described here
*If JUnit hasn't implemented the annotation to denote Test method like in this article, you might think to do the same thing
*If Spring hasn't implemented Validation, it's something that you might come up as well such as the one here
*And if Java itself hasn't come up with annotations for documentation, you probably would use your own custom annotations described here
To answer your question, everytime you want to enrich your class through additional metadata that hasn't been covered by other framework, you might be thinking of creating your own annotations. While, a lot of smart people cover the common usages for annotations, that doesn't hinder you for coming up with your own usage in the future and thus the need for your own custom annotation and processing.
A: There are some related discussions on StackOverflow, for instance here.
Simply put: whenever you implement your own framework which - in one way or the other - "glues" code together, enriches the code with some kind of "meta"-information that you process at build (or run-)time a.s.o.
Some well-known examples include: dependency injection, object-relational mapping, reflection, documentation etc.
A: There's tons of reasons, but they're obviously application-specific.
For example, we annotate domain classes to be in-house-security-framework-aware. We process our own annotations for documentation purposes. We have state-machine annotations that build up directed graphs for both configuration and documentation purposes.
Some are interrogated at run-time, some during documentation processing, some at startup, some have multiple uses.
Framework annotations start off as being something custom, then when it's turned into a framework and released, they just seem "obvious" and "built-in", but they weren't necessarily always intended to be.
A: IMHO they are one of the best things that you can use in Java and they save me ages. I'll give you an example: some days ago I was writing an image processing application. All Filters extended a base class called Filter and many of them had properties like contrast, brightness, etc... Now each property will have a default value, a range with a min and a max, a name suitable for the gui. Then there are properties on filters that I wanted the GUI to expose through controls, others that I didn't. So I created the @FilterPropertyAnnotation that you would use like this:
...
@FilterAnnotation(name = "Image contrast", default = 0.0D, min = -100D, max = 100D)
public double getContrast(){
...
}
Then, using reflection, every time the user choose a filter in the GUI it would scan that Filter subclass methods, see which ones have the annotation and display the appropriate controls only for the properties that I marked with the annotation, all of the with the correct default value and scale. I can't think of a simpler or faster way of doing anything like this.
Annotations are for me the best thing in Java.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Composing an average stream piecewise I have a list of n floating point streams each having a different size.
The streams can be be composed together using the following rules:
You can put a stream starting at any point in time (its zero before it started). You can use the same stream few times (it can overlap itself and even be in the same position few times) and you are allowed to not use a certain stream at all.
e.g.:
input streams:
1 2 3 4
2 4 5 6 7
1 5 6
Can be composed like:
1 2 3 4
1 5 6
1 5 6
After the placements an output stream is composed by the rule that each output float equals to the square root of the sum of the square of each term.
e.g.:
If the streams at a position are:
1
2
3
The output is:
sqrt(1*1 + 2*2 + 3*3) = sqrt(14) = 3.74...
So for the the example composition:
1 2 3 4
1 5 6
1 5 6
The output is:
1 5.09 6.32 3 4.12 5 6
What I have is the output stream and the input streams. I need to compute the composition that lead to that output. an exact composition doesn't have to exists - I need a composition as close as possible to the output (smallest accumulated difference).
e.g.:
Input:
Stream to mimic:
1 5.09 6.32 3 4.12 5 6
and a list:
1 2 3 4
2 4 5 6 7
1 5 6
Expected output:
Stream 0 starting at 1,
Stream 2 starting at 0,
Stream 2 starting at 4.
This seems like an NP problem, is there any fast way to solve this? it can be somewhat brute force (but not totally, its not theoretic problem) and it can give not the best answer as long as its close enough.
The algorithm will be usually used with stream to mimic with very long length (can be few megabytes) while it will have around 20 streams to be composed from, while each stream will be around kilobyte long.
A: I think you can speed up a greedy search a bit over the obvious. First of all, square each element in all of the streams involved. Then you are looking for a sum of squared streams that looks a lot like the squared target stream. Suppose that "it looks like" is the euclidean distance between the squared streams, considered as vectors.
Then we have (a-b)^2 = a^2 + b^2 - 2a.b. So if we can find the dot product of two vectors quickly, and we know their absolute size, we can find the distance quickly. But using the FFT and the http://en.wikipedia.org/wiki/Convolution_theorem, we can work out a.b_i where a is the target stream and b_i is stream b at some offset of i, by using the FFT to convolve a reversed version of b - for the cost of doing an FFT on a, an FFT on reversed b, and an FFT on the result, we get a.b_i for every offset i.
If we do a greedy search, the first step will be to find the b_i that makes (a-b_i)^2 smallest and subtract it from a. Then we are looking for a stream c_j that makes (a-b_i-c_j)^2 as small as possible. But this is a^2 + b_i^2 + c_j^2 - 2a.b_i - 2a.c_j + 2b_i.c_j and we have already calculated everything except b_i.c_j in the step above. If b and c are shorter streams it will be cheap to calculate b_i.c_j, and we can use the FFT as before.
So we have a not too horrible way to do a greedy search - at each stage subtract off the stream from the adjusted target stream so far that makes the residual smallest (considered as vectors in euclidean space), and carry on from there. At some stage we will find that none of the streams we have available make the residual any smaller. We can stop there, because our calculation above shows us that using two streams at once won't help either then - this follows because b_i.c_j >= 0, since each element of b_i is >= 0, because it is a square.
If you do a greedy search and are not satisfied, but have more cpu to burn, try Limited Discrepancy Search.
A: If I can use C#, LINQ & the Rx framework's System.Interactive extensions then this works:
First up - define a jagged array for the allowable arrays.
int[][] streams =
new []
{
new [] { 1, 2, 3, 4, },
new [] { 2, 4, 5, 6, 7, },
new [] { 1, 5, 6, },
};
Need an infinite iterator on integers to represent each step.
IEnumerable<int> steps =
EnumerableEx.Generate(0, x => true, x => x + 1, x => x);
Need a random number generator to randomly select which streams to add to each step.
var rnd = new Random();
In my LINQ query I've used these operators:
*
*Scan^ - runs an accumulator function over a sequence producing an
output value for every input value
*Where - filters the sequence based on the predicate
*Empty - returns an empty sequence
*Concat - concatenates two sequences
*Skip - skips over the specified number of elements in a sequence
*Any - returns true if the sequence contains any elements
*Select - projects the sequence using a selector function
*Sum - sums the values in the sequence
^ - from the Rx System.Interactive library
Now for the LINQ query that does all of the hard work.
IEnumerable<double> results =
steps
// Randomly select which streams to add to this step
.Scan(Enumerable.Empty<IEnumerable<int>>(), (xs, _) =>
streams.Where(st => rnd.NextDouble() > 0.8).ToArray())
// Create a list of "Heads" & "Tails" for each step
// Heads are the first elements of the current streams in the step
// Tails are the remaining elements to push forward to the next step
.Scan(new
{
Heads = Enumerable.Empty<int>(),
Tails = Enumerable.Empty<IEnumerable<int>>()
}, (acc, ss) => new
{
Heads = acc.Tails.Concat(ss)
.Select(s => s.First()),
Tails = acc.Tails.Concat(ss)
.Select(s => s.Skip(1)).Where(s => s.Any()),
})
// Keep the Heads only
.Select(x => x.Heads)
// Filter out any steps that didn't produce any values
.Where(x => x.Any())
// Calculate the square root of the sum of the squares
.Select(x => System.Math.Sqrt((double)x.Select(y => y * y).Sum()));
Nice lazy evaluation per step - scary though...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: UITableViewCell textLabel color not changing I've got a UITableView and as the cellForRowAtIndexPath method I am changing some attributes of the cell (font, size, etc.) Now all of the assignments listed below work just fine except changing the color of the textLabel. I can't figure out why only that specific color attribute won't change. I've looked about everywhere I can think of to figure out why it isn't working and I'm stuck. Any ideas?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kLocationAttributeCellID = @"bAttributeCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kLocationAttributeCellID];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:kLocationAttributeCellID] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0];
cell.detailTextLabel.numberOfLines = 0;
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.userInteractionEnabled = NO;
cell.textLabel.font = [UIFont fontWithName:@"Courier" size:18.0];
cell.textLabel.textColor = [UIColor redColor]; // this never takes effect...
}
cell.textLabel.text = @"Test Label";
cell.detailTextLabel.text = @"Test Details";
return cell;
}
A: It's because of this:
cell.userInteractionEnabled = NO;
If you don't want your cells to be selectable, try using this instead:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: java.lang.NoClassDefFoundError when reading hadoop SequenceFile I am trying to read a SequenceFile with custom Writeable in it.
Here's the code:
public static void main(String[] args) throws IOException {
//String iFile = null;
String uri = "/tmp/part-r-00000";
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
Path path = new Path(uri);
MyClass value = new MyClass();
SequenceFile.Reader reader = null;
try {
reader = new Reader(fs, path, conf);
while(reader.next(value)){
System.out.println(value.getUrl());
System.out.println(value.getHeader());
System.out.println(value.getImages().size());
break;
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
finally {
IOUtils.closeStream(reader);
}
}
When I run this, I get following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/configuration/Configuration
at org.apache.hadoop.metrics2.lib.DefaultMetricsSystem.<init>(DefaultMetricsSystem.java:37)
at org.apache.hadoop.metrics2.lib.DefaultMetricsSystem.<clinit>(DefaultMetricsSystem.java:34)
at org.apache.hadoop.security.UgiInstrumentation.create(UgiInstrumentation.java:51)
at org.apache.hadoop.security.UserGroupInformation.initialize(UserGroupInformation.java:196)
at org.apache.hadoop.security.UserGroupInformation.ensureInitialized(UserGroupInformation.java:159)
at org.apache.hadoop.security.UserGroupInformation.isSecurityEnabled(UserGroupInformation.java:216)
at org.apache.hadoop.security.UserGroupInformation.getLoginUser(UserGroupInformation.java:409)
at org.apache.hadoop.security.UserGroupInformation.getCurrentUser(UserGroupInformation.java:395)
at org.apache.hadoop.fs.FileSystem$Cache$Key.<init>(FileSystem.java:1418)
at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1319)
at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:226)
at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:109)
at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:210)
at com.iathao.run.site.emr.DecryptMapReduceOutput.main(DecryptMapReduceOutput.java:32)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.configuration.Configuration
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
... 14 more
All libraries are packaged into the jar file and are present. What's wrong, and how do I fix this?
A: The hadoop-common-*.jar has to be included for the org.apache.commons.configuration.Configuration class. Put the jar as dependencies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: lxml with schema 1.1 I'm trying to use lxml with the xs:assert validation tag. I've tried using the example from this IBM page:
http://www.ibm.com/developerworks/library/x-xml11pt2/
<xs:element name="dimension">
<xs:complexType>
<xs:attribute name="height" type="xs:int"/>
<xs:attribute name="width" type="xs:int"/>
<xs:assert test="@height < @width"/>
</xs:complexType>
</xs:element>
It seems like lxml doesn't support XML Schema 1.1.
Can someone validate this?
What XML (for Python) engine does support Schema 1.1?
A: The two schema processors that currently support XSD 1.1 are Xerces and Saxon - both Java based.
A: Yea, libxml does not support xsd 1.1. Use xmlschema >=1.0.14 instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Openquery SQL how to check if exists? I am using sql OPENQUERY to check if record exist passing parameter update it, if not insert a new record.
Here is what I have so far
DECLARE @sql VARCHAR (8000)
DECLARE @Id VARCHAR(20)
SET @Id= '31124'
SET @sql = '
SELECT * FROM OPENQUERY
(
SERVERNAME,
''
SELECT Name FROM table WHERE Id= ''''' + @Id + '''''
''
)'
EXEC (@sql)
A: DECLARE @sql VARCHAR (8000)
DECLARE @Id VARCHAR(20)
SELECT @Id= '31124'
SELECT @sql =
'
IF EXISTS
(
SELECT * FROM OPENQUERY
(
SERVERNAME,
''SELECT Name FROM table WHERE Id= ''''' + @Id + '''''''
)
)
BEGIN
UPDATE OPENQUERY
(
SERVERNAME,
''SELECT Name FROM table WHERE Id= ''''' + @Id + '''''''
)
SET Name = ''NewName''
ELSE
INSERT OPENQUERY
(
SERVERNAME,
''SELECT Name FROM table''
)
VALUES
(
''NewName''
)
END
'
EXEC (@sql)
Unless you have some specific requirement to use EXEC, you don't need it.
DECLARE @Id VARCHAR(20)
SELECT @Id= '31124'
IF EXISTS
(
SELECT * FROM OPENQUERY
(
SERVERNAME,
'SELECT Name FROM table WHERE Id= ''' + @Id + ''''
)
)
BEGIN
UPDATE OPENQUERY
(
SERVERNAME,
'SELECT Name FROM table WHERE Id= ''' + @Id + ''''
)
SET Name = 'NewName'
ELSE
INSERT OPENQUERY
(
SERVERNAME,
'SELECT Name FROM table'
)
VALUES
(
'NewName'
)
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent inbreeding and monoculture in genetic algorithm (newbie question) I am writing a genetic algorithm. My population quickly develops a monoculture. I am using a small population (32 individuals) with a small number of discrete genes (24 genes per individual) and a single point cross-over mating approach. Combine that with a roulette wheel selection strategy and it is easy to see how all the genetic diversity is lost in just a few dozen generations.
What I would like to know is, what is the appropriate response? I do not have academic-level knowledge on GAs and only a few solutions come to mind:
*
*Use a larger population. (slow)
*Use runtime checks to prevent in-breeding. (slow)
*Use more cross-over points. (not very effective)
*Raise the number of mutations.
What are some appropriate responses to the situation?
A: I would look at a larger population, 32 induviduals is a very small population. I usually run GAs with a population at least in the number of chromosomes^2 range (by experience) to get a good starting distribution of individuals.
A possible way to speed things upwith a larger population is to spawn different threads (1 per individual, possibly in batches) when running your fitness function (usually the most expensive part of a GA).
Assuming a population of 32, and a Quad core system, spawn threads in batches of 8 (2 threads per cpu will interleave nicely) and you should be able to run approx 4 * faster.
Therefore if you have a time limit on how long to run your GA, this may be a solution.
A: You can add to that:
*
*tournament selection instead of roulette wheel
*island separated multi population scheme, with migration
*restarts
*incorporating ideas from estimation of distribution algorithms (EDA) (resampling the domain close to promising areas to introduce new individuals)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Updating the DOM to recognize AJAX inserted inputs I'm pretty much an idiot when it comes to AJAX, so if this problem is really simple, please forgive me.
I have this little form:
<form id="location_ajax_request">
<label for="location">Enter Your Location:</label>
<input name="ajax_location" id="ajax_location" type="text" value="Irvine, CA, USA" />
<input id="requestLocation" type="button" value="Click to Submit" />
<p id="output"></p>
</form>
When requestLocation is clicked, a GET call to a php script returns something like:
<input type="radio" name="location_selected" value="0" />
<input type="hidden" name="location_x_0" value="-117.8253403" />
<input type="hidden" name="location_y_0" value="33.6868782" />
<input type="hidden" name="location_name_0" value="Irvine, CA, USA" />
[...]
<input type="button" id="confirmAddress" value="Confirm Address" />
Where the _0 is a count of items. If, for instance, someone had entered London, USA, they'd receive some 5 responses.
With jQuery, I grab the click of $('#confirmAddress') successfully using live() and attempt to grab the values of the inputs. I assume they somehow need to be checked for since inserted elements aren't registered with the DOM. Say I'm trying to grab:
document.forms['location_ajax_request']['location_name_0'].value;
How do I first register it with the DOM as a valid object so it stops returning undefined?
A: Well if you are using jquery as the OP tags say:
$('input[name="location_name_0"]', '#location_ajax_request').val();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails Formtastic does not show error message for date field I have a Formtastic form like:
<%= semantic_form_for @event do |form| %>
<div class="field">
<%= form.label :starts_at %><br />
<%= form.datetime_select :starts_at, :discard_year => true, :minute_step => 30 %>
</div>
<% end %>
In my Event.rb, I have:
validates_inclusion_of :starts_at, :in => Time.now..(Time.now + 1.year),
:message => "appointment must be between now and one year from now"
It seems that the validation works (prevent instances with invalid date from being saved), but the error message does not show in the form. I have other fields with validations and they all show message that I specified in Event.rb
I wonder what I did wrong, or there's something special about date field.
A: To see the error message you need to access the the errors method. I call a helper method inside the form:
render_form_errors(form)
Where the helper method is:
def render_form_errors(form)
object = form.object
if object && object.errors.any?
message = 'Please fix these errors, then try again:'.html_safe
content_tag :div, message + form.semantic_errors(*object.errors.keys), :class => "form-error ui-state-error ui-corner-all"
else
''
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get function in perl w/ website does not produce a value inside the perl script I'm trying to get index.pl?home=home to produce the value 'home' within my perl script, or home=anything to produce 'anything'.
For some reason I'm not using the GET method correctly.
#!/usr/local/bin/perl
use CGI qw(:standard);
$cgi = new CGI;
$home = $cgi->param('home');
What am I doing wrong? I've searched and searched for this SPECIFIC answer...
A: Add a $cgi->header(); to your script. You're most probably running into a "Premature end of script headers" error:
#!/usr/local/bin/perl
use CGI qw(:standard);
$cgi = new CGI;
$home = $cgi->param('home');
print $cgi->header();
print $home
Check your error_log for details.
A: Your code works fine for me. My full script looks like this:
#!C:/perl/bin/perl.exe
use CGI qw(:standard);
$cgi = new CGI;
$home = $cgi->param('home');
print "Content-Type: text/plain\n";
print "\n";
print "Hello world\n";
print "Hello $home world\n";
(I'm on Windows, but that shouldn't matter.)
When I visit http://localhost/stack.pl?home=xx I see:
Hello world
Hello xx world
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How are multiple ServicePointManager.ServerCertificateValidationCallback methods evaluated? How is the following code evaluated?
ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificateA;
ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificateB;
Given an HttpWebRequest, is it enough if one of the Validator methods returns true, or do they both have to return true? i.e.
ValidateRemoteCertificateA && ValidateRemoteCertificateB
or
ValidateRemoteCertificateA || ValidateRemoteCertificateB
?
Cheers,
tamberg
A: It will use the return value of the last delegate added, in all cases.
ServerCertificateValidationCallback is a multicast delegate property.
Writing ServerCertificateValidationCallback += x appends x to its invocation list.
The return value of a multicast delegate is the return value of the last delegate in its list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to set MaxDate and MinDate to DatePicker returned from webservice on ios I have a an XML response which returns the below data as response
Start Day of the Week-Wednesday
End Day of the Week-Sunday
Start time -16:00
End time -19:00
Now I know how to parse these values ,but I am getting confused on how can I set these values to MaxDate and MinDate of the Date Picker,because the returned response is not same always and may change later,I mean later start day of the week ,end day of the week may change,so how shall I implement it so that it will be efficient..please help me friends..I tried some code which is below,but I am not sure whether i am on the right path,so please show me direction and help me out
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
[Gregorian setfirstDayofWeek:2];
NSDateComponents * comps =[[NSDateComponents alloc]init];
[comps setday:7];
A: So I suggest you to create two UIDatePicker's or one custom UIDatePicker.
If you will select first approach, you can set ranges of time in UIDatePicker in following way:
Using IB:
*
*Select your Date picker.
*Open Utilities -> Attribute inspector
*In block Constraints :
*Select Minimum Date and set its value 01/01/1970 16:00:00
*Select Maximum Date and set its value 01/01/1970 19:00:00
*Set value Date to 01/01/1970 16:00:00
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: The best way to implement multi-language PHP First of all, I know that there is a lot of answers about multi-language functionality, I didn't find the answer for what I want.
I thought about three ways that I can work with. I need to create the languages files using PHP each time I'm adding a new value to a web form interface.
The first two are kind of similar - using arrays or defines in a specific language file and include it on the start of the run.
But in this case I might load thousands of definitions or arrays just to use a few in each page.
The third way is to create function that is called each time with the keyword or the full phrase and using IF-s or switch to choose the right term (or returning the key called if no match).
What is the best way to do that?
I decided to do some tests. I tried three different ways and measured the time and memory took for it:
*
*I defined an array (22 values) with and run over it from 1 to 1,000,000 - checked for calling value - 1 of three by using the % operator to choose what to use and just setting it on a variable
*
*Time took: 0.476591110229 second
*Memory: 6536 bytes
*I used the same array (22 values) and called it using function - return $arr[$string]; (just for convenient way to work and the ability to change it to different way if I'll need)
*
*Time took: 0.960635185242 second
*Memory: 6704 bytes
*I created a function with list of strings and using switch-->case I chose the returning string
*
*Time took: 1.46953487396 second
*Memory: 848 bytes
Well, now the question is what's the right choice - preferring time or preferring memory.
And in case that the sites are big and it would take a lot of memory - I couldn't change it because it is built with arrays - If it works with function I can always change it.
A: In terms of code, something like this will be great to you. It must be based in the choice of the user (Choosing a language from a button or menu) or based on the browse language (it is not the best aprouch).
index.php
<?php
// verify the user's choice
if ($_POST[lang] == "en")
{
include_once("en_language.php");
}
if ($_POST[lang] == "pt")
{
include_once("pt_language.php");
}
// calling a lable in your page
echo LABEL_MENU;
// the rest of your file
...
?>
en_language.php
<?php
// ENGISH Language file
define('LABEL_MENU','Main Menu');
// the whole file with the labels of your system
?>
pt_language.php
<?php
// PORTUGUESE Language file
define('LABEL_MENU','Menu Principal');
// the whole file with the labels of your system
?>
complementing
If you wish use array type than Constant values with define(), but I'm not sure what is faster than..
$arrays = array("MAIN_MENU" => "Main Menu", "LEFT_MENU" => "Left Menu");
echo $arrays["MAIN_MENU"];
A: Group your strings into categories - one global and the other - corresponding to the views you have in the web site (for example lang_global, lang_profile, lang_something_else)
Include the global file and the file corresponding to the current view. In this way you won't load the entire translation, but only a subset of it. And it is more managable, and you can provide context, having different translations on the same string.
A: there's some useful answer here, but i would also recommend symfony/translation if you are using composer as a dependency manager.
lang/messages.fr.yaml :
Hello, %name%!: Bonjour, %name%!
Goodbye: Goodbye!
lang/messages.en.yaml :
Hello, %name%!: Hello, %name%!
file.php :
<?php
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Translator\Loader\YamlFileLoader;
require_once __DIR__ . '/vendor/autoload.php';
$translator = new Translator();
$translator->addLoader('yaml', new YamlFileLoader());
$translator->addResource('yaml', __DIR__ . 'lang/messages.en.yaml', 'en');
$translator->addResource('yaml', __DIR__ . 'lang/messages.fr.yaml', 'fr');
$translator->setFallbackLocales(array('en'));
$translator->setLocale('en');
echo $translator->translate('Hello, %name%!', ['name' => 'saif']); // Hello, saif!
$translator->setLocale('fr');
echo $translator->translate('Hello, %name%!', ['name' => 'saif']); // Bonjour, saif!
// Goodbye isn't set in the "fr" file, translator uses the fallback locale instead
echo $translator->translate('Goodbye'); // Goodbye !
read more on how to use the symfony translator component here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: WCF Message contract versioning I would like add a new MessageBodyMember to my MessageContract which refers to a new Datacontract.
Will there be an issue?.
What is the best way to handle message contract changes?.
How to know whether the addition of a new MessageBodyMember would be a breaking or non-breaking change?.
A: Message contract versioning is handled in http://msdn.microsoft.com/en-us/library/ms730255.aspx:
Occasionally, you may need to change message contracts. For example, a
new version of your application may add an extra header to a message.
Then, when sending from the new version to the old, the system must
deal with an extra header, as well as a missing header when going in
the other direction.
The following rules apply for versioning headers:
*
*WCF does not object to the missing headers—the corresponding
members are left at their default values.
*WCF also ignores unexpected extra headers. The one exception to
this rule is if the extra header has a MustUnderstand attribute set to
true in the incoming SOAP message—in this case, an exception is thrown
because a header that must be understood cannot be processed.
Message bodies have similar versioning rules—both missing and
additional message body parts are ignored.
So that means that you can add and remove MessageBodyMembers, without breaking compatibility. Be careful with changing member types. Make sure they are serialized equally to remain compatible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use ViewModel Ok, after some research I was unable to understand the "viewmodel thing".
I didn't find any article that explains me what are the steps to work with ViewModels compared to simply passing the Entity as a Model to the View.
When using the pure Entity it is pretty straight-forward:
If creating a new entry, just show the view. If is post, validate, do Add(x) and voilá! When editting, populate an object and send it to the View. When posting, validate, change the state and save. No secret here.
But I am unable to create and edit ViewModels. Can someone help me on this?
To be short, I have this POCOs :
public class Vessel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int ShipownerId { get; set; }
public virtual Shipowner Shipowner { get; set; }
}
public class Shipowner
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Vessel> Vessels { get; set; }
}
And this View:
@model INTREPWEB.Models.VesselCreateViewModel
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Vessel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Vessel.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Vessel.Name)
@Html.ValidationMessageFor(model => model.Vessel.Name)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Vessel.ShipownerId, Model.Shipowners, String.Empty)
@Html.ValidationMessageFor(model => model.Vessel.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
I've created this ViewModel:
public class VesselCreateViewModel
{
public Vessel Vessel { get; set; }
public SelectList Shipowners { get; set; }
public VesselCreateViewModel()
{
using (INTREPDB db = new INTREPDB())
{
var list = db.Shipowners.ToList()
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
});
Shipowners = new SelectList(list, "Value", "Text");
}
}
public VesselCreateViewModel(int id)
{
using (INTREPDB db = new INTREPDB())
{
Vessel = db.Vessels.Find(id);
var list = db.Shipowners.ToList()
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
});
Shipowners = new SelectList(list, "Value", "Text");
}
}
}
As you can see, it auto populates a collection for the View to show a DropDown menu. I was able to create new Vessels by doing the same way I do with only Models. But can't figure out what I'm doing wrong when editting this thing.
This is the wrong POST Edit method:
[HttpPost]
public ActionResult Edit(VesselCreateViewModel vm)
{
if (ModelState.IsValid)
{
db.Entry(vm.Vessel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
}
What should I do to save this little monster?
A: as you can see you are only using the Model-part of your ViewModel in this code. This is IMHO typical so you pass the ViewModel to the View but only bind the Model in your Edit-Postback.
Then you can easily recreate the viewmodel based on the changed model if you have to.
BTW: IMO ViewModel is a bad name in this case. If I hear ViewModel I think of MVVM but this case the viewmodel is only some kind of static-typed View-Helper and should have no behavior.
A: Viewmodel little excerpt from Steve senderson book
MVC also uses the term view model, but refers to a simple model class that is used only to pass data from
a controller to a view. We differentiate between view models and domain models, which are sophisticated
representations of data, operations, and rules.
If you want to save view model you may use automapper
A: I'm guessing you should wrap around the db calls in a Using block just like in the VesselCreateViewModel constructors.
You could eventually use commands in your ViewModel to save, edit or delete your data and bind this command to Buttons or other Controls on the view.
I would recommend you two great books about MVVM, you find good examples, easy to understand them too.
Building Enterprise Applications with Windows® Presentation Foundation
and the Model View ViewModel Pattern
Pro WPF and Silverlight MVVM - Effective Application Development with
Model-View-ViewModel
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: VS2010 add a .dll reference error I am trying to add a DLL to my project but there are some problems.
first of all, VS dont compile when I add the dll in references. it shows the error :
The "NativeAssemblies=@(NativeReferenceFile);@(_DeploymentNativePrerequisite)" parameter for the "ResolveManifestFiles" task is invalid.
The "ResolveManifestFiles" task could not be initialized with its input parameters.
anyone can tell me what is wrong ?
A: A similar question was asked previously. You can refer to the links below to see if it helps alleviate your errors.
See this StackOverflow question : ResolveManifestFiles
MSDN Forums - Discussion
Regsvr32 Usage and Errors
A: I have already resolved the problem.
first, the dll isn´t a .NET dll so I has to put it in bin/debug directory of project folder.
then I access it with :
[DllImportAttribute(@".\LDACTL.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int LDA_GetStatus();
LDA_GetStatus() is a function on dll....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: PHP passing array to function I've seen a few people ask a similar question. But I do need a little more clarification on this particular subject.
I have several functions that pass several arguments. I even have a few that are about 10 arguments. (didn't initially plan it, simply grew over time)
I don't have any problems looking at my source code to find out what the 7th argument is, but it does get tedious. Most of the time I know what arguments to pass, just not the position.
I had a few ideas to simplify the process for me.
a) pass 1 argument, but divide everything with some delimiter. (but that's a bad idea!, since I still need to remember the position of each.
function myfunc('data|data|data|'){
// explode the string
}
b) pass an array with key and values, and look for the key names inside my function, and act accordingly.
function myfunc(array('arg1' => 'blah blah', 'arg2' => 'more blah')){
// loop through the array
}
c) keep it as it is.
function myfunc($arg1,$arg2,$arg3,$arg4,$arg5........){
// yay
}
So, I'm seeking other options and better ideas for handling functions with growing argument lists.
A: In my opinion, the best way to it is by passing in an associative array. That way you immediately see what each argument does. Just be sure to name them descriptively, not arg1 & arg2.
Another advantage an associative array, is that you don't have to care about the order in which the arguments are being passed in.
Just remember that if you use an associative array, you lose PHP's native way of assigning default values, e.g.:
function doSomething($arg1 = TRUE, $arg2 = 55) { }
So, what you have to do is create your own set of default options, and then merge your arrays:
function doSomething( $props = array() )
{
$props = array_merge(array(
'arg1' => TRUE,
'arg2' => 55
), $props);
// Now use the $props array
}
A: go with the myfunc($options) form when you have many optional parameters that can be mixed and matched. Use array_merge_recursive with a default options array, and you'll be golden.
A: b) (an associative array) is by far the easiest, most adaptible (as it allows simulating default keyword arguments), and least error-prone variant.
A: First, see if you can introduce paramter object. It not necesseary to replace all 7 parameters, but maybe you can lower their count.
Next, examine the function itself - why it needs so many parameters, maybe it just does to much things? Is Replace parameter with method / Replace parameter with explicit method applicable?
By the way, Refactoring is great reading!
A: Depending on the intention of the function, sometimes it is appropriate to pass an object.
A: Let's not talk about solution #1. You already say that it is bad...
I like the second idea of passing in this hash/associative array. It feels rubylike :)
The thing you are doing is that you are giving up some checks that you would get for free. If you call a function and forget an argument the runtime complains and the script stops executing.
In your scenario you would have to do all those checks inside your function: Are all necessary options given? Are the values the right types, etc?
I would say, the decision is up to your taste if it's just you working on the code.
If others are working with you, I would ask them about their opinion. Until then, I would stick with the classic approach of having the function with 7 arguments
A: Associative array with keys as parameter names, order does not count (do not to forget you document which keys are expected):
function myFunc(array $args)
{
# default values
$args += array('arg1' => 'default1', 'arg2' => 'default2');
}
Sometimes you want to verify that you drop all unimportant keys from the input as well. A useful function for this is array_intersect_keyDocs.
A:
function myfunc($arg1,$arg2,$arg3,$arg4,$arg5........){
With the limited information provided, I would have to say keep it as is. The reason for this is that your function signature shows that none of your arguments have default values (they are all required).
If you make it an associative array, then you remove the parser's ability to warn about ill-called functions, i.e.:
Missing argument 2 for some_function, called in [etc.]
IDEs can help with function calling assistance if you have difficulty remembering all the arguments.
Basically, if it's a required argument, it should be in the function signature.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Glassfish log in NetBeans: Domain Pinged Sometimes I get this message in the Glassfish log window of NetBeans:
Domain Pinged: stable.glassfish.org
Anybody has an idea of what it means?
A: The message is generated by the update Tool of GlassFish:
http://blogs.oracle.com/alexismp/entry/let_glassfish_update_itself_v3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: ShellExecute async (launch program from within C++ and exit immediately) I want to launch MYAPPLICATION from within a C++ program and immediately exit the C++ program (so I do NOT want to wait until MYAPPLICATION has finished or get a reference to the program): just start the MYAPPLICATION and exit.
I tried ShellExecute, but the C++ app is still running after the MYAPPLICATION is started. I also tried using a thread, but if I don't wait for the thread, MYAPPLICATION is not started at all.
if ((err = _waccess_s( MYAPPLICATION, 0 )) == 0 )
{
// application found
ShellExecute(NULL, _T("open"), MYAPPLICATION,NULL, NULL, SW_SHOWNORMAL);
// Create thread 1.
int Data_Of_Thread_1 = 1;
HANDLE Handle_Of_Thread_1 = 0;
HANDLE Array_Of_Thread_Handles[1];
Handle_Of_Thread_1 = CreateThread( NULL, 0, Thread_no_1, &Data_Of_Thread_1, 0, NULL);
Array_Of_Thread_Handles[0] = Handle_Of_Thread_1;
WaitForMultipleObjects( 1, Array_Of_Thread_Handles, TRUE, INFINITE);
CloseHandle(Handle_Of_Thread_1);
}
How can I start MYAPPLICATION from within C++ and immediately exit the C++ app?
Thanks.
A: You need to terminate your process using ExitProcess(), TerminateProcess(), or returning from WinMain() after you start the child process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 2d array from boost::multi_array - unable to compile I am trying to create a 2d array class based on boost::multi_array. I face two issues in the code given below. (1) The code for the member function col() does not compile saying that ::type’ has not been declared. Where am I going wrong? (2) Is it possible to define the member function data() outside the class? My attempt gives compile error as the typedefs are not available. But I am unable to define the typedefs outside the class because the typedefs in turn require the type T which is available only inside the template class. Thanks.
#include <boost/multi_array.hpp>
#include <algorithm>
template <class T>
class Array2d{
public:
typedef typename boost::multi_array<T,2> array_type;
typedef typename array_type::element element;
typedef boost::multi_array_types::index_range range;
//is it possible to define this function outside the class?
Array2d(uint rows, uint cols);
element * data(){return array.data();}
//this function does not compile
template<class Itr>
void col(int x, Itr itr){
//copies column x to the given container - the line below DOES NOT COMPILE
array_type::array_view<1>::type myview = array[boost::indices[range()][x]];
std::copy(myview.begin(),myview.end(),itr);
}
private:
array_type array;
uint rows;
uint cols;
};
template <class T>
Array2d<T>::Array2d(uint _rows, uint _cols):rows(_rows),cols(_cols){
array.resize(boost::extents[rows][cols]);
}
A: array_type::array_view<1>::type
You need template and typename here :)
typename array_type::template array_view<1>::type
^^^^^^^^ ^^^^^^^^
The keyword template is required because otherwise the < and > will be treated as less and greater because the array_type is a dependent name, and therefore whether array_view is a nested template or not is not known until instantiation.
A:
(1) The code for the member function col() does not compile saying that ::type’ has not been declared.
array_type is a dependant type on T and array_type::array_view<1>::type is still dependant on T, you need a typename.
(2) Is it possible to define the member function data() outside the class?
It sure is, but it shouldn't be a problem for it to be defined inside the class.
template< typename T >
typename Array2d< T >::element* Array2d< T >::data(){ ... }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you create attribute handlers for methods of an object in Perl/Moose I think I've got attribute handlers down for perl Natives!
package tree;
has '_branches' => (
traits => ['Hash'],
is => 'rw',
isa => 'HashRef[Any]',
handles => {
_set_branch => 'set',
_is_branch => 'defined',
_list_branches => 'keys',
_branch => 'get'
},
trigger => sub {
my($self,$hash) = @_;
$self->_build_branch($hash);
}
);
sub _build_branch{
my($self,$hash);
# do stuff!
#return altered or coerced hash
return $hash;
}
What do you think?
But let's say for example I have a LinkedList object with the following methods
LinkedList{}
LinkedList.append()
LinkedList.insert()
LinkedList.size()
LinkedList.has_children()
LinkedList.remove()
LinkedList.split()
Is there a way handle the object's methods via Moose Attributes (without using MooseX) - similar to this?
package Bucket;
has '_linkedlist' => (
traits => ['LinkedList'],
is => 'rw',
isa => 'LinkedListRef[Any]',
handles => {
_add_link => 'append',
_insert_link => 'insert',
_count_links => 'size',
_del_link => 'remove',
_split_at_link => 'split',
_has_sublinks => 'has_children',
},
It would be great if there was a way to do this, but I'm concerned maybe I've misunderstood something somewhere about how or why to create handlers for non-native attributes.
Thoughts?
A: Are you simply overcomplicating things, or am I missing something?
package Bucket;
has '_linkedlist' => (
is => 'rw',
isa => 'LinkedList',
handles => {
_add_link => 'append',
_insert_link => 'insert',
_count_links => 'size',
_del_link => 'remove',
_split_at_link => 'split',
_has_sublinks => 'has_children',
},
);
Hashes don't have methods, which is why it involves a trait. The trait adds the methods. Your LinkedList class has methods, so no need to write a trait to provide the methods.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Flip animation only halfway through I was wondering if it would be possible to make an animation that looks like the flip transition, but only animate it halfway through, so that the animation stops at the moment when you you can't really see it.
Any help is greatly appreciated.
A: You want to animate the layer's transform property from it's default (CATransform3DIdentity) to a quarter-rotation around the Y axis. It should be something like this:
[UIView animateWithDuration:1 animations:^{
CATransform3D transform = CATransform3DMakeRotation(M_PI_2, 0, 1, 0);
transform.m34 = 1.0 / -2000.0;
self.view.layer.transform = transform;
}];
The m34 value is how you turn on perspective for a layer. Search for "m34 perspective" for many discussions of it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you configure a different page size for production and test for Kaminari I'm running some rspec unit tests involving getting data back through kaminari paging, but the default page size for our application is 20, whereas 2 would work fine for test.
How do a set a different configuration for the default kaminari page size for test, or how do I set it up during the rspec setup for the test?
A: In your model you can override the default per_page:
class Something < ActiveRecord::Base
paginates_per Rails.env.test? ? 2 : 20
end
A: Don't. You are supposed to test the data as similar to the production environment as possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: performance of nspropertylistserialization vs nsjsonserialization I'm considering making a switch from serializing data from my web service endpoint as JSON to a binary property list. I'm unserializing on Cocoa. Has anyone who has used both NSPropertyListSerialization and NSJSONSerialization noticed a difference in parsing times? I'm curious as I've read before that there's a noticeable difference—see this blog post (in the Under the Hood section) for an example by Hipmunk.
Also interesting to me if there's a noticeable difference between NSJSONSerialization and external libraries like JSONKit or TouchJSON.
A: I pulled down 200 tweets and profiled parsing the payload using both SBJSON and NSJSONSerialization. The results:
SBJSON: 489ms / 397KB
NSJSONSerialization : 133ms / 3.8 KB
NSJSONSerialization has a pretty significant advantage - especially in terms of the memory footprint.
http://blog.skulptstudio.com/nsjsonserialization-vs-sbjson-performance
A: I can say that NSJSONSerialization is faster than JSONKit, I used it for a Core Graphics project and code which took on average 26ms before is now 16ms, with only changes in the JSON deserialization.
Not sure on NSPropertyListSerialization, but the GitHub page of JSONKit claims it's faster than binary .plist, which leads me to believe that NSJSONSerialization class is the fastest of them all. Correct me if I'm wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 'Group' is a reserved keyword and cannot be used as an alias, unless it is escaped I'm using Entity Framework 4.1 with repository pattern (Database is already existing).
My problem is the existence of a table called GROUP (which is reserved). This is a production database which i cannot change.
So, using all this techniques above i'm getting the following error:
'Group' is a reserved keyword and cannot be used as an alias, unless it is escaped.
Is it possible to tell Entity Framework to use the following as the table name:
[GROUP]
EDIT
The class with the db context looks like the following (stripped down)
public class AMTDatabase : DbContext
{
private IDbSet<GROUP> _Groups;
public IDbSet<GROUP> Group
{
get { return _Groups ?? (_Groups = DbSet<GROUP>()); }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<GROUP>().ToTable("GROUP");
}
//etc
}
Thanks in advance
A: Well it seems very weird, but notice the property name above: the name is Group and it should read Groups! This is the reason i'm getting this error. The corrected code is the following:
private IDbSet<GROUP> _Groups;
public IDbSet<GROUP> Groups
{
get { return _Groups ?? (_Groups = DbSet<GROUP>()); }
}
Works like a charm now!
A: Try to use another naming for you class and tell him to use the Group table in your database like so:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyGroup>().ToTable("GROUP");
}
Or with the attributes directly on your entity class:
[Table("Group")]
public class MyGroup
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("GroupId")]
public int GroupId { get; set; }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Open link from PDF into IE I am having a tough time with PDF files opened in IE. What I need to do is link to a Word document (.doc) file from a PDF document in IE without IE navigating away from the PDF once the link has been clicked. I am finding that the default behavior of IE is to close the PDF file when you navigate away from it, Firefox will just open the link in a new tab and keep the document open in a separate tab. I need to find a fix that emulates the firefox behavior that doesn't involve changing the IE settings on the local machine.
To give another example of the functionality I am looking for here is the HTML equivalent:
<a href="some_pdf.pdf" target="_blank">Some PDF</a>
I need that "_blank" functionality in the PDF document.
A: In short, you should disable IE reusing the window session. The steps are as follows:
*
*Open Internet Explorer
*Click on the Tools button, located in the upper right hand corner of your browser window.
*When the drop-down menu appears, select Internet Options
*After the Options window opens, switch to the Advanced tab
*Find and make sure the option Reuse windows for launching shortcuts is unchecked (it should be under the Browsing category)
*Save and close Internet Options, and restart the browser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: C2DM authorization key CRLF and .Net WebRequest We are using C2DM and are writing the server app in C#.
We obtain the authorization key with a POST using the WebRequest component. This works and we get back an encoded authorization key. The problem comes when we add this key to the auth header of the request that is going to send the message.
WebRequest request = WebRequest.Create("url");
...
request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthorizationKey);
Since the key has the LF character, we get an exception...
Unhandled Exception: System.ArgumentException: Specified value has invalid CRLF characters.
Parameter name: value
at System.Net.WebHeaderCollection.CheckBadChars(String name, Boolean isHeaderValue)
at System.Net.WebHeaderCollection.Add(String name, String value)
It would seem that CheckBadChars() is refusing the authorization key because it thinks there is a CRLF in the key, when in fact there is only a LF.
Does anyone have any ideas how we could get around this issue?
A: Maybe you’re just getting a linebreak at the end that you’re supposed to remove?
Edit: I read the documentation (at http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Response) and it says you’re supposed to get back a response that looks like this:
SID=DQAAAGgA...7Zg8CTN
LSID=DQAAAGsA...lk8BBbG
Auth=DQAAAGgA...dk3fA5N
There’s your three linebreaks. So what you need to do is pick out the the line starting with Auth= and grab the authorization token from there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: hide headers of asp.net ajax control I have a problem: I would like to hide all of the headers of Asp.net ajax control from this link: http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/tabs/tabs.aspx
Then I click next, then the tabContainer will select a next tab.
Is it possible?
thanks in advance.
A: Sound more like you are in need of the Asp.Net Wizard Control
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Zend PDF problem I made for myself this simple class for drawing text by lines into specific pages. This is how it looks:
class pdf {
public $path;
private $pdf;
private $page;
private $font;
private $visibleLineYValue = 600;
public function __construct() {
require_once './Zend/Pdf.php';
}
public function loader($page) {
$this->pdf = Zend_Pdf::load($this->path);
$this->page = $this->pdf->pages[$page];
}
public function fontSetter($size) {
$this->font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES_BOLD);
$this->page->setFont($this->font, $size);
}
public function drawVisibleLine($content) {
$page->drawText($content, 20, $this->visibleLineYValue);
$this->visibleLineYValue - 40;
}
public function saver() {
$pdf->save('something.pdf');
}
}
The problem is, taht when I call this class... like that:
$pdf = new pdf();
$pdf->path = 'PJ Pracovnepravni.pdf';
$pdf->loader(1);
$pdf->fontSetter(13);
$pdf->drawVisibleLine('Lorem');
$pdf->drawVisibleLine('Ipsum');
$pdf->drawVisibleLine('Dolor');
$pdf->saver();
...it writes this:
Notice: Undefined variable: page in E:\!localhost\woltersKluwer\classes\pdf.php on line 31
Fatal error: Call to a member function drawText() on a non-object in E:\!localhost\woltersKluwer\classes\pdf.php on line 31
If I correctly understand it, it means that private variable $page is not define, but if I see good it is define.
Thanks in advance for answer
A: You're missing a $this in the last two methods:
public function drawVisibleLine($content) {
$this->page->drawText($content, 20, $this->visibleLineYValue);
$this->visibleLineYValue - 40;
}
public function saver() {
$this->pdf->save('something.pdf');
}
Without this, the interpreter looks for a local variable $page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Faking/mocking an interface gives "no default constructor" error, how can that be? I'm trying to write a unit test of a repository implementation. The repository uses RavenDB as a database. For the unit tests, I would like to mock the RavenDB parts. In order to create the mocks (fakes) I'm using FakeItEasy. I figured there wouldn't be any problems with the mocking/faking since the RavenDB API is accessed through interfaces.
I do however have a problem when trying to instantiate a specific mock. The relevant parts of my unit test code looks like this:
[Fact]
public void Test() {
UserDocument doc = ...;
IQueryable<UserDocument> where = A.Fake<IQueryable<UserDocument>>();
A.CallTo(() => where.First()).Returns(doc);
IRavenQueryable<UserDocument> query = A.Fake<IRavenQueryable<UserDocument>>();
IDocumentSession session = A.Fake<IDocumentSession>();
A.CallTo(() => session.Query<UserDocument>()).Returns(query);
IDocumentStore store = A.Fake<IDocumentStore>();
A.CallTo(() => store.OpenSession()).Returns(session);
.
.
.
}
When instantiating the IRavenQueryable fake I get an exception. This is the log from the Xunit.net runner:
UnitTest.Test : FakeItEasy.Core.FakeCreationException :
Failed to create fake of type "System.Linq.IQueryable`1[UserDocument]".
Below is a list of reasons for failure per attempted constructor:
No constructor arguments failed:
No default constructor was found on the type System.Linq.IQueryable`1[UserDocument].
Stack Trace:
vid FakeItEasy.Core.DefaultExceptionThrower.ThrowFailedToGenerateProxyWithResolvedConstructors(Type typeOfFake, String reasonForFailureOfUnspecifiedConstructor, IEnumerable`1 resolvedConstructors)
vid FakeItEasy.Creation.FakeObjectCreator.TryCreateFakeWithDummyArgumentsForConstructor(Type typeOfFake, FakeOptions fakeOptions, IDummyValueCreationSession session, String failReasonForDefaultConstructor, Boolean throwOnFailure)
vid FakeItEasy.Creation.FakeObjectCreator.CreateFake(Type typeOfFake, FakeOptions fakeOptions, IDummyValueCreationSession session, Boolean throwOnFailure)
vid FakeItEasy.Creation.DefaultFakeAndDummyManager.CreateFake(Type typeOfFake, FakeOptions options)
vid FakeItEasy.Creation.DefaultFakeCreatorFacade.CreateFake[T](Action`1 options)
The "no default constructor found" doesn't make any sense since what I'm trying to fake is an interface. Does anyone have a suggestion what the problem might be?
A: I know it is an old post, but I ran into the same issue.
What I found to be the problem was a return type of one of the methods declared into the interface I was trying to fake.
This method was returning an object of a certain class, and this class didn't have a default constructor with which FakeItEasy could work.
If someone else gets this error try to check the objects your interface is returning, and if the corresponding classes have the default constructors.
A: Does the IRavenQueryable<T> interface have a where T : new() type constraint?
If so, and UserDocument does not provide a parameter-less ctor, this might be causing your problem.
A: I just ran into this, but my issue wasn't around internal types. My issue was with the assembly containing the type not being in the bin folder of the unit test project.
It seems like FakeItEasy throws this error when it can't resolve a type that it needs to fake. (This makes sense why an internal type in another assembly would cause the same error.)
So, I had Project Foo, which is referenced by Project Bar. Project Bar had a public interface referencing a public type from Project Foo. Project Bar.Tests has a reference to Project Bar, but not Project Foo. When I build Bar.Tests, Bar.dll gets put in the bin folder but Foo.dll does not. When FakeItEasy tries to fake out my interface, it can't resolve the type which resides in Foo.dll.
Adding a reference to Project Foo in my Bar.Tests project ensured that Foo.dll makes its way over and is there for FakeItEasy and made this error disappear.
So...
In your case, it could be that your RavenDB assembly (which I assume contains UserDocument) is only referenced by your actual project and is not getting copied to your unit test build output.
A: You're correct in that the exception message does not make any sense, this is a bug. It would be great if you could supply a VS-solution that reproduces the bug and file an issue here: https://github.com/patrik-hagne/FakeItEasy/
The bug is in that the wrong exception message is used, however there must be something wrong that makes the fake creation go wrong. Is the "UserDocument"-type public? If it is internal and you have given your test-project access to it through the use of InternalsVisibleToAttribute you must give the proxy generating library access to it as well: https://fakeiteasy.readthedocs.io/en/stable/how-to-fake-internal-types/#how-to-fake-internal-friend-in-vb-types.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to Bind an Observable collection in Autocomplete Text box? I need to bind an Observable collection to my AutoComplete Text box in the WPF application. But When I run the application after binding in the designer, I got a display with my full BL class Reference in the dropdown. How to avoid this behaviour? Also I want to show some other properties in the dropdown(as details view) and I should be able to get the Other properties of the object once I select a item from the List. Is anybody can come with a code snippet?
A: Without seeing your code, I'm assuming your ObservableCollection is a user defined object and you're binding the ItemsSource to the ObservableCollection and not providing a DataTemplate. The controls within the DataTemplate would then be bound to the public properties of the object stored in the ObservableCollection.
The DataTemplate would also allow for you to show all the properties you want in the dropdown listbox. Since I'm unaware of the auto-complete textbox you are using I can't really give an example of the DataTemplate.
Here is a simple example of a ListBox DataTemplate:
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is a link which will give you all the info you need: http://msdn.microsoft.com/en-us/library/ms742521.aspx.
A: There is ItemTemplate property in the AutoCompleteTextBox. You can use that to display whatever you want in the drop down list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calling addon functionality from a unit test I've made a firefox addon using the the addon-sdk and I'm trying to write unit tests for it now.
How can I access the addon functionality from the test? From what i see, they are separated, and I cannot simply access the addon functions and variables of my addon.
A: You simply import the modules of your add-on. For example, if you have a module lib/foo.js in your add-on you do:
var foo = require("foo");
Note that you will only be able to access the methods and variables that the module exports (essentially properties of its global exports object).
The reading-data example in the Add-on SDK uses that approach to load the add-on's main module and to call the exported method main().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery $() function I am new to javascript and jquery so I am wondering what does
$('#someid a')
referring to?
and when does the function $.get get called? (since I feel the code after $.get is called before $.get
Thanks in advance.
A: $('#someid a')
Selects all a tags contained within an element with the id someid
I don't see any calls to $.get, so I don't understand that part of the question.
A: It creates (selects (it's a selector)) a new jQuery object which holds a tag in #someid
$.get
is called to call a page with ajax
A: $("#someid a") will select all <a> tags that are inside of the first element that has an id of #someid.
$.get() makes an asynchronous http request to the given url. once the request returns, the callback is ran.
i suggest going through the jquery getting started tutorials
http://docs.jquery.com/Main_Page
A: Selects zero or more 'a' tags contained by a tag with id "someid". $.get is called when the execution gets to the line containing $.get. See the documentation for more information about $.get here: http://api.jquery.com/jQuery.get/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Resources not being 'selected' in Telerik Scheduler Edit Dialog I've implemented Telerik scheduler on timeline view. I am allowing a M:M relationship between my y-axis resource (advocates) and Meetings. Here is what my scheduler looks like:
When I double click one of the instances of the meeting, the advanced edit dialog appears. However, in here, none of the advocates are selected as participants in the meeting:
There are a number of advocates for whom this meeting appears in the timeline. Why do they not get displayed as selected in the edit form?
The problem doesn't end there. I have a second type of resources (legislators) that also has a M:M relationship with Meetings. There is a similar problem here - I have relationships defined for this meeting and 4 legislators, but only the first legislator is checked (and the other three remain unckecked):
I need to add two other types of resources (again, each will be M:M with Meetings), and I expect that I will have a similar problem to the two I have already added.
I have been able to verify visually by changing the grouping of my scheduler and through SQL queries that the relationships in the database are valid. So, why am I unable to see each of these related resources checked? My scheduler code is as follows:
<telerik:RadScheduler runat="server" ID="RadScheduler1"
AdvancedForm-Enabled="true"
AllowEdit="true"
AllowInsert="true"
DataEndField="End"
DataKeyField="ID"
DataSourceID="EventsDataSource"
DataStartField="Start"
DataSubjectField="Subject"
DayEndTime="17:00:00"
DayStartTime="07:00:00"
EnableAdvancedForm="true"
Localization-HeaderMultiDay="Work Week"
OverflowBehavior="Expand"
OnAppointmentDelete="OnAppointmentDelete"
OnAppointmentInsert="OnAppointmentInsert"
OnAppointmentUpdate="OnAppointmentEdited"
OnNavigationComplete="RadScheduler1_NavigationComplete"
SelectedDate="9/20/2011"
SelectedView="TimelineView"
>
<AppointmentContextMenuSettings EnableDefault="true" />
<AdvancedForm Modal="true" />
<ResourceTypes>
<telerik:ResourceType KeyField="Adv_AdvocateID" AllowMultipleValues="true" Name="Advocate" TextField="Adv_FullName" ForeignKeyField="Adv_AdvocateID"
DataSourceID="AdvocatesDataSource" />
</ResourceTypes>
<ResourceTypes>
<telerik:ResourceType KeyField="Leg_LegID" Name="Legislator" AllowMultipleValues="true" TextField="Leg_FullName" ForeignKeyField="Leg_LegID"
DataSourceID="LegislatorsDataSource" />
</ResourceTypes>
<TimelineView UserSelectable="true" GroupBy="Advocate" GroupingDirection="Vertical" />
<MultiDayView UserSelectable="false" />
<DayView UserSelectable="false" />
<WeekView UserSelectable="false" />
<MonthView UserSelectable="false" />
</telerik:RadScheduler>
I'm hoping someone can shed some insight into how to correctly display the selected resources in the edit appointment dialog, and I thank you in advance for your help.
A: I was looking at that form earlier, the one you just found, which is what prompted me to ask. The methods below seem to be the ones I'm focusing on the most as it would seem they are responsible for the population of the check box and the checking of each entry.
The thing is, what you have now is good, you would just have to substitute your checkbox control into the code rather than create one like they do.
EDIT: I went through the Program to see what gets called in order, so that you may adjust them accordingly to fit your data.
protected void Page_Load(object sender, EventArgs e)
{
SemanticCheckBoxList resourceValue = new SemanticCheckBoxList();
resourceValue.ID = "ResourceValue";
ResourceValuesPlaceHolder.Controls.Add(resourceValue);
if (resourceValue.Items.Count == 0)
{
PopulateResources();
MarkSelectedResources();
}
}
private void PopulateResources()
{
foreach (Resource res in GetResources(Type))
{
ResourceValue.Items.Add(new ListItem(res.Text, SerializeResourceKey(res.Key)));
}
}
private IEnumerable<Resource> GetResources(string resType)
{
List<Resource> availableResources = new List<Resource>();
IEnumerable<Resource> resources = Owner.Resources.GetResourcesByType(resType);
foreach (Resource res in resources)
{
if (IncludeResource(res))
{
availableResources.Add(res);
}
}
return availableResources;
}
private bool IncludeResource(Resource res)
{
return res.Available || ResourceIsInUse(res);
}
private string SerializeResourceKey(object key)
{
LosFormatter output = new LosFormatter();
StringWriter writer = new StringWriter();
output.Serialize(writer, key);
return writer.ToString();
}
private void MarkSelectedResources()
{
foreach (Resource res in Appointment.Resources.GetResourcesByType(Type))
{
ResourceValue.Items.FindByValue(SerializeResourceKey(res.Key)).Selected = true;
}
}
I'd think the code via the page load wouldn't be used in yours, you would just need to call the methods inside the conditional if statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: FBGraph on facebook fan page with Ruby on Rails 3 I have many doubts with fbgraph ruby gem. I understand if my page is a independent application which can connect to Facebook.
Now I don´t understand how I should take the user information if my page is on Facebook fan page. I know what Facebook send me params['signed_request'].
However I don't understand how and when I should use fbgraph ruby wrapper if my site is on Facebook fan page.
A: I add a filter in my application controller.
def parse_facebook
@auth = FbGraph::Auth.new(configatron.fb_authentication_app_key, configatron.fb_authentication_app_secret).from_signed_request params[:signed_request]
end
This could be modified for other scenarios however this is the simplest example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to animate CSS resize? I have the following CSS:
<style type="text/css">
#list { overflow:auto; }
#list li { float:left; margin-right:10px; }
div { width:500px; height:500px; border:1px solid gray; position:relative; }
iframe { border:0 none; width:100%; height:100%; display:block; }
span.togglebutton { position:absolute; left:0; top:0; background-color:black; padding:3px; color:white; }
div.maximized { position:fixed; top:0; left:0; width:100%; height:100%; border:0 none; z-index:9; }
</style>
This is being called:
$("span.togglebutton").click(function() {
var $this = $(this);
$this.closest("li").children("div").toggleClass("maximized");
});
Essentially it maximizes/minimizes my iFrame to be fullscreen. I want to animate the maximize and minimize. How can I go about doing this?
UPDATE
Here is my code using adeno's code:
$("span.togglebutton").click(function() {
var $this = $(this);
var currentText = $this.text();
var theFrame = $(this).closest("li").children("div");
if (currentText === "Maximize") {
$this.text("Minimize");
theFrame.animate({height: "100%", width: "100%"});
}
else {
$this.text("Maximize");
theFrame.animate({height: "50%", width: "50%"});
}
});
This works well, except I would like the maximize to take over the FULL screen. How can I do this?
A: There are ways to animate class transitions, but I think I would opt for something else.
Depends what minimized means, but you could look at toggle() instead of toggleClass() and drop the classes entirely as toogle allows animation, but hides the element completely.
Another option would be to just use animate() on height and width to maximize and minimize your iframe. With an if statement you could create a toggle effect on the sizes you wish to animate to and from.
There are some cross domain issues with iframes, but if it's working with toggleClass() it should probably work with animate() as well. Example assumes the iframe has an id of #myiframe, and it's not tested so there could be errors, just to show an example.
#myiframe { position:fixed; top:0; left:0; width:40%; height:40%; border:0 none; z-index:9; }
-
$("span.togglebutton").click(function() {
var elm = $(this).closest("li").children("div");
if (elm.css("height") == "40%") {
elm.animate({height: "100%", width: "100%"});
}
else {
elm.animate({height: "40%", width: "40%"});
}
});
Edit: Another option would be to set the iframe size in pixels and animate it to the size of the screen:
#myiframe { position:fixed; top:0; left:0; width:400px; height:400px; border:0 none; z-index:9; }
-
$("span.togglebutton").click(function() {
var H = window.height();
var W = window.width();
var elm = $(this).closest("li").children("div");
if (elm.css("height") == "400px") {
elm.animate({height: H, width: W});
}
else {
elm.animate({height: "400px", width: "400px"});
}
});
Maybe you could use that for someting, as not I'm not sure why the iframe does not animate to 100%, but it is probably constrained within an other element or someting like that, so it goes to 100%, only it does so within the element it is positioned in. Using absolute pixels gotten from the screen size should work, or maybe something inbetween? but unfortunately you can't mix pixels and percent in css/jQuery.
Using pixels would also require a function for updating the size on browser resize.
A: This is a little tricky to be quite honest... to make it behave correctly there is quite a lot that needs to be done.
Here is a working demo using jQuery
I hope you like it. I made it from scratch to ensure it would work. I added a (tool)bar on the top so it could hold my controls, with some tweaking you could make that an image and make the controls be right aligned to the container div.
Theres really no 'smarter' way to do this I think. The resize event bind / unbind is critical, without it this would break on a resize.
PS.; It's google that is making it a little wonky in the animation (it has resize events of it's own which are triggered constantly in the animation), I just couldn't think of a better website to use that also works in an iframe (stackoverflow doesn't).
Edit:
As per request in comments; here is a version for multiple frames on a page. Not thoroughly tested and could use some optimization but I am very tired so that is not going to happen today ;)
http://jsfiddle.net/sg3s/BT4hU/35/
A: This should be what your after:
Class Transitions
Not sure how well it'll transition with fixed positioning, there's sure to be a workaround though.
A: chain the animation to your toggleClass, http://api.jquery.com/animate/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cleaner way to implement moving a div back and forth using jQuery? I am trying to setup a simple example where a user can click a button on a page and divs are moved from one side of a parent div to another. If the button is clicked again the divs should move back to their original position.
I have successfully set this up, but the code feels a little clumsy to me. Can anyone recommend a cleaner way to do this than what I have done below:
var operator = '+=';
$('#clickme').click(function() {
$('#main div:even').animate({
left:operator + '200'
}, 2000);
if(operator == '+='){operator = '-=';}
else{operator = '+=';}
});
The if/else at the end of my click event is the part that seems odd to me. Any suggestions for prettying this up?
You can play with the fiddle here:
http://jsfiddle.net/S6UtE/3/
A: I would keep the += and change the 200 to -200 and back again:
var move = 200;
$('#clickme').click(function() {
$('#main div:even').animate({
left:"+="+move
}, 2000);
move = -move;
});
http://jsfiddle.net/S6UtE/7/
A: I don't know if you would consider this better or not?
var rightd = true;
$('#clickme').click(function() {
$('#main div:even').animate({
left:(rightd ? "+=" : "-=") + '200px'
}, 2000);
rightd = !rightd;
});
http://jsfiddle.net/S6UtE/6/
A: You could have a 2-element array containing '+=' and '-=' at spots 0 and 1, and do something like this:
var operat0rindex = 0;
$('#clickme').click(function() {
var operator = operators[operatorindex];
//operatorindex = (operatorindex + 1) % 2
//or more quickly/simply:
operatorindex = 1 - operatorindex;
$('#main div:even').animate({
left:operator + '200'
}, 2000);
});
A: You could use jQuery.data() to avoid a global var. Something like this:
$('#clickme').click(function() {
var moved = $('#main div:even').data('moved');
var operator = moved ? '-=' : '+=';
$('#main div:even').data('moved', !moved);
$('#main div:even').animate({
left:operator + '200'
}, 2000);
});
A: There is another option that may not have been considered.
$('#clickme').click(function() {
$('#main div:even').each(function(index, element) {
var $this = $(this);
$this.animate({
left: parseFloat($this.css("left")) >= 200 ? "-=200" : "+=200"
}, 2000);
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: sql select duplicate records once Lets say I have 5 rows with the same data
|id|
--
|1 |
--
|1 |
--
|1 |
--
|1 |
if I echo those results out I'm gonna get 1111 but I only want to select duplicate records one, so instead I would get 1.
is this possible?
A: GROUP BY id; in your mysql statement
Although I am not sure why you have duplicate IDs in your database -- that should be remedied.
A: You can either SELECT DISTINCT to remove rows in the result that have all columns the same or you can GROUP BY the columns you want to select which is useful if you want to get a count of the rows that have duplicates.
A: GROUP BY id
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
or
SELECT DISTINCT(id) from table
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What MDAs are useful to track a heap corruption? I have a heap corruption in a .NET/C# program and cannot track it with WinDbg + PageHeap + Application Verifier. In the next step, I plan to use Managed Debugging Assistants (MDAs).
Currently I try using these MDAs:
<gcManagedToUnmanaged />
<gcUnmanagedToManaged />
<invalidVariant />
(Having these MDAs enabled makes the program run very slowly.)
Are there any other I can try in this case?
A: As Hans Passant pointed out, the primary MDA for such cases would be <gcUnmanagedToManaged>. However, this MDA makes the program run very slow. Actually, the program becomes unusable (it takes "forever" to draw the program interface), thus it won't work in production. Visually this MDA is as slow as GCStress.
Other useful MDAs (work must faster):
<callbackOnCollectedDelegate />
<invalidOverlappedToPinvoke />
<overlappedFreeError />
To learn more about available MDAs and their detailed description, refer to the MSDN article Diagnosing Errors with Managed Debugging Assistants.
A good article on how to set MDAs for a program is Managed Debugging Assistants in .NET 2.0.
And finally, how to activate MDAs in the system, see Stack Overflow question .NET/C#: How to set debugging environment variable COMPLUS_HeapVerify?.
A: Try one of the commercial tools such as Red Gate's ANT's Memory Profiler or Jetbrain's DotTrace. I use ANTs Memory Profiler and was able to detect the memory leaks and fix the code that was causing the memory leaks, which may eventually lead to heap corruption. Here is an article on finding memory leaks using ANTs Memory Profiler
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is my seam app only deploying partially? I have a seam app that my colleague created. It is maven-based. I'm trying to get make it work in eclipse which is baffling in itself, but I managed to get rid of all the eclipse "Problems" (as displayed in the problem view) and the app builds successfully, both from the command line and from within eclipse.
The difficulty is when I deploy the app to the jboss server (Jboss 5.1) the deployment only gets as far as JSF and never starts the Seam section. So the logfile looks like this
13:15:23,087 INFO [EJBContainer] STARTED EJB: org.jboss.seam.transaction.EjbSynchronizations ejbName: EjbSynchronizations
13:15:23,107 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
nccm-app/EjbSynchronizations/local - EJB3.x Default Local Business Interface
nccm-app/EjbSynchronizations/local-org.jboss.seam.transaction.LocalEjbSynchronizations - EJB3.x Local Business Interface
13:15:23,357 INFO [TomcatDeployment] deploy, ctxPath=/nccm
13:15:23,448 INFO [config] Initializing Mojarra (1.2_13-b01-FCS) for context '/nccm'`
and stops. A working app continues with seam:
2011-09-16 11:59:48,494 INFO [javax.servlet.ServletContextListener] (HDScanner) Welcome to Seam 2.2.0.EAP5
Something must be missing in my EAR file, but I can't figure out what. The seam library is definitely there. Any way to tell what I am missing?
A: Hanging on Initializing Mojarra can mean at least 2 things:
*
*There is not enough memory. Increase your container's heap space. Start at 512M, depending on your webapp's size.
*There is a conflict in JSF-related libraries. Ensure that all versions are compatible with each other (JSF, Seam, RichFaces, etc). Ensure that you understand that JBoss ships with its own set of JSF api/impl libraries and that you should not include any in your webapp's /WEB-INF/lib (i.e. mark it as provided in Maven). Or, if you want to override JBoss from loading its builtin JSF libs and prefer the webapp-included libraries, then you should add the following context parameter to the webapp's web.xml to tell JBoss to use the WAR-bundled JSF impl instead:
<context-param>
<param-name>org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL</param-name>
<param-value>true</param-value>
</context-param>
A: Check that you have seam.properties file (may be empty) in your resulting files.
For war assemblies it should be presented here:
\WEB-INF\classes\seam.properties
For jar assemblies (which have seam bean declarations) it should be here:
\classes\seam.properties
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Asynchronously delay JS until a condition is met I have a class, ChatRoom, that can only render after it receives a long-running HTTP request (it could take 1 second or 30 seconds). So I need to delay rendering until ChatRoom.json is not null.
In the code below, I'm using Closure Library's goog.async.ConditionalDelay. It works, but is there a better way (maybe without needing Closure Library) to do this?
ChatRoom.prototype.json = null; // received after a long-running HTTP request.
ChatRoom.prototype.render = function() {
var thisChatRoom = this;
function onReady() {
console.log("Received JSON", thisChatRoom.json);
// Do rendering...
}
function onFailure() {
alert('Sorry, an error occurred. The chat room couldn\'t open');
}
function isReady() {
if (thisChatRoom.json != null) {
return true;
}
console.log("Waiting for chat room JSON...");
return false;
}
// If there is a JSON request in progress, wait until it completes.
if (isReady()) {
onReady();
} else {
var delay = new goog.async.ConditionalDelay(isReady);
delay.onSuccess = onReady;
delay.onFailure = onFailure;
delay.start(500, 5000);
}
}
Note that "while (json == null) { }" isn't possible because that would be synchronous (blocking all other JS execution).
A: Consider this:
(function wait() {
if ( chatroom.json ) {
chatroom.render();
} else {
setTimeout( wait, 500 );
}
})();
This will check every half second.
Live demo: http://jsfiddle.net/kBgTx/
A: You could also achieve this using lodash's debouncer with recursion.
import _debounce from 'lodash/debounce';
const wait = (() => {
if ( chatroom.json ) {
chatroom.render();
} else {
_debounce(wait, 500)();
}
})();
A: we can use await new Promise((resolve) and call resolve when our condition is true :
we can run whole code in browser with audioPermission On.
(async () => {
const getVolume = async () => {
let n = 0;
let abc = async () => {
let count = 0;
try {
let audioStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
},
});
let audioContext = new AudioContext();
let audioSource = audioContext.createMediaStreamSource(audioStream);
let analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
analyser.minDecibels = -127;
analyser.maxDecibels = 0;
analyser.smoothingTimeConstant = 0.4;
audioSource.connect(analyser);
let volumes = new Uint8Array(analyser.frequencyBinCount);
console.log("volume__________________");
console.log(volumes);
await new Promise((resolve) => {
const timer = setInterval(() => {
count += 1;
console.log("count = " + count);
analyser.getByteFrequencyData(volumes);
console.log("volume__________________");
console.log(volumes);
if (count == 3 || volumes[0] > 0) {
clearInterval(timer);
n = volumes[0];
console.log("count__________________" + count);
resolve(n);
}
}, 2000);
});
} catch (e) {
console.error(
"Failed to initialize volume visualizer, simulating instead...",
e
);
return 0;
}
console.log("n inside______________ = " + n);
return n;
};
await abc();
return n;
};
let t = await getVolume();
console.log(t);
})();
A: The answer I came up with is like this:
var count = 0;
// Number of functions that need to run. This can be dynamically generated
// In this case I call check(data, cb) a total of 3 times
var functionNum = 3;
function toCallAfter(){
console.log('I am a delayed function');
}
I had this for a check function that ran once regularly and twice in a loop:
check(data, function(err){ // check is my asynchronous function to check data integrity
if (err){
return cb(null, { // cb() is the return function for the containing function
errCode: 'MISSINGINFO',
statusCode: 403,
message : 'All mandatory fields must be filled in'
});
} // This part here is an implicit else
count++; // Increment count each time required functions complete to
// keep track of how many function have completed
if (count === functionNum) {
return anon();
}
return;
});
// Run twice more in a loop
for(var i = 0; i < 2; i++) {
check(data, function(err) { // calls check again in a loop
if (err){
return cb(null, {
errCode: 'MISSINGINFO',
statusCode: 403,
message : 'All mandatory fields must be filled in'
});
}
count++;
if (count === functionNum) {
return toCallAfter();
}
return;
});
}
Lastly, I'd like to point out a significant performance fault in the alternate (and extraordinarily common) answer:
(function wait() {
if ( chatroom.json ) {
chatroom.render();
} else {
setTimeout( wait, 500 );
}
})();
In this case, you are essentially holding the browser or server (If using node.js) hostage for 500 milliseconds for every check which is an incredibly long time for a computer. Meaning a huge performance hit. My solution of directly keeping track of the required completed functions is free from time restraints and will run instantly as soon as all functions complete.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Simple PHP application to create URL's like /twitter_username I am making a simple php application which uses twitter to login as shown in the example here at http://www.1stwebdesigner.com/tutorials/twitter-app-oauth-php/
However, instead of going to a page where the user posts a tweet, I want to redirect the user to a URL /twitter_user_name where he can see his twitter profile information.
Also, this page needs to be publicly viewable at /twitter_user_name as the profile page of the person. I am not sure how I can create URL's like /twitter_user_name.
I am not using any framework as such.
My DB structure for the users table is:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`oauth_uid` text,
`oauth_token` text,
`oauth_secret` text,
`is_logged_in` boolean,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
How do I accomplish this without using any framework?
A: Simple, use mod_rewrite in a .htaccess file:
RewriteEngine on
RewriteRule ^twitter_(.*)$ twitter_profile.php?username=$1 [L]
twitter_profile.php will be called with GET param (username) as $1
You can learn about mod_rewrite and .htaccess here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.