text stringlengths 8 267k | meta dict |
|---|---|
Q: Is there a way to make LostFocus fire when the keyboard focus leaves a focus scope? My application's building a UI dynamically in which each ItemsControl in the view is a focus scope. The items displayed by each ItemsControl are controls in its focus scope. The user can tab through all of the controls in the view from start to end (i.e. the keyboard navigation mode is Continue). These controls are all bound to data source properties.
What seems to be happening is that when I'm on the last control in the first focus scope and press TAB, the keyboard focus moves to the second focus scope, but the previous control doesn't lose logical focus. So the bound property doesn't get updated.
I can make this problem go away (in theory, at least) by not making each ItemsControl a focus scope. But I didn't decide to implement logical focus capriciously: there are things the application needs to do when each ItemsControl loses logical focus, and if I get rid of the focus scopes it's going to be hard to make that happen.
This seems like a problem that should have a straightforward solution, but nothing in the documentation seems to suggest a way around it. Any ideas?
A: The problem is that you're trying to make logical focus in-line with keyboard focus which as the documentation shows is really not how it is supposed to be used. Logical focus provides a way to maintain what the previous control that had focus in a given focus scope so you can refocus again on it when you regain keyboard focus.
Looking at your question I think what you really want to do is pick up the event when your item contol, or one of the visual child elements, loses keyboard focus. This can
be achieved using IsKeyboardFocusedWithin property and you can trigger actions based on the associated event.
If you need this to be a routed event, then you'll need a custom control like follows which exposes a routing event for gaining and losing focus.
public partial class FocusManagingControl : UserControl
{
public static readonly RoutedEvent KeyboardLostFocusWithinEvent = EventManager.RegisterRoutedEvent("KeyboardLostFocusWithin",
RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FocusManagingControl));
public static readonly RoutedEvent KeyboardGotFocusWithinEvent = EventManager.RegisterRoutedEvent("KeyboardGotFocusWithin",
RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FocusManagingControl));
public event RoutedEventHandler KeyboardLostFocusWithin
{
add { AddHandler(KeyboardLostFocusWithinEvent, value); }
remove { RemoveHandler(KeyboardLostFocusWithinEvent, value); }
}
public event RoutedEventHandler KeyboardGotFocusWithin
{
add { AddHandler(KeyboardGotFocusWithinEvent, value); }
remove { RemoveHandler(KeyboardGotFocusWithinEvent, value); }
}
public FocusManagingControl()
{
this.InitializeComponent();
this.IsKeyboardFocusWithinChanged += FocusManagingControl_IsKeyboardFocusWithinChanged;
}
private void FocusManagingControl_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if((bool)e.OldValue && !(bool)e.NewValue)
RaiseEvent(new RoutedEventArgs(KeyboardLostFocusWithinEvent, this));
if(!(bool)e.OldValue && (bool)e.NewValue)
RaiseEvent(new RoutedEventArgs(KeyboardGotFocusWithinEvent, this));
}
}
Which you can use in your XAML with the entry
<local:FocusManagingControl>
<local:FocusManagingControl.Triggers>
<EventTrigger RoutedEvent="local:FocusManagingControl.KeyboardLostFocusWithin">
....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using mylyn outside eclipse - task management/time tracking tool I left Eclipse over two year ago in favor of Jetbrains products (PhpStorm and RubyMine). The only feature I miss from Eclipse is Mylyn. Until now I use it only for convenience in organizing things, what I need now for a project is its time tracking feature.
Is there any way to use Mylyn outside Eclipse?
Alternatively, is there any automatic tool/plugin for Jetbrains IDE (or for the OS itself, in my case OS X) which tracks spent time inside projects/tasks?
A: Disclaimer: I work for Tasktop Technologies.
You can use Tasktop's standalone application to track time. Tasktop has the added advantage that it can also track non-code artifacts (like spreadsheets, documents, presentations, images, etc.) and keep track of them but connected to your task. (In Mylyn-speak, it will add them to your context.)
There is not a Mylyn-esque plugin for Jetbrains IDE that I know of.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Not clear on this jQuery syntax: return !$() I saw this code and I'm not clear what the '!' does in this line of jQuery code on the return on the jQuery object:
$('#remove').click(function() {
return !$('#select2 option:selected').appendTo('#select1');
});
EDIT
What is a good case to do this?
A: It converts the result of $('#select2 option:selected').appendTo('#select1') to a boolean, and negates it.
However, as the result of appendTo is always a jQuery object, and an object (jQuery or not) is always truthy, the result of !$('#select2 option:selected').appendTo('#select1') is always false.
So what we have is effectively:
$('#remove').click(function() {
$('#select2 option:selected').appendTo('#select1');
return false;
});
Returning false in a jQuery event handler will stop the default event action occuring (e.g. the submission of a form/ navigation of a hyperlink) and stop the event propagating any further up the DOM tree.
So what we have is effectively:
$('#remove').click(function(e) {
$('#select2 option:selected').appendTo('#select1');
e.preventDefault();
e.stopPropagation();
});
Using return false instead of e.preventDefault(); e.stopPropagation(); is OK, but using the return !$(..) as a shortcut for the first example is ridiculous, and there is no need to do it.
Just to reiterate my point, the most important thing to note here is that there is never, ever a good reason/ case to do this.
Links:
*
*Docs for bind() (alias for click())
*Docs for preventDefault()
*Docs for stopPropagation()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to convert string to integer when I try to access the data in json converted to hash in ruby? I have converted the data in json to a hash and tried to access the data. I used the following code:
require 'yajl'
json=File.new('5104.txt', 'r')
parser=Yajl::Parser.new
hash=parser.parse(json)
puts hash['response']['venue']['id']
puts hash['response']['venue']['name']
puts hash['response']['venue']['categories']['parents']
When I run this code, I had this error message says:
test.rb:8:in `[]': can't convert String into Integer (TypeError)
from test.rb:8:in `<main>'
I assume it means that the data type of 'parents' is string which cannot be converted to integer. Does anyone know how should I solve this problem? Is there anyway I can convert this string into integer and save it?
Thanks ahead and I really appreciate your help.
Thanks a lot for your answers. Line 8 is the last line for 'parents'. I can use this code to get 'id' and 'name', but cannot get the data for 'parent'. Here is the json;
response: {
venue: {
id: "xxx"
name: "xxx"
contact: {
phone: "xxx"
formattedPhone: "xxx"
twitter: "theram"
}
location: {
address: "xxx"
lat: xxx
lng: xxx
postalCode: "xxx"
city: "xxx"
state: "xxx"
country: "xxx"
}
categories: [
{
id: "xxx"
name: "xxx"
pluralName: "xxx"
shortName: "xxx"
icon: "xxx"
parents: [
"xxx"
]
primary: true
}
]
}
}
I converted the json to a hash. If it is the case that this json is an array which requires integers for its keys, is there anyway that I can convert this string into an integer so that I can still use this code to get the data I want? If not, is there any other ways that I can get data for 'parents'? Regular expression?
Thanks ahead :)
A: Categories is an array, you should get an item before trying to get the parents:
hash['response']['venue']['categories'].first['parents']
There's also a primary parameter, if there could be more than one category and want to get the primary one, use Array#select:
hash['response']['venue']['categories'].select {|category| category['primary'] } .first['parents']
A: Are you absolutely positive that what you're getting out of the JSON is a hash? Because that error message generally means you're trying to access an array with a non-integer key.
I'm guessing that your JSON is actually an array, and ruby is dutifully complaining that you're not treating it like one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Excel add one hour I have in cel A1 with the following contents:
7:30:43
which is a time.
But now i want to use a formula to add one hour. What is the best way or how can i do this?
A: In cell A1, enter the time.
In cell B2, enter =A1+1/24
A: =A1+TIME(1,0,0)
Although, maybe this should be posted on Super User.
A: This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.
=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))
You can also substitute TIME with DATE to add or subtract a date or time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
} |
Q: How can I capture this through a regex? I have some text like this:
ABCPQR01 is not at all good
EFHSTU39 is somewhat nicer
and I want to capture the ABC... and EFH... type words. The first set of three letters can be ABC or EFH and the second set of three letters can be PQR or STU. Instead of writing two separate regexes to capture these two text elements, how can I write this as a single re.compile statement? Any suggestions?
A: >>> re.match('(ABC|EFH)(PQR|STU)', 'ABCPQR01 is not at all good').groups()
('ABC', 'PQR')
A: I think this would be a pattern which would work :)
>>> re.compile("^(ABC|EFH)(PQR|STU)\d\d\b")
also you can test it at http://www.regextester.com/index2.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to implement wxScrolledWindow without changing the whole project? I have a UI, whose class is initialized as such:
class SimpleUI : public wxFrame
From the main.cpp, I initialize:
SimpleUI *ui = new SimpleUI(wxT("Simple User Interface"));
ui->Show();
After some progressing, I realized that I needed a vertical and horizontal scrollbar to be able to use that UI on computers, which have smaller screen resolutions. Now I want to change my wxFrame rooted SimpleUI class with wxScrolledWindow. I replaced wxFrame with wxScrolledWindow, but it can't be initialized without any parent window.
What should I do to implement toolbars to my project? Are there alternatives?
Thanks.
A: There seem to be two questions here. A suggestion for the first question:
class SimpleUI : public wxScrolledWindow
{
SimpleUI( wxWindow * parent )
: wxScrolledWindow( parent )
{
...
}
...
}
SimpleUI *ui = new SimpleUI( new wxFrame(NULL,-1,wxT("Simple User Interface")));
ui->Show();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Removing char from string? I am searching for the following text in an input string: +Bob
If the program finds +Bob, I want it to remove the + before Bob
However, I do not want the program to eliminate all +'s, just +'s before or after Bob, with or without intervening whitespace. So a string for example of: + Bob still counts as +Bob.
A: String str = "+Bob foo + bar";
str = str.replace("+Bob", "Bob");
System.out.println(str);
Bob foo + bar
To handle a space between + and Bob you can use regular expressions:
String str = "+Bob foo + bar";
str = str.replaceAll("\\+\\s*Bob", "Bob");
To check for a plus afterwards, use
str = str.replaceAll("Bob\\s*\\+", "Bob");
A: public class Test {
public static void main(String[] args) throws Exception {
String regexp = "(?)\\+(\\s?)+Bob";
System.out.println("+Bob foo + bar".replaceAll(regexp, "Bob"));
System.out.println("+ Bob foo + bar".replaceAll(regexp, "Bob"));
System.out.println("+ Bob foo + bar +Bob".replaceAll(regexp, "Bob"));
System.out.println("+ Bob foo + bar + Bob".replaceAll(regexp, "Bob"));
}
}
/* output :
Bob foo + bar
Bob foo + bar
Bob foo + bar Bob
Bob foo + bar Bob
*/
A: Sorry I downvoted you guys because the answer is: use StringBuffer.deleteCharAt(int Index)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 'Uncaught Error: DATA_CLONE_ERR: DOM Exception 25' thrown by web worker So I'm creating a web worker:
var arrayit = function(obj) {
return Array.prototype.slice.call(obj);
};
work = arrayit(images);
console.log(work);
//work = images.push.apply( images, array );
// Method : "load+scroll"
var worker = new Worker('jail_worker.js');
worker.postMessage(work)
worker.onmessage = function(event) {
console.log("Worker said:" + event.data);
};
Here's what images is:
$.jail.initialStack = this;
// Store the selector into 'triggerEl' data for the images selected
this.data('triggerEl', (options.selector) ? $(options.selector) : $window);
var images = this;
I think my problem has something to do with this:
http://dev.w3.org/html5/spec/Overview.html#safe-passing-of-structured-data
How can I get around this? as you can see, I tried slicing the host object into a real array, but that didn't work.
Here's a link to the file I'm hacking on:
https://github.com/jtmkrueger/JAIL
UPDATE--------------------------------------------------
This is what I had to do based on the accepted answer from @davin:
var arrayit = function(obj) {
return Array.prototype.slice.call(obj);
};
imgArray = arrayit(images);
work = _.map(images, function(i){ return i.attributes[0].ownerElement.outerHTML; });
var worker = new Worker('jail_worker.js');
worker.postMessage(work)
worker.onmessage = function(event) {
console.log("Worker said:" + event.data);
};
NOTE: I used underscore.js to assure compatibility.
A: The original exception was most likely thrown because you tried passing a host object to the web worker (most likely a dom element). Your subsequent attempts don't throw the same error. Remember two key points: there isn't shared memory between the different threads, and the web workers can't manipulate the DOM.
postMessage supports passing structured data to threads, and will internally serialise (or in some other way copy the value of the data recursively) the data. Serialising DOM elements often results in circular reference errors, so your best bet is to map the object you want serialised and extract relevant data to be rebuilt in the web worker.
A: Uncaught DataCloneError: An object could not be cloned was reproduced when tried save to indexeddb function as object's key. Need double recheck that saved object is serializable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: What is the current status of GHC on 64 bit Windows? My current understanding is
*
*No 64-bit GHC, ticket #1884
*The 32-bit GHC and the binaries it builds work just fine because the Windows OS loader converts OS calls and pointers to 64 bits. The same applies to DLLs
*No mixing 32 bit and 64 bit code (ie. your 32 bit Haskell DLL isn't going to be friends with the 64 bit program that wants to use it)
*Latest discussion is a thread started on May 2011
Is this correct? Are there any pitfalls to watch out for, particularly as an FFI user? For example, if I were to export some Haskell code as a 32 bit DLL to some Windows program, should I expect it to work?
Edit: looks like you'd need a 64 bit DLL to go with a 64 bit process
A: I don't know if anyone's actively working on a 64-bit codegen right now, but 32-bit haskell will work just fine as long as you're only talking to 32-bit FFI libraries (and/or being embedded in 32-bit host programs). If you want to interact with 64-bit programs, you will need to use some form of IPC, as 32-bit and 64-bit code cannot coexist in one process.
A: 64-bit windows is supported now. There is binary a distribution of 64-bit GHC.
No 64-bit Haskell Platform yet though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: asp.net calling code inline not working In my code behind, I can do the following in the onload:
string x = Fmg.Cti.UI.Utilities.Classes.ResourceController.ReadResourceValue("Riblet", "Riblet_Chicklet1_Button_text");
This works without issue.
In my aspx page (I didn't remove the code from the onload), I put this:
<%= Fmg.Cti.UI.Utilities.Classes.ResourceController.ReadResourceValue("Riblet", "Riblet_Chicklet1_Button_text")%>
When I do, I got an error:
error CS0234: The type or namespace name 'Cti' does not exist in the
namespace 'Fmg' (are you missing an assembly reference?)
I had this (or something quite similar) working. I don't know how I broke it.
Thanks again for your help.
A: You need to register the assemblies you're using in your page as well (just like usings in your code behind). See Do I have to add "<%@ Register assembly=" to every page?
A: Do you have that namespace imported? For asp.net you can do something like the following to make namespaces available for inline coding.
<%@ Import Namespace="Fmg.Cti.UI.Utilities.Classes" %>
You can make namespaces generally available to all of your asp.net pages for inline coding by adding the namespaces into the web.config
<system.web>
<pages>
<namespaces>
...
<add namespace="Fmg.Cti.UI.Utilities.Classes" />
...
</namespaces>
</pages>
</system.web>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Declare Inside a Function in Bash I am want to change a global variable (or at least append to it) using a function.
input="Hello"
example=input
func() {
declare -x $example="${input} World"
}
func
echo $input
The output of this would be "Hello" The original value. I would like it if the function were to able to change the original value. Is there alternative to accomplishing this. Please note I need to set example=input and then perform on the operation on example (the variable).
BTW, if I used eval instead the function will complain about World being a function or something.
A: Did you try using export?
export $example="${input} World"
A: you should use
declare -x -g $example="${input} World"
in your func
The -g option forces variables to be created or modified at the global scope, even when declare is executed in a shell function. It is ignored in all other cases.
see
http://www.gnu.org/software/bash/manual/bashref.html
Also note in MinGW, it seems that declare does not support the -g option.
A: You could use eval by redefining func() as the following:
func() {
eval $example=\"${input} World\"
}
This allows the double-quotes to "survive" the first parsing (which expands the variables into their values, as needs to be done) so that eval starts parsing again with the string 'input="Hello World".
As for the use of export to do the job, if the variable input does not actually need to be exported, include its '-n' option:
export -n $example=...
, and the variable remains a shell variable and does not get exported as an environment variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Apply jqueryUI interaction attributes to newly added DOM elements? So I start off with an element of class="list" that are defined as .sortable. Now if I create another element of class="list" via jquery, it does not inherit the same definition that I had already defined.
Now, I got around that by throwing the definition into a function and then call the function upon initial load and as well as every time I add a new element. Is this the best method? Or is there a more appropriate method of doing this?
http://jsfiddle.net/S24d4/11/
A: You probably want jQuery's .live() function. This will bind things to DOM elements added later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Attach a .Change event to a Radiobutton list. (Values bound at run time) How can i attach a .change event to a radiobuttonlist which has its values bound at runtime
rbSecurity.dataSource = Data();
rbSecurity.dataBind();
I want to hide a dropdownlist (ddlContact) based on certain selection in the rbSecurity
I tried this but doesn't work:
$("#<%=rbSecurity.ClientID%> input[name*='Security']").change(function () {
if ($("input[@name=GroupName]:checked").val() != 'Value1') {
$('#<%=ddlApprovers.ClientID %>').hide();
}
else {
$('#<%=ddlApprovers.ClientID %>').show();
}
}
});
Thanks in advance
A: You could attach a change handler to every radio button in your RadioButtonList that takes action only when the radio button is checked. For instance:
Control declaration:
<asp:RadioButtonList ID="rbSecurity" runat="server" />
jQuery:
$("#<%=rbSecurity.ClientID%> input:radio").change(function() {
if (this.checked) {
if (this.value == "Value1") {
$("#<%=ddlContact.ClientID %>").show();
}
else {
$("#<%=ddlContact.ClientID %>").hide();
}
}
}).filter(":checked").change();
Notice in the jQuery snippet I also suggest you fire an initial change event for the radio button that is checked on page load.
In the code's if block, you could test this.value to see if it is part of a valid set of values and call .show() for a particular selector, and if it is not, .hide() that selector instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Camera extrinsics calculation wrong I am trying to find camera extrinsics from 2 images. I have the intrinsics from CameraCalibration and the scene has known dimensions (created with 3DSMAX).
The chessboard is 1000*1000, each square thus 125*125. The camera is at (0,0,3000) looking straight down at the chessboard which is centred at the origin. In the second image, the camera is translated (-1500, 0, -402) and rotated 30° on the Y axis to point again to the centre of the chessboard:
GoodFeaturesToTrack correctly identifies the 81 corners:
I create the 3d points of the chessboard corners, cvFindExtrinsicCameraParams2 to compute the intrinsics and cvRodrigues2 to get the rotation matrix. Here's the code
Imports Emgu.CV
Imports Emgu.CV.Structure
Imports Emgu.CV.CvInvoke
Imports Emgu.CV.CvEnum
Imports Emgu.CV.UI
Imports System.Drawing
Imports System.IO
Imports System.Diagnostics
Imports System.Math
Module main_
Sub Main()
Const MAXFEATURES As Integer = 100
Dim featuresA(0)() As PointF
Dim featuresB(0)() As PointF
Dim features As Integer = 0
Dim imgA As Emgu.CV.Image(Of Emgu.CV.Structure.Bgr, Byte)
Dim imgB As Emgu.CV.Image(Of Emgu.CV.Structure.Bgr, Byte)
Dim grayA As Emgu.CV.Image(Of Emgu.CV.Structure.Gray, Byte)
Dim grayB As Emgu.CV.Image(Of Emgu.CV.Structure.Gray, Byte)
Dim pyrBufferA As Emgu.CV.Image(Of Emgu.CV.Structure.Gray, Byte)
Dim pyrBufferB As Emgu.CV.Image(Of Emgu.CV.Structure.Gray, Byte)
Dim pointsA As Matrix(Of Single)
Dim pointsB As Matrix(Of Single)
Dim flags As Emgu.CV.CvEnum.LKFLOW_TYPE = Emgu.CV.CvEnum.LKFLOW_TYPE.DEFAULT
Dim imagesize As Size
Dim termcrit As New Emgu.CV.Structure.MCvTermCriteria(20, 0.03D)
Dim status As Byte() = Nothing
Dim errors As Single() = Nothing
Dim red As Bgr = New Bgr(Color.Red)
' Load chessboards
imgA = New Image(Of [Structure].Bgr, Byte)("chessboard centre.jpg")
imgB = New Image(Of [Structure].Bgr, Byte)("chessboard left.jpg")
grayA = imgA.Convert(Of Gray, Byte)()
grayB = imgB.Convert(Of Gray, Byte)()
' setup for feature detection
imagesize = cvGetSize(grayA)
pyrBufferA = New Emgu.CV.Image(Of Emgu.CV.Structure.Gray, Byte)(imagesize.Width + 8, imagesize.Height / 3)
pyrBufferB = New Emgu.CV.Image(Of Emgu.CV.Structure.Gray, Byte)(imagesize.Width + 8, imagesize.Height / 3)
features = MAXFEATURES
' Find features
featuresA = grayA.GoodFeaturesToTrack(features, 0.01, 25, 3)
grayA.FindCornerSubPix(featuresA, New System.Drawing.Size(10, 10), New System.Drawing.Size(-1, -1), termcrit)
features = featuresA(0).Length
' Compute optical flow. Not necessary here but good to remember
Emgu.CV.OpticalFlow.PyrLK(grayA, grayB, pyrBufferA, pyrBufferB, featuresA(0), New Size(25, 25), 3, termcrit, flags, featuresB(0), status, errors)
Debug.Assert(featuresA(0).GetUpperBound(0) = featuresB(0).GetUpperBound(0))
' Copy features to an easier-to-use matrix and get min/max to create 3d points
Dim minx As Double = Double.MaxValue
Dim miny As Double = Double.MaxValue
Dim maxx As Double = Double.MinValue
Dim maxy As Double = Double.MinValue
pointsA = New Matrix(Of Single)(features, 2)
pointsB = New Matrix(Of Single)(features, 2)
For i As Integer = 0 To features - 1
pointsA(i, 0) = featuresA(0)(i).X
pointsA(i, 1) = featuresA(0)(i).Y
pointsB(i, 0) = featuresB(0)(i).X
pointsB(i, 1) = featuresB(0)(i).Y
If pointsA(i, 0) < minx Then
minx = pointsA(i, 0)
End If
If pointsA(i, 1) < miny Then
miny = pointsA(i, 1)
End If
If pointsA(i, 0) > maxx Then
maxx = pointsA(i, 0)
End If
If pointsA(i, 1) > maxy Then
maxy = pointsA(i, 1)
End If
Next
' Create 3D object points that correspond to chessboard corners
' (The chessboard is 1000*1000, squares are 125*125)
Dim corners As Integer = Sqrt(features)
Dim obj As New Matrix(Of Double)(features, 3)
Dim squaresize2dx As Double = (maxx - minx) / 8 ' pixel width of a chessboard square
Dim squaresize2dy As Double = (maxy - miny) / 8 ' pixel height of a chessboard square
For i As Integer = 0 To features - 1
obj(i, 0) = Math.Round((pointsA(i, 0) - minx) / squaresize2dx) * 125 ' X=0, 125, 250, 375 ... 1000
obj(i, 1) = Math.Round((pointsA(i, 1) - miny) / squaresize2dy) * 125 ' idem in Y
obj(i, 2) = 0
' Debug.WriteLine(pointsA(i, 0) & " " & pointsA(i, 1) & " " & obj(i, 0) & " " & obj(i, 1) & " " & obj(i, 2)) ' Just to verify
Next
' These were calculated with CalibrateCamera using the same images
Dim intrinsics As New Matrix(Of Double)({{889.1647, 0.0, 318.3721},
{0.0, 888.5134, 238.4254},
{0.0, 0.0, 1.0}})
' Find extrinsics
Dim distortion As New Matrix(Of Double)({-0.036302, 2.008797, -29.674306, -29.674306})
Dim translation As New Matrix(Of Double)(3, 1)
Dim rotation As New Matrix(Of Double)(3, 1)
cvFindExtrinsicCameraParams2(obj, pointsA, intrinsics, distortion, rotation, translation, False)
' Convert rotation vector to rotation matrix
Dim rotmat As New Matrix(Of Double)(3, 3)
Dim jacobian As New Matrix(Of Double)(9, 3)
cvRodrigues2(rotation, rotmat, jacobian)
' From http://en.wikipedia.org/wiki/Rotation_representation paragraph "Conversion formulae between representations"
Dim yr As Double = Asin(-rotmat(2, 0))
Dim xr As Double = Asin(rotmat(2, 1) / Cos(yr))
Dim zr As Double = Asin(rotmat(1, 0) / Cos(yr))
End Sub
End Module
The results don't seem correct, I was expecting the translation/rotation but i get this:
translation
208.394425348956
-169.447506344527
-654.273807995629
rotation
-0.0224937226554797
-2.13660350939653
-1.10542281290682
rotmat
-0.741100224945266 0.322885083546921 -0.588655824237707
-0.293966101915684 0.632206237134128 0.716867633983572
0.603617749499279 0.704315622822328 -0.373610915174894
xr=1.08307908108382 yr=-0.648031006135158 zr=-0.377625254910525
xr=62.0558602250101° yr=-37.1294416451609° zr=-21.636333343925°
Would someone have an idea what I'm doing wrong? Thanks!
A: Found it. The distortion coefficients are
k1, k2, p1, p2, k3
and not
k1, k2, k3, k4, k5
as I had coded. When I set them to
-0.05716, 2.519006, -0.001674, -0.001021, -33.372798
the answer is (roughly) correct
A: Please look at the pin hole camera equation:
[u, v, 1]' ~ A * R|T * [x, y, z, 1]', where extrinsic matrix
R|T has dimensions 3x4. Note that multiplying it with the 'ideal' or vanishing point at infinity such as [1,0,0,0] will give you a corresponding column of R|T. This simply means that to find all columns of R|T you have to have at least three vanishing points that can be easily found from your checkerboard patterns.
For now you have only 1, so you simply got lucky if your results look reasonable. Try again and select minimum 10-20 different slants, distances and tilts of the calibration rig.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: email to php - working with large attachments Using this tutorial Use Email Piping to Save Email Attachments I'm on the way to making my own posterous type app - however, when I send large attachments (over 10k), they don't get uploaded? Everything else works a treat!
Is there some php.ini setting I've missed, or something to do with the max time on the php
script?
EDIT: it would seem that the issues is in fact sending image files (jpg/pdf) from Apple's Mail client is the issue as it works fine using googlemail - Must have something to do with Mail putting the files in the main body??
Many thanks
A: Thanks for the comments - turns out the issue was only inline attachments (i.e. sent from apple mail) and the script wasn't interpreting them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to convert from lazy text to non-lazy text? I am new to Haskell, so this may be a trivial problem. I am seeing an error message that says
Couldn't match expected type 'Data.Text.Lazy.Internal.Text'
with actual type 'Data.Text.Internal.Text'
and I think the problem is that the actual type is Data.Text.Text and it expects lazy text. How can I convert one to the other?
EDIT:
here is a simplified code that gives this error.
{-# LANGUAGE OverloadedStrings #-}
import Data.Text.Lazy.Encoding
import Network.Mail.Mime
import Yesod
data FormData = FormData { dataField :: Textarea } deriving Show
part d = Part {
partType = "text/plain; charset=utf-8"
, partEncoding = None
, partFilename = Nothing
, partContent = encodeUtf8 $ unTextarea $ dataField d
, partHeaders = []
}
main = return ()
basically I have a yesod form with a textarea input element and I want to e-mail the contents of the textarea.
A: toStrict from Data.Text.Lazy would do what you ask for (convert lazy to strict).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: My @property is declared yet I still get may not respond to warning I don't like warnings lying around and this one has been bothering me. Any ideas on what I am doing wrong? I have tons of properties using this same approach and none of them are giving me warnings. Why doesn't Xcode recognize this one?
While the app works as expected, Xcode gives me the following compile time warning:
'OnlinePeerBrowser' may not respond to '-setMyParent:'
My property declaration in OnlinePeerBrowser.h
#import "WelcomeViewController.h"
@interface OnlinePeerBrowser : UIViewController <UITableViewDelegate, UITableViewDataSource, NSNetServiceBrowserDelegate> {
WelcomeViewController *_myParent;
}
@property (nonatomic, assign) WelcomeViewController *myParent;
OnlinePeerBrowser.m has
@synthesize myParent=_myParent;
I am getting the warning on setMyParent in WelcomeViewController.m here...
#import "WelcomeViewController.h"
#import "OnlinePeerBrowser.h"
@implementation WelcomeViewController
- (void)peerPickerController:(GKPeerPickerController *)picker didSelectConnectionType:(GKPeerPickerConnectionType)type {
...
OnlinePeerBrowser *controller = [[OnlinePeerBrowser alloc]
initWithNibName:@"OnlinePeerBrowser" bundle:nil];
[controller setMyParent:self];
}
Also, what is weird is that I can not use the dot syntax here either.
controller.myParent = self;
gives me the following error:
/Users/vesselhead/Development/iPhone/DJBox/WelcomeViewController.m:254: error: request for member 'myParent' in something not a structure or union
I feel like I must be missing something very simple.
A: The code you've posted looks correct. That means that the compiler is pulling in another declaration of the OnlinePeerBrowser class from somewhere.
*
*Check for circular imports.
*Check if you have multiple copies of the OnlinePeerBrowser.h file.
*Add the line #warning Testing to your OnlinePeerBrowser.h file. That warning should then appear in the log when you compile. If that warning doesn't appear then that file isn't being picked up by the compiler.
If it's a circular import then don't import "WelcomeViewController.h" in "OnlinePeerBrowser.h". Instead, use a forward declaration in OnlinePeerBrowser.h, e.g. @class WelcomeViewController , and import "WelcomeViewController.h" in OnlinePeerBrowser.m
A: Sometimes Circular Imports create an issue with the compiler.
Instead of using
#import "WelcomeViewController.h"
in OnlinePeerBrowser.h move that line to the OnlinePeerBrowser.m and add
@class WelcomeViewController
to the OnlinePeerBrowser.h
this will allow you to set the Class of myParent and _myParent to WelcomeViewController and not have the Circular Import.
Alternatively:
you may want to use a @protocol that the WeclomeViewController would have to adhere to. Then you would only have to import the Classes in one direction.
the implementation for a Protocol property would be as Follows
//#import "WelcomeViewController.h"
@protocol OnlinePeerBrowserParent <NSObject>
@required
- (NSString*) informationFromParent;
@end
@interface OnlinePeerBrowser : UIViewController <UITableViewDelegate, UITableViewDataSource, NSNetServiceBrowserDelegate> {
id<OnlinePeerBrowserParent> _myParent;
}
@property (nonatomic, assign) id<OnlinePeerBrowserParent> myParent;
notice the Protocol is on the OnlinePeerBrowser.h so you can import the OnlinePeerBrowser.h and get the Protocol by default.
finally you implement the Protocol in the WelcomeViewController as so
@implementation WelcomeViewController<OnlinePeerBrowserParent>
- (NSString*) informationFromParent
{
return @"My Parental Info";
}
...... etc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java System.currentTimeMillis() problem So in my java class we have a homework assignment to use System.currentTimeMillis to display the amount of time between clicks. I've tried and tried but it isn't working. Here's my code.
1 /* Matthew Caldwell
2 * September 21, 2011
3 * Homework #4: Problem 5.8.1 pg. 149
4 * Program that displays the amount of time that passed
5 * between two mouse clicks. Nothing is displayed
6 * on the first click, then each successive click will
7 * display how much time passed between that click and
8 * the previous one.
9 */
10
11 import objectdraw.*;
12 import java.awt.*;
13
14 public class ElapsedTimeClient extends WindowController {
15
16 public static void main(String[]args) {
17 new ElapsedTimeClient().startController(800,500);
18 }
19
20 private Text title,result;
21 private double count = 0;
22
23 public void begin() {
24
25 // Set up the title and result
26 title = new Text("CLICK COUNTER",
27 canvas.getWidth() / 2,
28 20, canvas);29 title.move(-title.getWidth() / 2, 0);
30 result = new Text("", canvas.getWidth() / 2, 40, canvas);
31
32 }
33
34 public void onMouseClick(Location p) {
35
36 double timerS=0;
37
38 if(count == 0) {
39 timerS = System.currentTimeMillis();
40 } else {
41 result.setText("The time between clicks was " +
42 (System.currentTimeMillis() - timerS)/1000 +
43 " seconds.");
44 timerS = System.currentTimeMillis();
45 }
46
47 count++;
48
49 }
50
51 }
I don't really want anyone to completely tell me how to do it but I just need a little guidance. What am I doing to make this wrong?
The code all compiles and runs just fine but when I click instead of giving me the time that elapsed between clicks it's giving me a big long number that never changes. It's telling me 1.316639174817E9 almost every single time.
A: Firstly, system time in millis should be represented as a long, not a double.
Secondly, you need to make the variable that holds the time since the last click (timerS) an instance variable, it's currently method local and so reset every time.
In short, change:
double timerS=0;
from being a local variable, to an instance variable, and a long:
public class ElapsedTimeClient extends WindowController {
long timerS;
A: the timerS variable is declared inside of the onMouseClick method, and thus only exists within this method. After your first mouse click, the variable disappears and can't be used to compare times.
Instead you should use a class variable to store this information in.
A: Your problems are:
*
*timerS should be a field of the class (not a local variable) otherwise its value will not be held between calls to your method
*timerS should be of type long - the type that's returned from the system time
Also:
*
*count should be type int
A: In addition to the other answers mentioned, System.nanoTime is the preferred method for this type of measurement. Rather than measuring the difference in "clock time", this method measured the number of nanoseconds. You will often find that the resolution on currentTimeMilils is no better than around 16 ms, whereas nanoTime can resolve much smaller intervals.
A: You don't need double type for timerS. currentTimeMillis() returns long.
Why this happend?
If you use double type like this:
(double - long) / 1000,
this is interpreted on:
double / double = double
So in the result you have "precise" value (e.g. 1.316639174817E9) instead of long one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android Keyboard automatically appears for EditText when activity is created I have a single activity class and it has a two EditTexts on the screen. When the activity launches the keyboard launches with it. Why is this? I did not request enter anything yet into the edit box. Why does it do this? And how can I get rid of this behavior?
A: Try setting your stateHidden in the manifest file for the activity:
http://developer.android.com/guide/topics/manifest/activity-element.html#wsoft
and this might be helpful:
How to keep soft keyboard from opening on activity launch in Android?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to set GWT to include style names in the compiled names? I use CssResource extensively, and now my generated html is full of GWXSHFKADAish class names. I get all of the advantages of that, but for debugging it'd be helpful to add a flag that would turn .selected into GWXSTY_selected. Is there any way to do this?
A: When you set
<set-configuration-property name="CssResource.style" value="pretty"/>
in your .gwt.xml file, then the resulting class names will contain the original class name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting cue points in XML for use in Flash Video We need to set up a system for a client which needs to be super simple for them to be able to do in future and I was wondering if it is possible to set cue points in an XML file which are then pulled into the swf along with the FLV. The cue points will be managed by the client so that they can change slides and images during the process of the video playing.
I know that there are hardcoded cue points which can be set up during FLV creation and one can set cue points using AS. I would like to know if it is possible to set those AS cue points using XML?
Also, do we have to use a streaming server (CDM) to get this right or will we be able to stream the video directly from the client's site?
Thanks :)
A: Sure you can get cue points from xml file, you just need to check netstream.time on enterframe to response cue points. You can make a eventdispacher class for this to let you know cue points that works like netstream onCuePoint
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dealing with Option and Either types - idiomatic conversions? I'm probably missing something that's right in the documentation, but I can't really make much sense of it - I've been teaching myself Scala mostly by trial and error.
Given a function f: A => C, what is the idiomatic way to perform the following conversions?
Either[A, B] -> Either[C, B]
Either[B, A] -> Either[B, C]
(If I have two such functions and want to convert both sides, can I do it all at once or should I apply the idiom twice sequentially?)
Option[A] -> Option[C]
(I have a feeling that this is supposed to use for (...) yield somehow; I'm probably just blanking on it, and will feel silly when I see an answer)
And what exactly is a "projection" of an Either, anyway?
A: Given f: A=>B and xOpt: Option[A], xOpt map f produces the Option[B] you need.
Given f: A=>B and xOrY: Either[A, C], xOrY.left.map(f) produces the Either you are looking for, mapping just the first component; similarly you can deal with RightProjection of Either.
If you have two functions, you can define mapping for both components, xOrY.fold(f, g).
A: You do either a:
either.left.map(f)
or a:
either.right.map(f)
You can also use a for-comprehension: for (x <- either.left) yield f(x)
Here's a more concrete example of doing a map on an Either[Boolean, Int]:
scala> val either: Either[Boolean, Int] = Right(5)
either: Either[Boolean, Int] = Right(5)
scala> val e2 = either.right.map(_ > 0)
either: Either[Boolean, Boolean] = Right(true)
scala> e2.left.map(!_)
either: Either[Boolean, Boolean] = Right(true)
EDIT:
How does it work? Say you have an Either[A, B]. Calling left or right creates a LeftProjection or a RightProjection object that is a wrapper that holds the Either[A, B] object.
For the left wrapper, a subsequent map with a function f: A => C is applied to transform the Either[A, B] to Either[C, B]. It does so by using pattern matching under the hood to check if Either is actually a Left. If it is, it creates a new Left[C, B]. If not, it just changes creates a new Right[C, B] with the same underlying value.
And vice versa for the right wrapper. Effectively, saying either.right.map(f) means - if the either (Either[A, B]) object holds a Right value, map it. Otherwise, leave it as is, but change the type B of the either object as if you've mapped it.
So technically, these projections are mere wrappers. Semantically, they are a way of saying that you are doing something that assumes that the value stored in the Either object is either Left or Right. If this assumption is wrong, the mapping does nothing, but the type parameters are changed accordingly.
A: val e1:Either[String, Long] = Right(1)
val e2:Either[Int,Boolean] = e1.left.map(_.size).right.map( _ >1 )
// e2: Either[Int,Boolean] = Right(false)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Question about the ~ and @ operators in Haskell What exactly do they do? I know one possible use of @ (assigning a name at the start of a pattern match), but haven't been able to find anything on ~.
I found them in the following code snippet, taken from http://www.haskell.org/haskellwiki/Prime_numbers, but the article assumes that you're fluent in Haskell syntax and doesn't bother explaining its esoteric operators (the part I'm confused about is the start of the declaration for sieve):
primesPT () = 2 : primes'
where
primes' = sieve [3,5..] primes' 9
sieve (p:xs) ps@ ~(_:t) q
| p < q = p : sieve xs ps q
| True = sieve [x | x<-xs, rem x p /= 0] t (head t^2)
Any explanation (or link to one) about the syntax used here would be greatly appreciated.
A: It's a lazy pattern match (also known as irrefutable pattern match which I think is the better name).
Essentially, ~(_:t) will always match, even if the input is the empty list []. Of course, this is dangerous if you don't know what you're doing:
Prelude> let f ~(_:t) = t in f []
*** Exception: <interactive>:1:4-15: Irrefutable pattern failed for pattern (_ : t)
A: The operator ~ makes a match lazy. Usually a pattern-match evaluates the argument, as there is a need to check whether the pattern fails. If you prefix a pattern with ~, there is no evaluation until it is needed. This functionality is often used in “Tying the knot” code, where one needs to refer to structures that are not yet created. If the pattern fails upon evaulation, the result is undefined.
Here is an example:
f (_:_) = True
f [] = False
g ~(_:_) = True
g [] = False
f [] yields False, while g [] yields true, because the first pattern always matches. (You actually get a warning for this code)
That said, you can see ~ as the opposite of !, which forces the evaluation of an argument even if it's unneeded.
Note that these operators only make things strict/lazy at the level they are applied at, not recursively. For example:
h ~((x,y):xys) = ...
The pattern match on the tuple is strict, but the cons pattern is lazy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Symfony 2 Embedded forms using one to many db relationship I'm have a problem embedding forms from different entities in one form, my form is being displayed with firstname [input] lastname [input] address - but the address has no input next to it.
Basically I want to create a form where the user can add first name, last name, address1, address2, city, country ect and submit it it as one, although it's different tables.
The main form is no problem the only issue I'm having is with the second embedded form. Any help would be greatly appreciated.
Here is my code:
Member class:
namespace Pomc\MembersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pomc\MembersBundle\Entity\Member
*/
class Member
{
/**
* @var integer $id
*/
private $id;
/**
* @var string $firstName
*/
private $firstName;
/**
* @var string $lastName
*/
private $lastName;
/**
* @var Pomc\MembersBundle\Entity\Address
*/
private $address;
/**
* @var Pomc\MembersBundle\Entity\Telephone
*/
private $telephone;
public function __construct()
{
$this->address = new \Doctrine\Common\Collections\ArrayCollection();
$this->telephone = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* @param string $firstName
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
/**
* Get firstName
*
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* @param string $lastName
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
/**
* Get lastName
*
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Add address
*
* @param Pomc\MembersBundle\Entity\Address $address
*/
public function addAddress(\Pomc\MembersBundle\Entity\Address $address)
{
$this->address[] = $address;
}
/**
* Get address
*
* @return Doctrine\Common\Collections\Collection
*/
public function getAddress()
{
return $this->address;
}
/**
* Add telephone
*
* @param Pomc\MembersBundle\Entity\Telephone $telephone
*/
public function addTelephone(\Pomc\MembersBundle\Entity\Telephone $telephone)
{
$this->telephone[] = $telephone;
}
/**
* Get telephone
*
* @return Doctrine\Common\Collections\Collection
*/
public function getTelephone()
{
return $this->telephone;
}
}
Here is the address class:
namespace Pomc\MembersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pomc\MembersBundle\Entity\Address
*/
class Address
{
/**
* @var integer $id
*/
private $id;
/**
* @var string $addressType
*/
private $addressType;
/**
* @var string $firstLine
*/
private $firstLine;
/**
* @var string $secondLine
*/
private $secondLine;
/**
* @var string $city
*/
private $city;
/**
* @var string $postCode
*/
private $postCode;
/**
* @var string $country
*/
private $country;
/**
* @var Pomc\MembersBundle\Entity\Member
*/
private $member;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set addressType
*
* @param string $addressType
*/
public function setAddressType($addressType)
{
$this->addressType = $addressType;
}
/**
* Get addressType
*
* @return string
*/
public function getAddressType()
{
return $this->addressType;
}
/**
* Set firstLine
*
* @param string $firstLine
*/
public function setFirstLine($firstLine)
{
$this->firstLine = $firstLine;
}
/**
* Get firstLine
*
* @return string
*/
public function getFirstLine()
{
return $this->firstLine;
}
/**
* Set secondLine
*
* @param string $secondLine
*/
public function setSecondLine($secondLine)
{
$this->secondLine = $secondLine;
}
/**
* Get secondLine
*
* @return string
*/
public function getSecondLine()
{
return $this->secondLine;
}
/**
* Set city
*
* @param string $city
*/
public function setCity($city)
{
$this->city = $city;
}
/**
* Get city
*
* @return string
*/
public function getCity()
{
return $this->city;
}
/**
* Set postCode
*
* @param string $postCode
*/
public function setPostCode($postCode)
{
$this->postCode = $postCode;
}
/**
* Get postCode
*
* @return string
*/
public function getPostCode()
{
return $this->postCode;
}
/**
* Set country
*
* @param string $country
*/
public function setCountry($country)
{
$this->country = $country;
}
/**
* Get country
*
* @return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set member
*
* @param Pomc\MembersBundle\Entity\Member $member
*/
public function setMember(\Pomc\MembersBundle\Entity\Member $member)
{
$this->member = $member;
}
/**
* Get member
*
* @return Pomc\MembersBundle\Entity\Member
*/
public function getMember()
{
return $this->member;
}
}
Here is the memberform:
namespace Pomc\MembersBundle\Form\Type;
use \Symfony\Component\Form\AbstractType;
use \Symfony\Component\Form\FormBuilder;
class MemberType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('firstName');
$builder->add('lastName');
$builder->add('address','collection', array( 'type' => new AddressType(),
'allow_add' => true,
'prototype' => true,
'by_reference' => false,
));
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Pomc\MembersBundle\Entity\Member');
}
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
function getName()
{
return 'member';
}
}
Here is the address form:
namespace Pomc\MembersBundle\Form\Type;
use \Symfony\Component\Form\AbstractType;
use \Symfony\Component\Form\FormBuilder;
class AddressType extends AbstractType
{
public function buildForm(Formbuilder $builder, array $options)
{
$builder->add('firstLine');
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Pomc\MembersBundle\Entity\Address');
}
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
function getName()
{
return 'address';
}
function getIdentifier()
{
return 'address';
}
}
Here is the controller:
namespace Pomc\MembersBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use \Pomc\MembersBundle\Entity\Member;
use \Symfony\Component\HttpFoundation\Request;
use \Pomc\MembersBundle\Form\Type\MemberType;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('PomcMembersBundle:Default:index.html.twig', array('name' => $name));
}
public function newAction(Request $request)
{
$member = new Member();
$form = $this->get('form.factory')->create(new MemberType());
if($request->getMethod() == 'POST')
{
$form->bindRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$em->persist($member);
$em->flush();
}
}
return $this->render('PomcMembersBundle:Default:new.html.twig', array( 'form'=> $form->createView(),));
}
}
Here is the template:
<form action="{{ path('member_new') }}" method="post" {{ form_enctype(form)}}>
{{ form_widget(form) }}
<div>
{{ form_row(form.address)}}
</div>
<input type="submit" />
</form>
Been a long time user of this site, but this is my first question.
Thank you
A: Oh I faced the same problem, but I found the solution, hope this will help you :-)
You're forgetting to add an Address object to the member entity.
In your action you'll need to do the following:
$member = new Member();
$member->addAddress(new Address());
$form = $this->createForm(new MemberType(), $member);
And then in your template:
{% for address in form.address %}
{{ form_widget(address.firstLine) }}
{% endfor %}
Btw your 'firstline' widget doesn't relate to an entity property.
Btw if you called addAddress two times, you would of course get two 'firstline' widgets in your form.
Hope this works. best of luck.
A: Llewellyn, do you mean something like thid:
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('imBundle:Inspecciones')->find($id);
$entity_valores = $em->getRepository('imBundle:ValoresInspecciones')->findByInspecciones($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Inspecciones entity.');
}
$entity->setValoresInspecciones($entity_valores);
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('imBundle:Inspecciones:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Where are the Azure trace logs on a local box when UseDevelopmentStorage=true I am running a Windows Azure Project in an emulator on a local box and have set the flag UseDevelopmentStorage=true for tracing. However, I cannot figure out where the traces/logs go, if they get written at all. I appreciate your help.
Thanks,
Archil
A: According to http://blog.bareweb.eu/2011/01/beginning-azure-diagnostics/ you should have a WADLogsTable showing up in your Table storage node. You need to make sure that Diagnostics are enabled.
And that you enable transfers
public override bool OnStart()
{
DiagnosticMonitorConfiguration diagnosticMonitorConfiguration = DiagnosticMonitor.GetDefaultInitialConfiguration();
diagnosticMonitorConfiguration.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
DiagnosticMonitor diagnosticMonitor = DiagnosticMonitor.Start(cloudStorageAccount, diagnosticMonitorConfiguration);
return base.OnStart();
}
A: In the windows system tray click on a a Windows Azure blue icon and pick Show Compute Emulator UI. In the window that opens up find you role instance on the left and click on it. You will see the traces scroll by.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Difference between sequence points and operator precedence? 0_o Let me present a example :
a = ++a;
The above statement is said to have undefined behaviors ( I already read the article on UB on SO)
but according precedence rule operator prefix ++ has higher precedence than assignment operator =
so a should be incremented first then assigned back to a. so every evaluation is known, so why it is UB ?
A: The important thing to understand here is that operators can produce values and can also have side effects.
For example ++a produces (evaluates to) a + 1, but it also has the side effect of incrementing a. The same goes for a = 5 (evaluates to 5, also sets the value of a to 5).
So what you have here is two side effects which change the value of a, both happening between sequence points (the visible semicolon and the end of the previous statement).
It does not matter that due to operator precedence the order in which the two operators are evaluated is well-defined, because the order in which their side effects are processed is still undefined.
Hence the UB.
A: Precedence is a consequence of the grammar rules for parsing expressions. The fact that ++ has higher precedence than = only means that ++ binds to its operand "tighter" than =. In fact, in your example, there is only one way to parse the expression because of the order in which the operators appear. In an example such as a = b++ the grammar rules or precedence guarantee that this means the same as a = (b++) and not (a = b)++.
Precedence has very little to do with the order of evaluation of expression or the order in which the side-effects of expressions are applied. (Obviously, if an operator operates on another expression according to the grammar rules - or precedence - then the value of that expression has to be calculated before the operator can be applied but most independent sub-expressions can be calculated in any order and side-effects also processed in any order.)
A:
why it is UB ?
Because it is an attempt to change the variable a two times before one sequence point:
*
*++a
*operator=
A: Sequence point evaluation #6: At the end of an initializer; for example, after the evaluation of 5 in the declaration int a = 5;. from Wikipedia.
You're trying to change the same variable, a, twice. ++a changes it, and assignment (=) changes it. But the sequence point isn't complete until the end of the assignment. So, while it makes complete sense to us - it's not guaranteed by the standard to give the right behavior as the standard says not to change something more than once in a sequence point (to put it simply).
A: It's kind of subtle, but it could be interpreted as one of the following (and the compiler doesn't know which:
a=(a+1);a++;
a++;a=a;
This is because of some ambiguity in the grammar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Assigning names to a dataframe via a loop in R There appear to be some similar questions but I cannot quite get my head round them at this late hour
I am trying to manipulate a set of dataframes based on sql calls - something like this
x <- c(3,9,12) # x is of variable length in real world
for (i in 1:length(x)) {
nam <- paste("df",i, sep="")
assign(nam) <- sqlQuery(channel,paste(
"Select myCol from myTable where myVal =",x[i],sep=""));
}
So I am after dataframes df1,df2,df3 which I can then combine etc.
Andrie's answer below is perfect but I am having trouble extending it to two variables
myQuery <- function(t,x){
sqlQuery(channel,paste("Select myCol from myTable where myTextVal='",t,"' and myVal =", x, sep=""))
}
x <- c(3,9,12)
t <-c("00","10","12")
myData <- lapply(c(t,x), myQuery)
I am getting an 'Error in paste... argument "x" is missing, with no default'
I'm not sure if it is because there is a mix of numeric and character variables in lapply vector
but applying as.numeric /as.character in the sql statement did not seem to help
A: The R idiom would be to use an apply type function instead of a loop. The effect of this is that your resultant data object is a list. In this case it will be a list of data.frame objects.
Something like the following:
myQuery <- function(x){
sqlQuery(channel,paste("Select myCol from myTable where myVal =", x, sep=""))
}
x <- c(3,9,12)
t <- c("00","10","12")
myData <- lapply(c(t, x), myQuery)
You can then extract the individual data.frames with list subsetting:
myData[[1]]
EDIT. The point is that lapply will take a single vector as input. Your instruction c(t, x) combines its input into a single vector. Thus you shouldn't change myQuery - it still only takes a single input argument.
A: Well, the assign function needs both the name and the value as arguments:
assign(nam, sqlQuery(channel,paste("Select myCol from myTable where myVal =",x[i],sep="")))
Type ?assign to learn more...
A: You need mapply:
myData <- mapply(myQuery, t, x, SIMPLIFY=FALSE)
But I think better solution is to first prepare queries:
queries <- sprintf(
"Select myCol from myTable where myTextVal='%s' and myVal=%i",
t, x) # here I assume that x is integer, see ?sprintf for other formats
queries
[1] "Select myCol from myTable where myTextVal='00' and myVal=3"
[2] "Select myCol from myTable where myTextVal='10' and myVal=9"
[3] "Select myCol from myTable where myTextVal='12' and myVal=12"
And then lapply over them:
myData <- lapply(queries, function(sql) sqlQuery(channel, sql))
# could be simplified to:
myData <- lapply(queries, sqlQuery, channel=channel)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: YUI Compressor - Automate Javascript Compression but skip some files I am following the suggested answer on this SO post:
How to automate JavaScript files compression with YUI Compressor?
However, in my ~/Scripts folder, I have several jQuery files that are already compressed and minified. What do I need to do to automate it in a similar fashion but skip the jQuery files?
A: You could name all of your uncompressed files whatever.max.js, and then change the rule to something like this:
for %%a in (*.max.js) do @java -jar yuicompressor.jar "%%a" -o "deploy\%%a"
A: maybe something like this:
cd ~/Scripts
find . -name "*jquery*" -prune -o -type d -o -exec java -jar yuicompressor.jar -o '.js$:-min.js' {} +
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get dynamically added element in JQuery I'm trying to replace the text within a div which is getting dynamically added to a dialog element on clicking a link.
var feedBackDialog;
if(!feedbackDialog){
$(".feedback_link").click(function() {
//set contents of the dialog 'feedback-dialog'
$.get("/users/feedback", null, function(result) {
feedBackDialog = $("#feedback-dialog").html(result). //set html content during callback
attr('title', title).
dialog({ autoOpen: true, width: 560, modal: true
});
});
}
else
{
feedbackDialog.dialog({ autoOpen: true, width: 560, modal: true });
}
//change the text in the newly created element.
$('#feedback-label').text($(this).attr('feedback_desc'));
An element with the id feedback-label exists in the html that I'm fetching. However, the last line's $('#feedback-label') does not work as the DOM has not been refreshed.
I tried doing $("#feedback-dialog").find('#feedback-label') but that does not seem to work consistently. Does anyone know of a good way of obtaining this newly created element?
I know I can simply replace the string of the html <div id="feedback_label"></div> with the contents, but I'm looking of a nicer way.
A: It's not because the dom hasn't been refreshed, it's because you're making an AJAX request that hasn't finished. Add the line of code to the success callback and you should be golden:
$.get("/users/feedback", null, function(result) {
$("#feedback-dialog").html(result).attr('title', title).dialog({ autoOpen: true, width: 560, modal: true });
$('#feedback-label').text($(this).attr('feedback_desc'));
});
A: Move the last line to the callback function of $.get, because the contents will only be ready when the Ajax call has finished:
$.get("/users/feedback", null, function(result) {
$("#feedback-dialog").html(result). //get HTML
attr('title', title).
dialog({ autoOpen: true, width: 560, modal: true });
$('#feedback-label').text($(this).attr('feedback_desc')); //change the text in the newly created element.
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Where should I place Indexes in MySQL Tables I have the following three WHERE clauses:
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight = $maxImageHeight
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight != $maxImageHeight
WHERE primaryId = $imgId AND imgWidth != $maxImageWidth AND imgHeight = $maxImageHeight"
They are acting upon two MySQL InnoDB tables joined in the query with UNION ALL.
I am not sure how I should set up the Indexes in these two tables; Whether I should have a Multi-Column Index, with imgWidth and imgHeight, or if it should include primaryId as well?
Is it true that a query can only use one index? If not, could I set up each column as an index?
Or would a Multi-Column Index not work in this case?
Here is an example of the entire query for the first WHERE clause. The others are the same, with the respective clauses:
SELECT 'allEqual' AS COL1,COUNT(*) AS imgCount FROM (
SELECT imgHeight, imgWidth, imgId AS primaryId FROM primary_images
UNION ALL
SELECT imgHeight, imgWidth, primaryId FROM secondary_images
) AS union_table
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight = $maxImageHeight
Here is the schema of the primary_images table:
CREATE TABLE IF NOT EXISTS `new_arrivals_images`.`primary_images` (
`imgId` SMALLINT(6) UNSIGNED NOT NULL AUTO_INCREMENT ,
`imgTitle` VARCHAR(255) NULL DEFAULT NULL ,
`view` VARCHAR(45) NULL DEFAULT NULL ,
`secondary` ENUM('true','false') NOT NULL DEFAULT false ,
`imgURL` VARCHAR(255) NULL DEFAULT NULL ,
`imgWidth` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgHeight` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgDate` DATETIME NULL DEFAULT NULL ,
`imgClass` ENUM('Jeans','T-Shirts','Shoes','Dress Shirts','Trackwear & Sweatwear') NULL DEFAULT NULL ,
`imgFamily` ENUM('Hugo Boss','Lacoste','True Religion','7 For All Mankind','Robin\'s Jeans','Robert Graham') NULL DEFAULT NULL ,
`imgGender` ENUM('Men\'s','Women\'s') NOT NULL DEFAULT Mens ,
PRIMARY KEY (`imgId`) ,
UNIQUE INDEX `imgDate_UNIQUE` (`imgDate` DESC) )
ENGINE = InnoDB;
And the schema for the secondary_images table:
CREATE TABLE IF NOT EXISTS `new_arrivals_images`.`secondary_images` (
`imgId` SMALLINT(6) UNSIGNED NOT NULL AUTO_INCREMENT ,
`primaryId` SMALLINT(6) UNSIGNED NOT NULL ,
`view` VARCHAR(45) NULL DEFAULT NULL ,
`imgURL` VARCHAR(255) NULL DEFAULT NULL ,
`imgWidth` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgHeight` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ,
`imgDate` DATETIME NULL DEFAULT NULL ,
PRIMARY KEY (`imgId`, `primaryId`) ,
INDEX `fk_secondary_images_primary_images` (`primaryId` ASC) ,
UNIQUE INDEX `imgDate_UNIQUE` (`imgDate` DESC) ,
CONSTRAINT `fk_secondary_images_primary_images`
FOREIGN KEY (`primaryId` )
REFERENCES `new_arrivals_images`.`primary_images` (`imgId` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
A:
Is it true that a query can only use one index?
No. That would be silly.
If not, could I set up each column as an index?
Yes that's an option, but only if you use the column independently of each other.
If you always combine the fields, like it seems you do here, it's more efficient to use a compound index.
I am not sure how I should set up the Indexes in these two tables; Whether I should have a Multi-Column Index, with imgWidth and imgHeight, or if it should include primaryId as well?
If you want to can use a compound index combining (imgWidth, imgHeight)
You must remember though that you cannot access the index on imgHeight without also using imgWidth in the where clause.
You must always use the left-most part (or all) of a compound index.
On InnoDB the primary key is always included in every secondary index, so it is counterproductive to include that.
Added bonus on InnoDB
If you only select indexed fields, InnoDB will never actually read the tabledata, because all the data needed is in the index. This will speed up things a lot.
You have an SQL-injection hole
Your code seems to have an SQL-injection hole. Please surround all your $vars in single quotes: where field1 = '$var' ... and don't forget to use $var = mysql_real_escape_string($var); before injecting them into the query. See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For speed and safety the query should read:
SELECT 'allEqual' AS COL1, COUNT(*) AS imgCount FROM (
SELECT imgId AS primaryId FROM primary_images pi
WHERE pi.ImgId = '$imgId'
AND pi.imgWidth = '$maxImageWidth'
AND pi.imgHeight = '$maxImageHeight'
UNION ALL
SELECT primaryId FROM secondary_images si
WHERE si.primaryId = '$imgId'
AND si.imgWidth = '$maxImageWidth'
AND si.imgHeight = '$maxImageHeight'
) AS union_table
This way the proper indexes will be used and no unneeded data is retrieved.
MySQL cannot use an index on the unioned data because it's a merge of two different tables. That's why you need to do the where in the inner selects.
A: Does your primaryId column have any duplicates? Or is it a primary key? If it's a primary key, then it will also serve as a fine index. In InnoDB, it probably already is an index if it's a primary key.
Put another way, how discriminating is your WHERE clause primaryId = $imgId ? If it typically matches none, or exactly one, or just a few rows, then another index won't help much. If it matches hundreds or thousands of rows, another index may well help.
Queries can definitely use multiple indexes.
This is one of those cases where the big question is "what are you trying to do?" It seems like you're trying to select an image where either or both dimensions match your input.
Consider making it more efficient by redoing the logic and getting rid of your UNION ALL clause (which turns into three queries).
WHERE primaryId = $imgId
AND (imgWidth = $maxImageWidth OR imgHeight = $maxImageHeight)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert ASCII characters to hex escaped strings I was reading in a file from Python. I opened this file and used 'rb' to read the bytes. When I read them off, say:
f.read(1)
it would output something like this
b'\x50'
So my question is, when I tried a longer string like this
f.read(24)
I got this:
b'R\x00S\x00S\x00Q\x00S\x00O\x00N\x00P\x00S\x00M\x00R\x00P\x00
You notice that there are ASCII characters mixed into the hex. I would want the R to be displayed as \x52.
How do I do that?
A: print(''.join('\\x%02x' % c for c in B))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Passing single string from forum in RoR Having a problem trying to do this with one string but basically I want a form that has just a text box and a submit button that when submitted passes the value of the text box back to the controller as a string - so I can do arithmetic in the controller. Unfortunately I only understand ruby passing objects through forums.
The view (where the forum is):
<h1>Questions#go</h1>
<p>Just a quick question</p>
<%= form_for(@answer) do |f| %>
<div class="field">
<%= f.label :answer %><br />
<%= f.text_field :answer %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>
The controller:
class QuestionsController < ApplicationController
def go
end
# POST /go
def submit
@answer = :answer
if @answer = 'Ted'
@message = 'Correct'
else
@message = 'Incorrect'
end
end
end
Finally the routes:
Quizzer::Application.routes.draw do
resources :quizzes
get "questions/go"
post "questions/go"
match '/go', :to => 'questions#go'
root :to => 'pages#home'
get "pages/home"
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end
I have been trying to teach myself basic rails for days and am seriously struggling. Basically what I am trying to achieve I wrote in Ruby as (yes I am learning RoR just to be able to implement this online):
class Quiz
def initialize(name)
puts "Welcome #{name}, I hope you brought your A-game."
@count = 0
@questions = ["What is 1 + 2 equal to?", "What is my name?", "What is the first letter of the alphabet?"]
@answers = ["3", "NICK", "A"]
@numberOfQuestions = @questions.length
self.startGame
end
def startGame
@gameOver = 0
while (@gameOver == 0)
self.playQuiz
self.checkOverallWin
end
end
def checkAnswer (givenAnswer)
if (givenAnswer == @answers[@count])
@count += 1
puts "Well done you answered that correctly."
else
puts "Sorry wrong answer. Here it comes again!"
end
puts ""
end
def checkOverallWin
if @count == @numberOfQuestions
@gameOver = 1
puts "Well done you have finished the quiz!"
else
@gameOver = 0
end
end
def playQuiz
puts "Question number #{@count + 1}:"
puts @questions[@count]
answer = gets()
answer.upcase!
answer.strip!
self.checkAnswer(answer)
end
end
puts "Hello, welcome to this simple game!"
puts "What is your name?"
name = gets()
name.strip!
game = Quiz.new(name)
Unfortunately every guide I have completed deals with objects and OO - which I dont need - I just want a way to pass text into the controller, check if it matches the required text and if so proceed with the 'next question' and show the input screen all over again.
A: In def submit to read the answer (the string you want to process), you need to get it from params array:
@answer = params[:answer]
BTW, in Ruby everything is an object so there's no way you can escape them :)
If you think you're not getting what you have submitted, you can check request or request params by puts request.inspect or puts params.inspect.
A: Here's a simple example, for the view:
<%= form_tag(:controller => 'home', :action => 'arithmetic', :method => 'post') %>
<%= text_field_tag(:my_thing) %>
<% end %>
Then the controller:
class HomeController < ActionController::Base
def arithmetic
my_value = params[:my_thing]
end
end
Untested, correct me if I'm wrong!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Returning multiple object types using hibernate using an inner join I seem to be having some difficulty with a query in hibernate. I am performing an inner join on two tables.
SELECT * FROM product p INNER JOIN warehouse w ON p.wid = w.id
Product Table:
id | name | wid | price | stock .....
Warehouse Table:
id | name | city | lat | long .....
The join result:
id | name | wid | price | stock | id | name | city | lat | long .....
When I run the query..
Session.createSQLQuery(this.query)
.addEntity("p", Product.class)
.addEntity("w", Warehouse.class).list();
So for every result I get an object containing a Product object and a Warehouse object.
This is expected. The issue is hibernate assigns the id and name of the product to the warehouse objects id and name property. Its as if the first two columns in the join result are over riding when it comes to creating the Warehouse project. The Product object always contains the correct data.
Any suggestion on finding a way around this issue so the id and name columns representing the correct Warehouse data would be much appreciated.
Thanks in advance.
A: Reference
In case the entities aren't from the same class, then here's a sample :
public static void main(String[] args) {
Session sess = NewHibernateUtil.getSessionFactory().openSession();
SQLQuery q = null;
String query = "select a.*, u.* from user u, account a where a.iduser=u.iduser";
q = sess.createSQLQuery(query);
q.addEntity(User.class);
q.addEntity(Account.class);
List lst = q.list();
System.out.println("" + lst.size());
for (int i = 0; i < lst.size(); i++) {
System.out.println(((Object[]) lst.get(i))[0]); //account bean, actually this is in reverse order - so this is user bean
System.out.println(((Object[]) lst.get(i))[1]); //user bean & this account bean
}
sess.close();
}
A: As coding_idiot said, maybe you don't know the entity for your query result because they are from different classes, you can access to every object in the element.
*
*Create a List<Object> to retrieve the query result (Example:
List<Object> objs = (List<Object>)query.getResultList();)
*Iterate through this array using a for (Example: for (Object obj : objs){...})
*Every element of List<Object> has got a Object[] so
cast every element to this class (Example: Object[] o = (Object[]) obj; )
*Access to the element through its index number (Example:
o[4])
Code sample:
Query query = JPA.em().createNativeQuery("SELECT * FROM product p
INNER JOIN warehouse w ON p.wid = w.id");
/* I suppose that it return fields sorted by entities and field in
database:
*
* 0: product.id | 1: product.name | 2: product.wid | 3: product.price | 4: product.stock | n-1: product.N-1Field
* n: warehouse.id | n+1: name | n+2: warehouse.city | n+3: warehouse.lat | n+4: warehouse.long | m-1: warehouse.M-1Field
*
* Join result: id | name | wid | price | stock | ... | id | name | city | lat | long | ...
*/
List<Object> objs = (List<Object>)query.getResultList();
for (Object obj : objs) {
Object[] o = (Object[]) obj;
String productId = String.valueOf(o[0]);
String productName = String.valueOf(o[1]);
String productWid = String.valueOf(o[2]);
... }
A: Use the {} form to avoid problems with column name duplication:
SELECT {p.*}, {w.*} FROM product p INNER JOIN warehouse w ON p.wid = w.id
From Hibernate Reference Documentation, section 18.1.4. Returning multiple entities:
Until now, the result set column names are assumed to be the same as
the column names specified in the mapping document. This can be
problematic for SQL queries that join multiple tables, since the same
column names can appear in more than one table.
Column alias injection is needed in the following query (which most
likely will fail):
sess.createSQLQuery("SELECT c.*, m.* FROM CATS c, CATS m WHERE c.MOTHER_ID = c.ID")
.addEntity("cat", Cat.class)
.addEntity("mother", Cat.class)
The query was intended to return two Cat instances per row: a cat and
its mother. The query will, however, fail because there is a conflict
of names; the instances are mapped to the same column names. Also, on
some databases the returned column aliases will most likely be on the
form "c.ID", "c.NAME", etc. which are not equal to the columns
specified in the mappings ("ID" and "NAME").
The following form is not vulnerable to column name duplication:
sess.createSQLQuery("SELECT {cat.*}, {mother.*} FROM CATS c, CATS m WHERE c.MOTHER_ID = c.ID")
.addEntity("cat", Cat.class)
.addEntity("mother", Cat.class)
This query specified:
the SQL query string, with placeholders for Hibernate to inject column
aliases the entities returned by the query The {cat.*} and
{mother.*} notation used above is a shorthand for "all properties".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How to check a module has been activated or not in emacs How to check if a org-timer module has been activated or not.
A: C-c C-x C-j
should actually work. It is the default chord bound to the command M-x org-clock-jump-to-current-clock .
Check your .emacs if you have changed the keybindings. If C-c C-x C-j is unbound and it still does not work you can try and put this in your .emacs:
(global-set-key (kbd "C-c C-x C-j") 'org-clock-jump-to-current-clock)
A: C-c C-x C-j
See C-h k C-c C-x C-j for docs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Explain this Function Can someone explain to me the reason why someone would want use bitwise comparison?
example:
int f(int x) {
return x & (x-1);
}
int main(){
printf("F(10) = %d", f(10));
}
This is what I really want to know: "Why check for common set bits"
x is any positive number.
A: Bitwise operations are used for three reasons:
*
*You can use the least possible space to store information
*You can compare/modify an entire register (e.g. 32, 64, or 128 bits depending on your processor) in a single CPU instruction, usually taking a single clock cycle. That means you can do a lot of work (of certain types) blindingly fast compared to regular arithmetic.
*It's cool, fun and interesting. Programmers like these things, and they can often be the differentiator when there is no difference between techniques in terms of efficiency/performance.
You can use this for all kinds of very handy things. For example, in my database I can store a lot of true/false information about my customers in a tiny space (a single byte can store 8 different true/false facts) and then use '&' operations to query their status:
*
*Is my customer Male and Single and a Smoker?
if (customerFlags & (maleFlag | singleFlag | smokerFlag) ==
(maleFlag | singleFlag | smokerFlag))
*Is my customer (any combination of) Male Or Single Or a Smoker?
if (customerFlags & (maleFlag | singleFlag | smokerFlag) != 0)
*Is my customer not Male and not Single and not a Smoker)?
if (customerFlags & (maleFlag | singleFlag | smokerFlag) == 0)
Aside from just "checking for common bits", you can also do:
*
*Certain arithmetic, e.g. value & 15 is a much faster equivalent of value % 16. This only works for certain numbers, but if you can use it, it can be a great optimisation.
*Data packing/unpacking. e.g. a colour is often expressed as a 32-bit integer that contains Alpha, Red, Green and Blue byte values. The Red value might be extracted with an expression like red = (value >> 16) & 255; (shift the value down 16 bit positions and then carve off the bottom byte)
*
*Data manipulation and swizzling. Some clever tricks can be achieved with bitwise operations. For example, swapping two integer values without needing to use a third temporary variable, or converting ARGB colour values into another format (e.g RGBA or BGRA)
A: The Ur-example is "testing if a number is even or odd":
unsigned int number = ...;
bool isOdd = (0 != (number & 1));
More complex uses include bitmasks (multiple boolean values in a single integer, each one taking up one bit of space) and encryption/hashing (which frequently involve bit shifting, XOR, etc.)
A: The example you've given is kinda odd, but I'll use bitwise comparisons all the time in embedded code.
I'll often have code that looks like the following:
volatile uint32_t *flags = 0x000A000;
bool flagA = *flags & 0x1;
bool flagB = *flags & 0x2;
bool flagC = *flags & 0x4;
A: It's not a bitwise comparison. It doesn't return a boolean.
Bitwise operators are used to read and modify individual bits of a number.
n & 0x8 // Peek at bit3
n |= 0x8 // Set bit3
n &= ~0x8 // Clear bit3
n ^= 0x8 // Toggle bit3
Bits are used in order to save space. 8 chars takes a lot more memory than 8 bits in a char.
The following example gets the range of an IP subnet using given an IP address of the subnet and the subnet mask of the subnet.
uint32_t mask = (((255 << 8) | 255) << 8) | 255) << 8) | 255;
uint32_t ip = (((192 << 8) | 168) << 8) | 3) << 8) | 4;
uint32_t first = ip & mask;
uint32_t last = ip | ~mask;
A: e.g. if you have a number of status flags in order to save space you may want to put each flag as a bit.
so x, if declared as a byte, would have 8 flags.
A: I think you mean bitwise combination (in your case a bitwise AND operation). This is a very common operation in those cases where the byte, word or dword value is handled as a collection of bits, eg status information, eg in SCADA or control programs.
A: Your example tests whether x has at most 1 bit set. f returns 0 if x is a power of 2 and non-zero if it is not.
A: Your particular example tests if two consecutive bits in the binary representation are 1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gpg decryption giving error in LINUX "can't query passphrase in batch mode" Hi im using gpg to decrypt a file in linux, im using
shell_exec("gpg --batch --passphrase-file $passphrase_file -d $encrypted_file");
to decrypt the file, but im getting the following errors.
gpg: gpg-agent is not available in this session
gpg: can't query passphrase in batch mode
gpg: Invalid passphrase; please try again ...
gpg: can't query passphrase in batch mode
gpg: Invalid passphrase; please try again ...
gpg: can't query passphrase in batch mode
A: This error makes it appear that the commaand doesnt like to be run using shell_exec (similar to how sudo/ssh warns about needing a tyy when run with shell_exec)::
gpg: gpg-agent is not available in this session
What happens if u run it directly from the shell prompt?
Also, make sure your not in safe mode:
shell_exec() (functional equivalent of backticks)
This function is disabled when PHP is running in safe mode.
Check with phpinfo()
check that the function is not disabled:
$ grep 'disable_functions' /etc/php.ini
Edit:
Also, try using putenv to point GNUPGHOME to your .gnupg folder.
It could be that the php script is being run as the httpd user and the gpg is expecting the 'user' user for your site.
A: I ran into a similar problem calling gpg from cron.
The command works fine when run from the command line or from a shell script. Running the command from cron fails with the same errors you're getting.
Two resources I found were a good gpg cheetsheet
And this answer on serverfault
I was able to get it to work after generating a gpg key.
gpg --gen-key
And then encrypt with:
gpg -e -r name@domain.tld backup_file.tgz
A: In order to decrypt gpg encrypted files using relevant passphrase file and running it through an applicative context, use the following formula:
gpg --no-tty --no-use-agent --yes --passphrase-file <pass-phrase-file>
--output <decrypted-file-path> --decrypt <encrypted-file-path>
example:
$ cd /home/app/gpg_example
$ ls -la
-rwxr-xr-x 3 user root 1000 Jan 1 00:00 secret_passphrase.txt
-rwxr-xr-x 3 user root 7000 Jan 1 00:00 encrypted-file.tar.gpg
$ gpg --no-tty --no-use-agent --yes --passphrase-file secret_passphrase.txt
--output decrypted-file.tar --decrypt encrypted-file.tar.gpg
$ ls -la
-rwxr-xr-x 3 user root 1000 Jan 1 00:00 secret_passphrase.txt
-rwxr-xr-x 3 user root 7000 Jan 1 00:00 encrypted-file.tar.gpg
-rwxr-xr-x 3 user root 6970 Jan 1 00:00 decrypted-file.tar # <= that's decrypted file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Help with my simple javascript/jquery I have an id #navigation li a and a class .menu-description . I want to change class from .menu-description to .menu-descriptionnew whenever user hovers on #navigation li a
My jquery so far:
<script>
$(document).ready(function() {
$('#navigation li a').onmouseover(function() {
//Check if element with class exists, if so change it to new
if ($('div.menu-description').length != 0)
$('div.menu-description').removeClass('menu-description').addClass('menu-descriptionnew');
//Check if element with class 'menu-descriptionnew' exists, if so change it to 'menu-description'
else if ($('div.menu-descriptionnew').length != 0)
$('div.menu-descriptionnew').removeClass('menu-descriptionnew').addClass('menu-description');
});
});
</script>
But it's not working. Any suggestions? Thanks!
A: The jQuery event is "mouseover" not "onmouseover"
You could clean up your code a lot with the use of .toggleClass() method and the .hover() event
Here's a simple example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: response-gating next message send, with Rx given a List<Message> i send out the first message with my Send(message). Now I would like to wait for (an asynchronous) response to come back before i send out the next message...
Block until notified 'old' way
i know how to implement an event-based solution for this situation, using thread locking / with Monitor.Wait and Monitor.Pulse
Reactive 'new' way?
But I was wondering whether it would make sense to utilize Reactive Extensions here?
If Rx would convey worthwhile benefits here then how could I make the response reactively gate the next send invocation? Obviously it would involve IObservable, probably two as primary sources, but then what?
A: I think Rx is a good choice here, but I think I could be missing something in your requirements. From what I understand Rx provides a very simple solution.
If you already have a list of messages then you can send them reactively like so:
messages
.ToObservable()
.ObserveOn(Scheduler.ThreadPool)
.Subscribe(m =>
{
Send(m);
});
This pushes the calls to Send to the thread-pool and, by the built-in behaviour of observables, each call to Send waits until the previous call is completed.
Since this is all happening on a different thread your code is non-blocking.
The extra benefit of Rx is that you wouldn't need to change the behaviour or signature of your Send method to make this work.
Simple, huh?
I tested this and it worked fine given my understanding of your problem. Is this all you need or is there something I missed?
A: The question is not very specific and seems to be very general in the sense that you have not mentioned what is the sender receiver etc, so the answer would also be very general :)
var receiveObs = //You have created a observable around the receive mechanism
var responses = messages.Select(m => {
send(m);
return receiveObs.First();
}).ToList();
A: I'm not sure Rx is a good fit here. Rx is based on the concept of "push collections", i.e. pushing data to consumers instead of pulling it. What you want is pull the first item, send it asynchronously, and continue with the next element when the asynchronous operation finished. For this kind of job, the perfect tool would be async / await*!
async void SendMessages(List<Message> messages)
{
foreach (Message message in messages)
{
await SendAsync(message);
}
}
with
Task SendAsync(Message message);
* available in the Async CTP or the .NET 4.5 Preview
A: Assuming your Send method follows the APM model, the following approach should work for you
List<Message> messages;
IObservable<Response> xs;
xs = messages.ToObservable().SelectMany(msg => Observable.FromAsyncPattern(Send, msg));
Edit - this won't work as Anderson has suggested, here's an example showing the problem
Func<int,string> Send = (ii) => { "in Send".Dump(); Thread.Sleep(2000); return ii.ToString(); };
Func<int,IObservable<string>> sendIO = Observable.FromAsyncPattern<int,string>(Send.BeginInvoke, Send.EndInvoke);
(new [] { 1, 2, 3 }).ToObservable().SelectMany(sendIO).Dump();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Class not found: org.eclipse.jdt.core.JDTCompilerAdapter I'm Using Eclipse SDK to develop my bundles. But whenever I want to export (File -> Export -> Plug-in Development -> "Deployable plug-ins and fragment") the Bundle I receive the following error screen. is there any solution or particular reason?
A: It means that you're missing a JAR from your CLASSPATH.
You can use FindJar to help you find it:
http://www.findjar.com/index.x?query=org.eclipse.jdt.core.JDTCompilerAdapter
A: Just needed to check the "Use class files compiled in the workspace" checkbox in options tab!
.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple GROUP_CONCAT on different fields using MySQL I have a query like this:
SELECT product.id,
GROUP_CONCAT(image.id) AS images_id,
GROUP_CONCAT(image.title) AS images_title,
GROUP_CONCAT(facet.id) AS facets_id
...
GROUP BY product.id
And the query works, but not as expected, because if I have a product with 5 facets and 1 image (suppose an image with id=7), then I get something like this in "images_id":
"7,7,7,7,7"
If I have 2 images (7 and 3) then I get something like:
"7,7,7,7,7,3,3,3,3,3"
and in facets I get something like:
"8,7,6,5,4,8,7,6,5,4"
I think MySQL is making some type of union of the differents rows returned by the query, and then concatenating everything.
My expected result is (for the last example):
images_id = "7,3"
facets_id = "8,7,6,5,4"
I can obtain that using DISTINCT in the GROUP_CONCAT, but then I have another problem:
If I have two images with the same title, one of them is ommited, and then I get something like:
images_id = "7,3,5"
images_title = "Title7and3,Title5"
So I miss the relation between images_id and images_title.
Does somebody know if it's possible to make this query in MySQL?
Maybe I'm complicating everything without any real benefits.
I'm trying to execute only one query because performance, but now I'm not so sure if it's even faster to execute two queries (one for selecting the facets and another for the images for example).
Please explain what do you think is the best solution for this and why.
Thanks !
A: Just add DISTINCT.
Example:
GROUP_CONCAT(DISTINCT image.id) AS images_id
A: You can add just the DISTINCT keyword, you'll get your desire results.
SELECT tb_mod.*, tb_van.*,
GROUP_CONCAT(DISTINCT tb_voil.vt_id) AS voil,
GROUP_CONCAT(DISTINCT tb_other.oa_id) AS other,
GROUP_CONCAT(DISTINCT tb_ref.rp_id) AS referral
FROM cp_modules_record_tbl tb_mod
LEFT JOIN cp_vane_police_tbl tb_van ON tb_van.mr_id= tb_mod.id
LEFT JOIN cp_mod_voilt_tbl tb_voil ON tb_voil.mr_id= tb_mod.id
LEFT JOIN cp_mod_otheraction_tbl tb_other ON tb_other.mr_id= tb_mod.id
LEFT JOIN cp_mod_referral_tbl tb_ref ON tb_ref.mr_id= tb_mod.id
WHERE tb_mod.mod_type = 2 GROUP BY tb_mod.id
A: You'll need to get each group separately:
SELECT
p.id,
images_id,
images_title,
facets_id,
...
FROM PRODUCT p
JOIN (SELECT product.id, GROUP_CONCAT(image.id) AS images_id
FROM PRODUCT GROUP BY product.id) a on a.id = p.id
JOIN (SELECT product.id, GROUP_CONCAT(image.title) AS images_title
FROM PRODUCT GROUP BY product.id) b on b.id = p.id
JOIN (SELECT product.id, GROUP_CONCAT(facet.id) AS facets_id
FROM PRODUCT GROUP BY product.id) b on c.id = p.id
...
A: If the issue is speed, then it may be a lot faster to simply select all the data you need as separate rows, and do the grouping in the application, i.e.:
SELECT product.id, image.id, image.title, facet.id
Then in the application:
foreach row:
push product_id onto list_of_product_ids
push image_id onto list_of_image_ids
etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Look and feel of datepicker Does anybody have a clue about this date picker are looking like this??
I wrote a partial view to added the attribute to the textbox
@model System.DateTime
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { data_datepicker = true });
Are this affecting the resulting datepicker??
A: I would immediately assume an issue with CSS. verify you have the correct CSS and everything is loading
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net: change color of listbox items a listbox on a webform is being populated by a datasource on a sql server 2008.
depending on the text in the list box i would liek the backgroudn color of that specific item to be a specific color
for example if these are the items in the list:
AA item 1
AA item 2
BB item 3
BB item 4
AA item 5
if the item begins with AA, then make the background green and if the item beings with BB then make it blue
how can i do this?
the solution can be client or server side, doesnt matter to me
i am currenlty doing this:
function colorproblemlist() {
ob = document.getElementById('lstProblems');
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[i].value.indexOf('AA')!=-1) {
ob.options[i].style.color = "red";
}
}
}
and it's working great!!
however i have the following complication.
the first column as you see below:
AA item 1
AA item 2
BB item 3
BB item 4
AA item 5
will not be visible
only the second one will be visible:
Item 1
Item 2
...
this column :
AA
AA
..
is a field in the database table from which this data is pulled and i need the color to be based on that field.
how can i do this?>
A: Server-side approach:
<asp:ListBox ID="prevSubList" runat="server" Height="16px" DataTextField="Key"
DataValueField="Value" Width="263px" Rows="1"
OnDataBound="prevSubList_DataBound">
</asp:ListBox>
And the DataBound Event is handled as follows:
protected void prevSubList_DataBound(object sender, EventArgs e)
{
foreach (ListItem item in prevSubList.Items)
{
if (item.Text.Contains("AA"))
item.Attributes.Add("style","background-color:green;");
else if(item.Text.Contains("BB"))
item.Attributes.Add("style", "background-color:blue;");
}
}
A: Something like:
function colorproblemlist() {
ob = document.getElementById('lstProblems');
for (var i = 0; i < ob.options.length; i++) {
var option = ob.options[i];
switch(option.value.substr(0,2))
{
case "AA":
option.style.color = "Red";
break;
case "BB":
option.style.color = "Green";
break;
}
option.value = option.value.slice(3); //Assumption of 'AA '
}
}
Based on the removal of the AA, BB flags from the html, modifying the color on the client will no longer be possible.
A: Since the data that controls the color is not part of the listitem you will have to manually add the items and color them before adding them.
ASPX page:
<asp:ListBox ID="testListBox" runat="server"
onload="TestListBoxOnLoad">
</asp:ListBox>
Code-behind (I just used an array of strings and their length to test it out, your logic will be different):
private string[] testData = new string[] { "Alpha", "Beta", "Gamma", "Delta", "Eta", "Theta", "Zeta", "Iota" };
protected void TestListBoxOnLoad(object sender, EventArgs e)
{
foreach (var data in testData)
{
ListItem item = new ListItem()
{
Text = data
};
if (data.Length < 5)
{
item.Attributes.Add("class", "aaStyle");
}
else
{
item.Attributes.Add("class", "bbStyle");
}
testListBox.Items.Add(item);
}
}
A: I don't know if this is against the rule of the asp .net mvc but what I did to solve a similar problem was not to use the @Html.ListBoxFor.
I check what the @Html.ListBoxFor add to the html and did the validations manually.
I guess if I change the name of the List (in the model) I'll have to return to my code and modify it manually too (less scalable and maintainable code)
this is my case:
<label for="EventsList" style="font-size:.9em" >Evento</label>
<select id="EventsList" multiple="multiple" name="Eventos">
@foreach (var evento in Model.Eventos)
{
string style = "";
switch (evento.Estado)
{
case 0:
style = "background-color:#ff6868";
break;
case 1:
style = "background-color:#ff8355";
break;
case 2:
style = "background-color:#fcfc6a";
break;
case 3:
style = "background-color:#79d779";
break;
}
<option value="@evento.Id" style="@style">@evento.Descripcion</option>
}
</select>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Selenium: simulating typeing on Chrome Does anybody know how to simulate typing on Chromium? I want to simulate real typing and I successfully used combination of keydown+keypress+keyup on firefox. However, this approach does not work on Chrome. I tried key{down|press|up}native but that does not help, either. Using type command does not work, because it is not simulating the real typing, it is just setting the input element's value. I know there is a bug in Chromium where one is not able to dispatch key events successfully, but I wasn't sure does Selenium works on javascript level, or maybe on window level. Is this an obstacle I can't get over?
Thanks!
A: I don't know how you are using Selenium but if you are using it through Selenium RC API you can use normal type (which copies the string into the field). After that try using something like fireEvent("yourstringlcoator", "KeyUp"). This has worked for me in a situation when I wanted the keyUP event triggered (this was with jQuery datatables actually).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: z in translate3d Can anyone explain or point me to an example where the "z" in translate3d (webkit transform) is being used? I have successfully used translate3d(x,y,0) to get hardware accelerated 2D animations on mobile Safari, but now I’m trying to scale using the z parameter, but it does not seem to have any effect...
elem.style.WebkitTransform = 'translate3d(100px,0,0)'; // this works as expected
elem.style.WebkitTransform = 'translate3d(0,0,100)'; // nothing happens
elem.style.WebkitTransform = 'translate3d(0,0,100px)'; // nothing happens
elem.style.WebkitTransform = 'scale(1.2, 1.2)'; // works but slow on ios
Sidenote: I’m trying to build a small zoom script that works smoothly on ios.
A: I made this for you to show how webkit transform 3D works:
http://jsbin.com/iderag
I hope it help you. I'm guessing you don't have -webkit-perspective in your body or parent tag.
A: Remember to set the -webkit-perspective on the containing box. 800 is a good starting value. If the box disappears, reduce it, it's probably bigger than the viewport.
The Surfin' Safari blog has an article from when 3d transforms were first invented:
-webkit-perspective is used to give an illusion of depth; it
determines how things change size based on their z-offset from the z=0
plane. You can think of it as though you’re looking at the page from a
distance p away. Objects on the z=0 plane appear in their normal size.
Something at a z offset of p/2 (halfway between the viewer and the z=0
plane) will look twice as big, and something at a z offset of -p will
look half as big. Thus, large values give a little foreshortening
effect, and small values lots of foreshortening. Values between 500px
and 1000px give a reasonable-looking result for most content.
More here: http://www.webkit.org/blog/386/3d-transforms/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to adjust trailing whitespace? I am writing to a file in java but the strings that are input into the file are different, how do i adjust the trailing whitespace depending on the length of the string.
for example
First Name Last Name Address
---------- --------- -------
Michael Jordan 23 E. Jump Street
Larry Bird 33 North Celtics Run
A: If you're trying to write to a file with padding, then consider writing to the file using a PrintWriter, and using its printf(...) method. The API will tell you how to use this.
e.g.,
public class PrintfExample {
public static void main(String[] args) {
String formatString = "%-14s %-14s %-14s%n";
String[][] data = {{"First Name", "Last Name", "Address"},
{"---------", "---------", "---------"},
{"Smith", "John", "100 Main St"},
{"Michael", "Jordan", "23 E. Jump Street"},
{"Larry", "Bird", "33 North Celtics Run"}};
for (int i = 0; i < data.length; i++) {
// you would be writing to a File wrapped in a PrintWriter using printf
// instead of to System.out (which is in fact a PrintWriter object),
// but the technique is the same.
System.out.printf(formatString, data[i][0], data[i][1], data[i][2]);
}
}
}
A: You can use String.format():
System.out.println(String.format("[%-20s]", "foo"));
will give you:
[foo ]
A: Or like this, just use substring():
public class FormatFields {
private static final String [] [] data = {
{"First Name", "Last Name", "Address"},
{"----------", "---------", "-------"},
{"Michael", "Jordan", "23 E. Jump Street"},
{"Larry", "Bird", "33 North Celtics Run"}
};
private static final int FIELD_LENGTH = 20;
private static final String PADDING = " "; // 20 spaces
/**
* @param args
*/
public static void main(String[] args) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print((data[i][j] + PADDING).substring(0, FIELD_LENGTH));
}
System.out.println();
}
}
}
Will give you
First Name Last Name Address
---------- --------- -------
Michael Jordan 23 E. Jump Street
Larry Bird 33 North Celtics Run
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL - Query only the first 25 columns in that table 75 columns in a table - I want to query only the first 25 columns in that table without naming each column name.... can you assist with a SQL query....
I been playing with the following:
Select Table_Name, Count(*) As ColumnCount
From Information_Schema.Columns
Group By Table_Name
Order By Table_Name
Doesn't meet my output........
If a Table has 75 columns, How can I see the first 25 columns without naming each column name? Don't want to delete Columns Only want to see the first 25 columns out of 75 columns in the same table.....TOP is not enable need another work around....
A: First 25 columns in a table query built into @query and then executed. Substitute correct @target_table value.
DECLARE
@target_table sysname
, @query nvarchar(max)
SET
@target_table = '_dimAreaOverlay'
; with of_interest as
(
SELECT
SS.name AS schemaname
, T.name AS tablename
, SC.name AS columname
FROM
sys.schemas SS
inner join
sys.tables T
ON T.schema_id = SS.schema_id
inner join
sys.columns SC
ON SC.object_id = T.object_id
WHERE
T.name = @target_table
AND SC.column_id < 26
)
, c AS
(
SELECT
STUFF((
SELECT
',' + QUOTENAME(I.columname)
FROM
of_interest I
FOR XML PATH('')), 1,1, '') AS column_list
, OI.tablename
, OI.schemaname
FROM
of_interest OI
GROUP BY
OI.schemaname
, OI.tablename
)
SELECT
@query = 'SELECT '
+ C.column_list
+ ' FROM '
+ QUOTENAME(C.schemaname)
+ '.'
+ QUOTENAME(C.tablename)
FROM C
EXECUTE(@query)
A: *
*Find the table in Management Studio Object Explorer.
*Right click it and choose Script Table As -> Select To -> New Query Editor Window
*Delete unwanted columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails 'routing' based on model properties I am trying to do different things on the home page of my application based on properties of the currently authenticated user. For example:
location, user, state, -> destination
/, no user -> a home page
/, user authenticated, state: unverified -> user profile page
/, user authenticated, state: verified -> a content listing
What this looks like is that I am trying to 'route' based on the current user's state (as represented by a state machine). These 3 actions already exist in 3 different controllers (I call them 'pages', 'users', and 'posts'), but while one can call another controller's view, one can't call another controller's action, making it a little tough to not repeat myself. There's a number of ways to deal with this, but I'm not sure what The Rails Way is for this, so I thought I'd ask. I see as my options:
*
*Use redirect_to in a hypothetical 'redirect controller', but I want the page to appear under /, so this isn't what I want.
*Get fancy with a routing constraint (not sure this is possible; need sessions/cookies available in routing and I'm not sure that's the case)
*Pull the logic for the particular actions out of their respective controllers, toss them into ApplicationController, and use them directly based on the user's state in a hypothetical controller (or just toss it into pages).
*Repeat myself significantly, either in the controller, the views, or both
*Yet-unknown options, I'm open to suggestions.
I'm leaning towards the third option, with the obvious downside that some piece of those controllers will now more or less inexplicably live in the ApplicationController (unless, god help me, I do some sort of Lovecraftian include-on-extend). Having this code live in two places feels dirty to me.
Am I missing something obvious?
A: Would a single action that uses a helper to pick the right partial based on the current state of the user work?
Also, take a look at using ActiveSupport::Concern instead of getting all Lovecraftian include-on-extend. http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Initializing Perl variables using eval I'm guessing this should be something obvious to those knowing Perl, but I simply don't get it... I also guess it has to do with problems described in Perl scoping « darkness - but I cannot apply any of that in my case.
Anyway, here's the code:
#!/usr/bin/env perl
# call with:
# ./test.pl
use strict;
my $tvars = "my \$varA = 1;
my \$varB = 2;
my \$varC = 3;
";
my @lines = split /\n/, $tvars;
foreach my $line (@lines) {
print "$line\n";
eval $line; warn $@ if $@;
}
#~ print "$varA\n"; # Global symbol "$varA" requires explicit package name at ./test.pl line 18.
#~ print "$varB\n"; # Global symbol "$varB" requires explicit package name at ./test.pl line 19.
#~ print "$varC\n"; # Global symbol "$varC" requires explicit package name at ./test.pl line 20.
$tvars = "our \$varA = 1;
our \$varB = 2;
our \$varC = 3;
";
@lines = split /\n/, $tvars;
foreach my $line (@lines) {
print "$line\n";
eval $line; warn $@ if $@;
}
print "$varA\n"; # Global symbol "$varA" requires explicit package name at ./test.pl line 33.
print "$varB\n"; # Global symbol "$varB" requires explicit package name at ./test.pl line 34.
print "$varC\n"; # Global symbol "$varC" requires explicit package name at ./test.pl line 35.
Simply speaking, I'd like to have something like "$varA = 1;" written as a string (text file); and I'd like perl to eval it, so that afterwards I have access to variable "$varA" in the same script - the errors I get when I try to access those after an eval are in the comments of the code above (however, no warnings are reported during the eval). (I'm guessing, what I'd need is something like "global" variables, if the eval runs in a different context than the main script?)
How would I go about doing that? Do I have to go through all of that package definition business, even for a simple script like the above?
A: The problem is that when you do eval $string, $string is evaluated as its own subroutine which has its own lexical scope. From perldoc -f eval:
In the first form [in which the argument is a string], the return value of EXPR is parsed and
executed as if it were a little Perl program. The value of the expression (which is itself
determined within scalar context) is first parsed, and if there were no errors, executed in the
lexical context of the current Perl program, so that any variable settings or subroutine and format
definitions remain afterwards.
So, in other words, if you have:
use strict;
use warnings;
eval "my $foo=5;";
print "$foo\n";
you'll get an error:
Global symbol "$foo" requires explicit package name at -e line 3.
Global symbol "$foo" requires explicit package name at -e line 4.
However, if you initialize your variables first, you're fine.
use strict;
use warnings;
my $foo;
eval "\$foo=5;";
print "$foo\n"; #prints out 5, as expected.
A: It has everything to do with scoping. The variables are declared with my inside the eval expression. This makes them local to the eval statement and not accessible once the eval statement exits. You can declare them first, though:
my ($varA, $varB, $varC); # declare outside the eval statement
my $tvars = "\$varA = 1;
\$varB = 2;
\$varC = 3;
";
eval $tvars;
# local $varA, $varB, $varC variables are now initialized
or as you suggest, you can use global variables. The easiest (though not necessarily the "best" way) is to prepend :: to all variable names and get them in the main package.
my $tvars = "\$::varA = 1;
\$::varB = 2;
\$::varC = 3;
";
eval $tvars;
print "A=$::varA, B=$::varB, C=$::varC\n";
Now when you tried our variables in your example, you actually were initializing package (global) variables. But outside the eval statement, you still need to qualify (i.e., specify the package name) them in order to access them:
$tvar = "our \$foo = 5";
eval $tvar;
print $main::foo; # ==> 5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Qt: Enumerating Windows on the desktop(s) My Qt application (that will run on Windows, OS X and Ubuntu) has a need to:
*
*List all windows everywhere
*Obtain their caption text (if any)
*Obtain an Icon of the application, if any, as QIcon or QPixmap (e.g. App Icon)
*Obtain some kind of unique ID about them (e.g. HWND on windows)
I know how to do this for Windows using Win32. I can research Mac and Ubuntu separately, but I was wondering if there's an abstracted/unified Qt approach to assist me?
A: Nope, those are OS specific:
http://www.qtcentre.org/threads/41730-How-to-enumerate-all-top-level-windows
As for starting down the quest of what's doable through published APIs...some X11 hints here:
How to identify top-level X11 windows using xlib?
On Macs, the "forward-looking" way to build Qt is against "Cocoa" instead of "Carbon":
http://doc.qt.nokia.com/latest/developing-on-mac.html#carbon-or-cocoa
And according to other SOers, it's the accessibility API (which has to be enabled by users, it seems) that can do this enumeration:
Get a list of opened windows cocoa
Mac / Cocoa - Getting a list of windows using Accessibility API
Then the question becomes how inside of a C++ application to make "calls out" to Cocoa APIs which are natively Objective-C:
How to mix Qt, C++ and Obj-C/Cocoa
...or you could just not do this. :-)
A: I would suggest keeping track of this information yourself. It wouldn't be perfect (just have a singleton class and overload the setWindowTitle() calls in your root window types) but would be platform-independent . . .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: iphone: addObjectsFromArray not adding after reinitializing nsmutable array i have the following code
inAppKeys = [[MKStoreManager sharedManager] purchasableObjectsDescription ];
NSMutableArray * unremovableArray = [[NSMutableArray alloc] init];
for(int i = 0; i<[inAppKeys count]; i++){
for (int j=0; j< [categories count]; j++) {
NSString * inAppKey = [[categories objectAtIndex:j] valueForKey:@"inAppKey"];
if([inAppKey isEqualToString: [inAppKeys objectAtIndex:i]]){
[unremovableArray addObject:[categories objectAtIndex:j]];
}
}
}
categories = [[NSMutableArray alloc] init];
[categories addObjectsFromArray:unremovableArray];
where categories is nsmutablearray .. the thing is addObjectsFromArray leave the categories empty .. what do i do wrong?
A: Looks to me like you're referring to [categories count] and [categories objectAtIndex:j] before you even alloc/init categories.
Having re-read your title ("reinitializing") which suggests you've previously inited categories, I'm now assuming that you have a master set of categories that you're trying to reduce to the ones actually purchased. If so, I wouldn't re-use the variable "categories" as that's confusing. (I assume categories was auto-released, or else you've got a leak). How 'bout using unremovableArray instead of leaking it?
I'd also use fast enumerators for clarity and speed...
NSLog(@"categories: %@", categories);
inAppKeys = [[MKStoreManager sharedManager] purchasableObjectsDescription ];
NSLog(@"inAppKeys:%@", inAppKeys);
NSMutableArray * unremovableCategories = [[NSMutableArray alloc] init];
for(NSString* thisAppKey in inAppKeys) {
for (NSDictionary* thisCategory in categories) {
if ([[thisCategory valueForKey:@"inAppKey"] isEqualToString: thisAppKey]){
[unremovableCategories addObject:thisCategory];
break; //having added this category; no reason to continue looking at it
}
}
}
//now use unremovableCategories...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: running embedded javascript - a small test file I've updated the code to reflect input.
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<!-- <script type="text/javascript" src="../archelib.js"></script> -->
<title>Test - Bookmark List</title>
<style>
</style>
</head>
<body>
<span id="f0e"></span>
<script type="text/javascript">
var arr1=['','a','b','c']
document.write(check_empty(arr1,'f0e','fail'));
function check_empty(text,id,res)
{
for(var d=0;d<text.length;d++)
{
if(text[d].value=='')
{
o2(id,res);
return 0;
}
}
return 1;
}
function o2(a,b)
{
return document.getElementById(a).innerHTML=b;
}
</script>
</body>
</html>
A: Use type array for the input argument.
A: change
if(text[d].value=='')
to
if(text[d].value!='')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Downloading files Right now I have <a href="...">FILE</a> to allow users to download a file. I don't like that because it forces them to leave the current page and have to reload it (which takes a few seconds) when they want to go back
What is the easiest way to have users download a file?
A: Have the server send a Content-Disposition: attachment header for the resource in question. It'll then be presented to the user (if they have a sane browser) as a file to "save", rather than as a new page.
For certain types of resources this may mean you write a proxy script in PHP, or perhaps you can configure your webserver to do it.
A: Use this method:
<a href="..." target="_blank">FILE</a>
A: The most reliable way to force a download without a server-side solution is to ZIP the file and then link to this archive. Provided that there aren't any limitations on using ZIP files almost every web browser I've encountered will download the file to the user's computer.
If you don't have server-side support, which I am just assuming because you're asking about the HTML and not a scripting language, you cannot always make a file download form the browser. This is because not every web browser is configured the same and the default application on the user's computer may also be set to something you can't predict.
Also, you should use the linking method that @craig1231 suggested so that the file download request is happening in a new window.
<a href="..." target="_blank">FILE</a>
This will cut down on some of the time needed to refresh pages and, in most cases, when the web browser encounters a ZIP file as the URL of the window it will close the window once the file starts to download.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Static image file is invisible in node.js/express The following code is an exemple of code to serve static files in express on node.js. If I ask the server a .css file there is no problem, but if I ask an image such as a jpg or png, it loads a white page (no /GET error or anything, a simple white page). In my developer tool in my browser I see the following warning: 1Resource interpreted as Document but transferred with MIME type image/jpeg. How can I fix this?
I am using cloud9ide and express 2.4.6
var express = require("express"),
app = express.createServer();
app.use(express.static(__dirname + '/static'));
app.get('/', function(req, res){
res.send('Hello World');
});
app.listen(process.env.C9_PORT);
A: It looks like the file in question is not in JPEG format. Can you save that URL as a file using wget, curl or similar tools and open that file in a text editor?
A valid JPEG file should look like binary garbage and should have "JFIF" signature string close to the beginning (byte offset 6 I think).
it is possible that the file contains an error message instead of valid JPEG data.
A: It seems to be a bug from cloud9 ide. I tried my code locally and it worked. There is a ticket open on cloud9ide at: http://cloud9ide.lighthouseapp.com/projects/67519/tickets/390-get-png-image-not-working-in-preview-mode#ticket-390-4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using wrapper Integer class or int primitive in hibernate mapping In the company that I work for we have this major discussion on whether it should be better to use wrapping classes for primitives (java.lang.Integer, java.lang.Long) or whether to use the primitive types directly in the POJOs that map Entities to Tables in Hibernate.
The idea is that we want these values to not be null in the database.
The arguments in favor of using primitives:
*
*Handling these values as int means that they can never be null, in
this way making it impossible to inadvertently get a null reference
on the field.
*int=32/64 bits of memory. Integer = 16 bytes of memory
and is also slower
The arguments in favor of using wrapper objects:
*
*We can add a constraint at the database level to always prevent null
values from getting there
*We can end up with misleading data, we can
have 0's instead of nulls in the database whenever the user doesn't
set a value and buggy data is a tough catch.
*Objects have more expressive power than primitives. We have null values and also
integer values, so we can validate them easier using annotations for
example (javax.validation.constraints.NotNull).
A: The Hibernate documentation (just the first version I happened to find) states:
The property might have been called anything, and its type might have been any primitive type, any primitive "wrapper" type, java.lang.String or java.util.Date.
...
We recommend that you declare consistently-named identifier properties on persistent classes and that you use a nullable (i.e., non-primitive) type.
So the "expert's voice" suggests using Integer / Long... but it's not described why this is the case.
I wonder whether it's so that an object which hasn't been persisted yet can be created without an identifier (i.e. with a property value of null), distinguishing it from persisted entities.
A: Use wrappers, make your life simple.
Your data model should dictate this. You should be enforcing nullability in the database anyway.
If they are nullable in the database, then use wrappers. If they are not nullable, and you use wrappers, then you'll get an exception if you try and insert a null into the database.
If your data model doesn't dictate it, then go for a convention, use wrappers all of the time. That way people don't have to think, or decide that a value of 0 means null.
I would also query your assertion that it would less performant. Have you measured this? I mean really measured it? When you're talking to a database, there are a lot more considerations than the difference between 16 bits and 32 bits.
Just use the simple, consistent solution. Use wrappers everywhere, unless somebody gives you a very good reason (with accurate measured statistics) to do otherwise.
A: Thought it should be mentioned:
Hibernate recommendation (section 4.1.2) using non-primitive properties in persistent classes actually refers - as titled - to identifier properties:
4.1.2. Provide an identifier property
Cat has a property called id. This property maps to the primary key column(s) of a database table. The property might have been called anything, and its type might have been any primitive type, any primitive "wrapper" type, java.lang.String or java.util.Date.
...
We recommend that you declare consistently-named identifier properties on persistent classes and that you use a nullable (i.e., non-primitive) type.
Nonetheless, the advantages of primitives aren't strong:
*
*Having an inconsistent non-null value in a property is worse than NullPointerException, as the lurking bug is harder to track: more time will pass since the code is written until a problem is detected and it may show up in a totally different code context than its source.
*Regarding performance: before testing the code - it is generally a premature consideration. Safety should come first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
} |
Q: Reading and writing to the file Android I am learning Android and I am making some basic math program(game). It gets two random numbers, random operator, and 30 secs to solve math problems as much as you can. If you solve problem u get 1 point.
Anyway right now, I want to get number of points that user have made, and write it to the file, and later to read it ( for now just to log it).
When I click to button to write file, it does and I get this log message:
09-21 21:11:45.424: DEBUG/Writing(778): This is writing log: 2
Yeah, seems that it writes. Okey, lets read it.
09-21 21:11:56.134: DEBUG/Reading log(778): This is reading log:2
It reads it.
But when I try again to write, it seems that it will overwrite previous data.
09-21 21:17:19.183: DEBUG/Writing(778): This is writing log: 1
09-21 21:17:28.334: DEBUG/Reading log(778): This is reading log:1
As you can see it reads just last input.
Here it is that part of code, where I am writing and reading it.
public void zapisi() {
// WRITING
String eol = System.getProperty("line.separator");
try {
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(poenibrojanje+eol);
//for(int i=0;i<10;i++){
Log.d("Writing","This is writing log: "+poenibrojanje);
//}
//osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void citaj() {
// READING
String eol = System.getProperty("line.separator");
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
openFileInput("samplefile.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
}
//TextView textView = (TextView) findViewById(R.id.result);
Log.d("Reading log","This is reading log:"+buffer);
System.out.println(buffer);
//tvRezultat.setText(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
A: You can use the openFileOutput ("samplefile.txt", MODE_APPEND)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get up-down control from buddy? Is it possible to get a handle to an up-down control from a handle to its buddy? So UDM_GETBUDDY is not an option.
Thanks!
A: Why would the buddy window know or care about the up-down control?
There are probably several workarounds you can use:
*
*Store the handle in the buddy's window with GWL_USERDATA or SetProp()
*Give the u/d control a id relative to the buddy (id+1 or id+1000 etc) and use GetDlgItem
*Enumerate all the windows in the dialog and ask every u/d control.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Accessing the contents of Map> in jsp using key value I have a jsp page that receives a HashMap object of this type:
Map<Long, Map<String, Object>>.
An example of this map would be: foo = {1 = {id=1, response="someText"}, 2={id=99, response="random"}};
I am trying to iterate over the contents of both maps in foo like this:
<c:forEach items="${fooMap.content}" var="outerMap">
<c:forEach items="${outerMap.value}" var = "innerMap">
<p>${innerMap.response}</p>
</c:foreach>
</c:forEach>
But this throws "Property 'response' not found on type java.util.HashMap.....
Would someone please tell me what I am doing wrong?
I know that I can access the contents of innerMap using Map.EntrySet. But I want to access the value using specific keys.
A: The ${outerMap.value} returns a Map<String, Object> of which one entry has "response" as key. So you need to get it straight from there instead of iterating over its entryset in ${innerMap}.
<c:forEach items="${fooMap.content}" var="outerMap">
<p>${outerMap.value.response}</p>
</c:forEach>
An (more clumsy) alternative is checking the ${innerMap} entry key:
<c:forEach items="${fooMap.content}" var="outerMap">
<c:forEach items="${outerMap.value}" var="innerMap">
<c:if test="${innerMap.key == 'response'}">
<p>${innerMap.value}</p>
</c:if>
</c:foreach>
</c:forEach>
Can you now still wrap your head around it? :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I programmatically get the previous version of an item in a TFS changeset? Using the TFS APIs it is trivial to loop through changes in a changeset and then get the files using the ServerItem and ChangesetId.
But suppose I want to diff the modified files, how can I get the VersionSpec for the previous versions?
The trick of subtracting one from the ChangesetId seems to break if the file was renamed or branched?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What toolchain do I need to cross-compile Clang for iOS OK, so first of all I know that this can be compiled on iOS (armv7) because I read the documentation. However, I can't find the right toolchain.
So, now, what toolchains I've already tried:
i686-apple-darwin10-cpp-4.2.1
i686-apple-darwin10-g++-4.2.1
i686-apple-darwin10-gcc-4.2.1
The above cross-compiles to x86 (I'm on i386). Works fine. But I don't need it
arm-apple-darwin10-cpp-4.2.1
arm-apple-darwin10-g++-4.2.1
arm-apple-darwin10-gcc-4.2.1
The above compiles fine, but doesn't cross compile to arm as I would have expected, instead, it simply compiles to my current arch.
I'm a real beginner in this matter, in fact this is my first attempt to cross-compile something.
UPDATE:
Here are the commands that I've tried(this is for armv6; armv7 is similar):
configure:
../llvm/configure --host=arm-apple-darwin6 --target=arm-apple-darwin6
--build=i386-apple-darwin --enable-optimized --disable-debug
--disable-expensive-checks --disable-doxygen --disable-threads
env vars:
export DEVROOT=/Developer/Platforms/iPhoneOS.platform/Developer
export SDKROOT=$DEVROOT/SDKs/iPhoneOS$IOS_BASE_SDK.sdk
export CFLAGS="-arch armv6 -pipe -no-cpp-precomp -isysroot $SDKROOT -miphoneos-version-min=$IOS_DEPLOY_TGT -I$SDKROOT/usr/include/"
export CPP="$DEVROOT/usr/bin/arm-apple-darwin10-cpp-4.2.1"
export CXX="$DEVROOT/usr/bin/arm-apple-darwin10-g++-4.2.1"
export CXXCPP="$DEVROOT/usr/bin/arm-apple-darwin10-cpp-4.2.1"
export CC="$DEVROOT/usr/bin/arm-apple-darwin10-gcc-4.2.1"
export LD=$DEVROOT/usr/bin/ld
export AR=$DEVROOT/usr/bin/ar
export AS=$DEVROOT/usr/bin/as
export NM=$DEVROOT/usr/bin/nm
export RANLIB=$DEVROOT/usr/bin/ranlib
export LDFLAGS="-L$SDKROOT/usr/lib/"
export CPPFLAGS=$CFLAGS
export CXXFLAGS=$CFLAGS
UPDATE : The purpose of this cross compile is to make an armv7(armv6) library not a command line tool.
YET ANOTHER UPDATE: I used the following:
CC="$DEVROOT/usr/bin/clang"
CXX="$DEVROOT/usr/bin/clang++"
./llvm/configure --host=i386-apple-darwin --target=armv7-apple-darwin --build=armv7-apple-darwin --enable-optimized --disable-debug --disable-expensive-checks --disable-doxygen --disable-threads --enable-targets=arm
And I managed to get checking whether we are cross compiling... yes out of the configure tool. However, make still outputs a x86_64 binary:(
A: In principle your configure invocation looks good. I'm trying to shoot a few typical mistakes:
*
*Did you make clean after every change of architecture?
*Why are you so sure that the LD, RANLIB etc. of your host system are fine for cross-compilation? It will overwrite the auto-configured value of LD. (The line reading "export LD=ld" would be at fault here.)
*Could you check a typical compiler and a typical linker invocation in the output of make for their correct use of the cross-compilation tools?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: git push origin master:refs/heads/master what does this do When I create a new repo on my gitolite repository I always have to enter the following command before I can start pushing code to the server.
git push origin master:refs/heads/master
What does it do ?
My guess is that is has to do with the head reference not sure. Could someone explain it to me?
A: master:refs/heads/master is a refspec.
refspecs are of the form +<src>:<dst>
So here master is the ref on your local repo that you are pushing to the refs/heads/master refspec on the remote (origin). master is short for refs/heads/master actually.
In fact, you can just do git push origin master whereby it will push master on your local to master on remote. Only when you want to push to a different ref do you need to explicitly specify the destination ref.
Also just git push has default behaviour too, which probably wouldn't have been the case before you did the first push and created a branch (master ) on the remote. So it would have seemed like you need to do the command you had mentioned. Refer to the manual
A: There's three parts to this command:
git push
This invokes the push command
origin
This names the remote to which you are pushing. This is either one of the named remotes stored in .git/config (you can list these with git remote), a URL, or the token . which means the current repository.
master:refs/heads/master
This is called a "refspec", and you can read about it in the man page for git push. But in general, it's comprised of two parts, separated by a colon. The first part is the name of a local branch, and the second part is the name of a branch on the remote repository (in this case, origin). This particular refspec could be shortened to master:master.
In general, one can shorten refspecs even further. Just specifying master as the refspec is equivalent to using the same name on the remote, so master is the same as master:master.
A: The default behavior of git push, which is presumably what you describe as "pushing code to the server", is to only push local branches that have a matching branch, by name, on the remote you're pushing to. When you create a new repo, it has no branches in it, so a simple git push will push nothing. You have to explicitly push a branch by name first. Thereafter, the default behavior will work as you expect it to.
P.S. Actually, you only have to git push origin master. What it does is push your local master to the gitolite repo as master, since you didn't specify a different name. If you said git push origin master:foo, then the branch you locally call "master" would be known as "foo" on gitolite.
P.P.S. You can switch default push behavior between "nothing", "matching" (the default), "trackings"/"upstream", and "current". See the settings for "push.default" on the git-config man page.
A: It sets up tracking for you. You can use the shorthand for this:
git push origin master
The part after the colon is the name of the branch on the remote repo. If you omit it, git assumes you want the same name.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: json errors after rails upgrade I upgraded from rails 3.0.4 to 3.1.0. Then I started getting these error messages when running rails server, I had to change a couple of initializers like this:from wrap_parameters format: [:json] to wrap_parameters :format => [:json]
Now WEBrick does start up but I get A LOT of these messages: syntax error, unexpected ':', expecting '=' ...er json: @page.errors, status: :unprocessable_entity }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rewrite rule in Nginx rewrite rule:
location / {
rewrite ^/([a-z]+)/$ /index.jsp?a=$1 last;
}
and I create a directory /abc/ in the root directory ,and put a index.html in /abc/
when I access http://localhost/abc/ ,I can't get /abc/index.html
How to make http://localhost/abc/ can be access?
A: create an extra location block
location /abc {
root /your/root/dir/abc/;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CellTemplateSelector won't choose template automatically I have two templates for DataGridTemplateColumn
<DataTemplate x:Key="firstTemplate">
<UniformGrid Grid.Column="1" Columns="2">
<Label Background="{Binding Path=Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=Value}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="Visible" />
</UniformGrid>
</DataTemplate>
<DataTemplate x:Key="secondTemplate">
<UniformGrid Grid.Column="1" Columns="{Binding Converter={StaticResource getColumnsAmount}}">
<Label Background="{Binding Path=ColorData_1.Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=ColorData_1,
Converter={StaticResource ValueRangeConvert}}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="{Binding Path=ColorData_1.IsSelected,
Converter={StaticResource boolConvert}}" />
<Label Background="{Binding Path=ColorData_2.Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=ColorData_2,
Converter={StaticResource ValueRangeConvert}}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="{Binding Path=ColorData_2.IsSelected,
Converter={StaticResource boolConvert}}" />
<Label Background="{Binding Path=ColorData_3.Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=ColorData_3,
Converter={StaticResource ValueRangeConvert}}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="{Binding Path=ColorData_3.IsSelected,
Converter={StaticResource boolConvert}}" />
</UniformGrid>
</DataTemplate>
<DataGrid Name="dgLegend"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AutoGenerateColumns="False"
Background="{x:Null}"
HeadersVisibility="None"
IsHitTestVisible="True"
IsReadOnly="True"
ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTemplateColumn Width="Auto"
Header="exp"
IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border Background="{Binding Path=Color>
<Label Content="{Binding Path=Color}" />
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="*" Header="Range">
<DataGridTemplateColumn.CellTemplateSelector>
<local:LegendDisplayModeTemplateSelector
firstTemplate="{StaticResource firstTemplate}"
secondTemplate="{StaticResource secondTemplate}" />
</DataGridTemplateColumn.CellTemplateSelector>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
My TemplateSelector
public class LegendDisplayModeTemplateSelector : DataTemplateSelector
{
public DataTemplate firstTemplate
{
get;
set;
}
public DataTemplate secondTemplate
{
get;
set;
}
public DisplayMode displayMode
{
get;
set;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
TSOptions opts = (TSOptions)item;
//some other code
}
}
The problem is the item in SelectTemplate(object item, DependencyObject container) always get null
A: I found the answer.
http://social.msdn.microsoft.com/Forums/en/wpf/thread/b47ac38a-077f-41da-99b1-8b88add693d8?prof=required
He used this way:
class UserCellEdit : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
ContentPresenter presenter = container as ContentPresenter;
DataGridCell cell = presenter.Parent as DataGridCell;
Guideline_node node = (cell.DataContext as Guideline_node);
//,...... etc. the rest of the code
}
}
A: I used this solution:
public class EmployeeListDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Employee)
{
Employee employee = item as Employee;
if (employee.Place == "UK")
return element.FindResource("UKdatatemp") as DataTemplate;
else
return element.FindResource("Otherdatatemp") as DataTemplate;
}
return null;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Query to find users that haven't paid? I have the following SQL
SELECT CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
This outputs 3 rows; 1, 1 and 0
I would like to extend this query to output the booking details of the 0 value.
How can I do this?
Thanks
A: select * from booking
where booking_id not in ( select bookingid from payment )
A: If you need to have a column when paid == 0, then you will also have the column when paid == 1.
Try this:
select
case
when booking.bookingId = payment.bookingId then
1
else
0
end as paid,
column_detail1,
column_detail2
from
booking
left outter join payment on payment.bookingId = booking.bookingId
If you only want to select information when paid is 0, you might try this:
select
paid_flag.paid,
booking.detail1,
booking.detail2
from
(
select
case
when booking.bookingId = payment.bookingId then
1
else
0
end as paid,
booking.bookingId
from
booking
left outter join payment on payment.bookingId = booking.bookingId
) paid_flag
join booking on paid_flag.bookingId = booking.bookingId
where
paid_flag.paid == 0
It seems likely that the query above can be optimized.
A: If I understand your question, this will give details on both. Then you can ignore the 1 details.
SELECT CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID,
B.details
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
Other wise maybe
SELECT CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID,
WHEN B.bookingId = P.bookingId
THEN ''
ELSE B.details
END AS UNPAIDDETAILS,
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
A: If you're in SQL 2005+
;with cte as (
SELECT B.BookingId,
CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
)
select B.*
from Booking B
inner join cte
on B.BookingId = cte.BookingId
where cte.PAID = 0
A: Because the rows from Booking will always be present in the result set (since it's the left-hand table in the JOIN) you can simply include the columns you want the list of columns returned:
SELECT CASE
B.Column1Name,
B.Column2Name,
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
This will show the booking details for all records.
If you're interested in only the unpaid records, add something to your WHERE clause to limit the output to those records only:
SELECT CASE
B.Column1Name,
B.Column2Name,
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
WHERE P.bookingID IS NOT NULL
A: SELECT B.BOOKINGID AS ID, 'PAID' AS PAYMENT_STATUS
FROM BOOKING B
WHERE B.BOOKINGID IN (SELECT PAYMENT.BOOKINGID FROM PAYMENT)
UNION ALL
SELECT B.BOOKINGID, 'UNPAID'
FROM BOOKING B
WHERE B.BOOKINGID NOT IN (SELECT PAYMENT.BOOKINGID FROM PAYMENT)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Javascript function scoping and hoisting I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
Using the code above, the browser will alert "1".
I'm still unsure why it returns "1". Some of the things he says come to mind like:
All the function declarations are hoisted to the top. You can scope a variable using function. Still doesn't click for me.
A: What you have to remember is that it parses the whole function and resolves all the variables declarations before executing it. So....
function a() {}
really becomes
var a = function () {}
var a forces it into a local scope, and variable scope is through the entire function, so the global a variable is still 1 because you have declared a into a local scope by making it a function.
A: The function a is hoisted inside function b:
var a = 1;
function b() {
function a() {}
a = 10;
return;
}
b();
alert(a);
which is almost like using var:
var a = 1;
function b() {
var a = function () {};
a = 10;
return;
}
b();
alert(a);
The function is declared locally, and setting a only happens in the local scope, not the global var.
A: *
*function declaration function a(){} is hoisted first and it behaves like var a = function () {};, hence in local scope a is created.
*If you have two variable with same name (one in global another in local), local variable always get precedence over global variable.
*When you set a=10, you are setting the local variable a , not the global one.
Hence, the value of global variable remain same and you get, alerted 1
A: Suprisingly, none of the answers here mention the relevancy of the Execution Context in the Scope Chain.
The JavaScript Engine wraps the currently executing code in an Execution Context. The base execution context is the global Execution Context. Each time a new function is invoked, a new Execution Context is created and put on the Execution Stack. Think of a Stack Frame sitting on an Invocation Stack in other programming languages. Last in first out. Now each Execution Context has its own Variable Environment and Outer Environment in JavaScript.
I will use the below example as a demonstration.
1) First, we enter the Creation Phase of the global Execution Context. Both the Outer Environment and Variable Environment of the Lexical Environment are created. The Global Object is setup and placed in memory with the special variable 'this' pointing to it. The function a and its code and the variable myVar with an undefined value are placed in memory in the global Variable Environment. it's important to note that function a's code is not executed. It is just placed in memory with function a.
2) Second, it is the Execution Phase of the Execution Context. myVar is no longer an undefined value. It is initialized with value of 1, which is stored in the global Variable Environment. The function a is invoked and a new Execution Context is created.
3) In the function a's Execution Context, it goes through the Creation and Execution Phase of its own Execution Context. It has its own Outer Environment and Variable Environment, thus, its own Lexical Environment. The function b and the variable myVar are stored in its Variable Environment. This Variable Environment is distinct from the global Variable Environment. Since the function a sits lexically (physically in code) on the same level as the global Execution Context, its Outer Environment is the global Execution Context. Thus, if the function a was to refer to a variable that is not in its Variable Environment, it will search the Scope Chain and try to find the variable in the Variable Environment of the global Execution Context.
4) The function b is invoked in function a. A new Execution Context is created. Since it sits lexically in function a, its Outer Environment is a. So when it references myVar, since myVar is not in function b's Variable Environment, it will look in function a's Variable Environment. It finds it there and console.log prints 2. But if the variable was not in function a's Variable Environment, then since function a's Outer Environment is the global Execution Context, then the Scope Chain will continue searching there.
5) After function b and a are finished execution, they are popped from the Execution Stack. The single-threaded JavaScript Engine continues execution at the global Execution Context. It invokes the b function. But there is no b function in the global Variable Environment and there is no other Outer Environment to search in the global Execution Context. Thus an exception is raised by the JavaScript Engine.
function a(){
function b(){
console.log(myVar);
}
var myVar = 2;
b();
}
var myVar = 1;
a();
b();
> 2
> Uncaught ReferenceError: b is not defined
The below example shows the Scope Chain in action. In the function b's Execution Context's Variable Environment, there is no myVar. So it searches its Outer Environment, which is the function a. The function a does not have myVar in its Variable Environment either. So the Engine searches function a's Outer Environment, which is the global Execution Context's Outer Environment and myVar is defined there. Hence, the console.log prints 1.
function a(){
function b(){
console.log(myVar);
}
b();
}
var myVar = 1;
a();
> 1
Regarding Execution Context and the Lexical Environment associated with it, including Outer Environment and Variable Environment, enable the scoping of variables in JavaScript. Even if you invoke the same function multiple times, for each invocation, it will create its own Execution Context. So each Execution Context will have its own copy of the variables in its Variable Environment. There is no sharing of variables.
A: Function hoisting means that functions are moved to the top of their scope. That is,
function b() {
a = 10;
return;
function a() {}
}
will be rewritten by the interpeter to this
function b() {
function a() {}
a = 10;
return;
}
Weird, eh?
Also, in this instance,
function a() {}
behaved the same as
var a = function () {};
So, in essence, this is what the code is doing:
var a = 1; //defines "a" in global scope
function b() {
var a = function () {}; //defines "a" in local scope
a = 10; //overwrites local variable "a"
return;
}
b();
alert(a); //alerts global variable "a"
A: function a() { } is a function statement, which creates an a variable local to the b function.
Variables are created when a function is parsed, regardless of whether the var or function statement gets executed.
a = 10 sets this local variable.
A: Hoisting is a concept made for us to make it easier to understand. What actually happens is the declarations are done first with respect to their scopes and the assignments will happen after that(not at the same time).
When the declarations happen, var a, then function b and inside that b scope, function a is declared.
This function a will shadow the variable a coming from the global scope.
After the declarations are done, the values assign will start, the global a will get the value 1 and the a inside function b will get 10.
when you do alert(a), it will call the actual global scope variable.
This little change to the code will make it more clear
var a = 1;
function b() {
a = 10;
return a;
function a() { }
}
alert(b());
alert(a);
A: What is the bone of contention in this small snippet of code?
Case 1:
Include function a(){} definition inside the body of function b as follows. logs value of a = 1
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
console.log(a); // logs a = 1
Case 2
Exclude function a(){} definition inside the body of function b as follows. logs value of a = 10
var a = 1;
function b() {
a = 10; // overwrites the value of global 'var a'
return;
}
b();
console.log(a); // logs a = 10
Observation will help you realise that statement console.log(a) logs the following values.
Case 1 : a = 1
Case 2 : a = 10
Posits
*
*var a has been defined and declared lexically in the global scope.
*a=10 This statement is reassigning value to 10, it lexically sits inside the function b.
Explanation of both the cases
Because of function definition with name property a is same as the variable a. The variable a inside the function body b becomes a local variable. The previous line implies that the global value of a remains intact and the local value of a is updated to 10.
So, what we intend to say is that the code below
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
console.log(a); // logs a = 1
It is interpreted by the JS interpreter as follows.
var a = 1;
function b() {
function a() {}
a = 10;
return;
}
b();
console.log(a); // logs a = 1
However, when we remove the function a(){} definition, the value of 'a' declared and defined outside the function b, that value gets overwritten and it changes to 10 in case 2. The value gets overwritten because a=10 refers to the global declaration and if it were to be declared locally we must have written var a = 10;.
var a = 1;
function b() {
var a = 10; // here var a is declared and defined locally because it uses a var keyword.
return;
}
b();
console.log(a); // logs a = 1
We can clarify our doubt further by changing the name property in function a(){} definition to some other name than 'a'
var a = 1;
function b() {
a = 10; // here var a is declared and defined locally because it uses a var keyword.
return;
function foo() {}
}
b();
console.log(a); // logs a = 1
A: It is happening because of the Variable name is same as the function name means "a".
Thus due to Javascript hoisting it try to solve the naming conflict and it will return a = 1.
I was also confused about this until i read this post on "JavaScript Hoisting" http://www.ufthelp.com/2014/11/JavaScript-Hoisting.html
Hope it helps.
A: Here's my recap of the answer with more annotation and an acompaniying fiddle to play around with.
// hoisting_example.js
// top of scope ie. global var a = 1
var a = 1;
// new scope due to js' functional (not block) level scope
function b() {
a = 10; // if the function 'a' didn't exist in this scope, global a = 10
return; // the return illustrates that function 'a' is hoisted to top
function a(){}; // 'a' will be hoisted to top as var a = function(){};
}
// exec 'b' and you would expect to see a = 10 in subsequent alert
// but the interpreter acutally 'hoisted' the function 'a' within 'b'
// and in doing so, created a new named variable 'a'
// which is a function within b's scope
b();
// a will alert 1, see comment above
alert(a);
https://jsfiddle.net/adjavaherian/fffpxjx7/
A: scpope & closure & hoisting (var/function)
*
*scpope : the global var can be access in any place(the whole file
scope), local var only can be accessed by the local
scope(function/block scope)!
Note: if a local variable not using
var keywords in a function, it will become a global variable!
*closure : a function inner the other function, which can access
local scope(parent function) & global scope, howerver it's vars
can't be accessed by others! unless, your return it as return value!
*hoisting : move all declare/undeclare vars/function to the scope
top, than assign the value or null!
Note: it just move the declare,not move the value!
var a = 1;
//"a" is global scope
function b() {
var a = function () {};
//"a" is local scope
var x = 12;
//"x" is local scope
a = 10;
//global variable "a" was overwrited by the local variable "a"
console.log("local a =" + a);
return console.log("local x = " + x);
}
b();
// local a =10
// local x = 12
console.log("global a = " + a);
// global a = 1
console.log("can't access local x = \n");
// can't access local x =
console.log(x);
// ReferenceError: x is not defined
A: Long Post!
But it will clear the air!
The way Java Script works is that it involves a two step process:
*
*Compilation(so to speak) - This step registers variables and function declarations and their respective scope. It does not involve evaluating function expression: var a = function(){} or variable expression (like assigning 3 to x in case of var x =3; which is nothing but the evaluation of R.H.S part.)
*Interpreter: This is the execution/evaluation part.
Check the output of below code to get an understanding:
//b() can be called here!
//c() cannot be called.
console.log("a is " + a);
console.log("b is " + b);
console.log("c is " + c);
var a = 1;
console.log("Now, a is " + a);
var c = function() {};
console.log("Now c is " + c);
function b() {
//cannot write the below line:
//console.log(e);
//since e is not declared.
e = 10; //Java script interpreter after traversing from this function scope chain to global scope, is unable to find this variable and eventually initialises it with value 10 in global scope.
console.log("e is " + e) // works!
console.log("f is " + f);
var f = 7;
console.log("Now f is " + f);
console.log("d is " + d);
return;
function d() {}
}
b();
console.log(a);
Lets break it:
*
*In the compilation phase,
'a' would be registered under global scope with value 'undefined'.
Same goes for 'c', its value at this moment would be 'undefined' and not the 'function()'.
'b' would be registered as a function in the global scope.
Inside b's scope, 'f' would be registered as a variable which would be undefined at this moment and function 'd' would be registered.
*When interpreter runs, declared variables and function() (and not expressions) can be accessed before the interpreter reaches the actual expression line. So, variables would be printed 'undefined' and declared anonymous function can be called earlier. However, trying to access undeclared variable before its expression initialisation would result in an error like:
console.log(e)
e = 3;
Now, what happens when you have variable and function declaration with same name.
Answer is - functions are always hoisted before and if the same name variable is declared, it is treated as duplicate and ignored. Remember, order does not matter. Functions are always given precedence. But during evaluation phase you can change the variable reference to anything (It stores whatever was the last assignment) Have a look at the below code:
var a = 1;
console.log("a is " + a);
function b() {
console.log("a inside the function b is " + a); //interpreter finds 'a' as function() in current scope. No need to go outside the scope to find 'a'.
a = 3; //a changed
console.log("Now a is " + a);
return;
function a() {}
}
var a; //treated as duplicate and ignored.
b();
console.log("a is still " + a + " in global scope"); //This is global scope a.
A: Hoisting In JavaScript means, variable declarations are executed through out the program before any code is executed. Therefore declaring a variable anywhere in the code is equivalent to declaring it at the beginning.
A: Its all depends on the scope of variable 'a'. Let me explain by creating scopes as images.
Here JavaScript will create 3 scopes.
i) Global scope.
ii) Function b() scope.
iii) Function a() scope.
Its clear when you call 'alert' method scope belongs to Global that time, so it will pick value of variable 'a' from Global scope only that is 1.
A: Hoisting is behavioural concept of JavaScript. Hoisting (say moving) is concept that explains how and where variables should be declared.
In JavaScript, a variable can be declared after it has been used because Function declarations and variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
We encounter two types of hoisting in most cases.
1.Variable declaration hoisting
Lets understand this by this piece of code.
a = 5; // Assign 5 to a
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = a; // Display a in the element
var a; // Declare a
//output-> 5
Here declaration of variable a will be hosted to top invisibly by the javascript interpreter at the time of compilation. So we were able to get value of a. But this approach of declaration of variables is not recommended as we should declare variables to top already like this.
var a = 5; // Assign and declare 5 to a
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = a; // Display a in the element
// output -> 5
consider another example.
function foo() {
console.log(x)
var x = 1;
}
is actually interpreted like this:
function foo() {
var x;
console.log(x)
x = 1;
}
In this case x will be undefined
It does not matter if the code has executed which contains the declaration of variable. Consider this example.
function foo() {
if (false) {
var a = 1;
}
return;
var b = 1;
}
This function turns out to be like this.
function foo() {
var a, b;
if (false) {
a = 1;
}
return;
b = 1;
}
In variable declaration only variable definition hoists, not the assignment.
*Function declaration hoisting
Unlike the variable hoisting the function body or assigned value will also be hoisted. Consider this code
function demo() {
foo(); // this will give error because it is variable hoisting
bar(); // "this will run!" as it is function hoisting
var foo = function () {
alert("this would not run!!");
}
function bar() {
alert("this will run!!");
}
}
demo();
Now as we understood both variable and function hoisting, let's understand this code now.
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
This code will turn out to be like this.
var a = 1; //defines "a" in global scope
function b() {
var a = function () {}; //defines "a" in local scope
a = 10; //overwrites local variable "a"
return;
}
b();
alert(a);
The function a() will have local scope inside b(). a() will be moved to top while interpreting the code with its definition (only in case of function hoisting) so a now will have local scope and therefore will not affect the global scope of a while having its own scope inside function b().
A: From my piece of knowledge, hoisting happens with the variable declaration and function declaration, for example:
a = 7;
var a;
console.log(a)
What happens inside JavaScript's engine:
var a;
a = 7;
console.log(a);
// 7
Or:
console.log(square(7)); // Output: 49
function square(n) { return n * n; }
It will become:
function square(n) { return n * n; }
console.log(square(7)); // 49
But assignments such as variable assigment, function expression assignment will not be hoisted:
For example:
console.log(x);
var x = 7; // undefined
It may become like this:
var x;
console.log(x); // undefined
x = 7;
A: To describe hosting in javascript in one sentence is variables and functions are hoisted to the top of the scope that they are declared in.
I am assuming you are a beginner, to understand hoisting properly at first we have understood the difference between undefined and ReferenceError
var v;
console.log(v);
console.log(abc);
/*
The output of the above codes are:
undefined
ReferenceError: abc is not defined*/
now in the bellow code what we see? a variable and a function expression is decleard.
<script>
var totalAmo = 8;
var getSum = function(a, b){
return a+b;
}
</script>
but the real picture with proof that the both variable and function are hoisted on the top of there scope:
console.log(totalAmo);
console.log(getSum(8,9));
var totalAmo = 8;
var getSum = function(a, b){
return a+b;
}
console.log(totalAmo);
console.log(getSum(9,7));
Output of first two logs are undefined and TypeError: getSum is not a function because both var totalAmo and getSum are hoisted on the top of their scope like bellow
<script>
var totalAmo;
var getSum;
console.log(totalAmo);
console.log(getSum(8,9));
var totalAmo = 8;
var getSum = function(a, b){
return a+b;
}
console.log(totalAmo);
console.log(getSum(9,7));
</script>
But for functions declaration whole functions hoisted on the top of their scope.
console.log(getId());
function getId(){
return 739373;
}
/* output: 739373, because the whole function hoisted on the top of the scope.*/
Now the same logic goes for those varibale, functions experessions and function declaratoins declared inside functional scope. Key point: they will not be hoisted on the top of the file;
function functionScope(){
var totalAmo;
var getSum;
console.log(totalAmo);
console.log(getSum(8,9));
var totalAmo = 8;
var getSum = function(a, b){
return a+b;
}
}
So, when you use var keyword, variable and function hoisted on the top of there scope (global scope and function scope).
What about let and const, const and let are still both aware of the global scope and function scope just like var is, but const and let variables are also aware of another scope called blocked scope. a block scope is present whenever there is a block of code, such as for loop, if else statement, while loop etc.
When we use const and let to declare a variable in these block scope, the variable declaration only will be hoisted on the top of that block that it is in, and it will not be hoisted on the top of the parent function or top of the global scope that it is hoisted.
function getTotal(){
let total=0;
for(var i = 0; i<10; i++){
let valueToAdd = i;
var multiplier = 2;
total += valueToAdd*multiplier;
}
return total;
}
Variables in abobe example will be hoisted like bellow
function getTotal(){
let total;
var multiplier;
total = 0;
for(var i = 0; i<10; i++){
let valueToAdd;
valueToAdd = i;
multiplier = 2;
total += valueToAdd*multiplier;
}
return total;
}
A: ES5: function hoisting & variable hoisting
function hoisting priority is greater than variable hoisting
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2016-06-01
* @modified
*
* @description function-hoisting.js
* @augments
* @example
* @link
*
*/
(function() {
const log = console.log;
var a = 1;
function b() {
a = 10;
log(`local a`, a)
return;
// function hoisting priority is greater than variable hoisting
function a() {}
}
b();
log(`global a`, a);
// local a 10
// global a 1
})();
which is equal to
(function() {
const log = console.log;
// define "a" in global scope
var a = 1;
function b() {
// define "a" in local scope
var a ;
// assign function to a
a = function () {};
// overwrites local variable "a"
a = 10;
log(`local a`, a);
return;
}
b();
// log global variable "a"
log(`global a`, a);
// local a 10
// global a 1
})();
the reason behind of hoisting
var a = 1;
//"a" is global scope
function b() {
var a = function () {};
//"a" is local scope
var x = 12;
//"x" is local scope
a = 10;
//global variable "a" was overwrited by the local variable "a"
console.log("local a =" + a);
return console.log("local x = " + x);
}
b();
// local a =10
// local x = 12
console.log("global a = " + a);
// global a = 1
console.log("can't access local x = \n");
// can't access local x =
console.log(x);
// ReferenceError: x is not defined
/**
* scpope & closure & hoisting (var/function)
*
* 1. scpope : the global var can be access in any place(the whole file scope), local var only can be accessed by the local scope(function/block scope)!
* Note: if a local variable not using var keywords in a function, it will become a global variable!
*
* 2. closure : a function inner the other function, which can access local scope(parent function) & global scope, howerver it's vars can't be accessed by others! unless, your return it as return value!
*
* 3. hoisting : move all declare/undeclare vars/function to the scope top, than assign the value or null!
* Note: it just move the declare, not move the value!
*
*/
ES6 let, const no exist hoisting
(() => {
const log = console.log;
log(a)
// Error: Uncaught ReferenceError: Cannot access 'a' before initialization
let a = 1;
})();
(() => {
const log = console.log;
log(b)
// Error: Uncaught ReferenceError: Cannot access 'b' before initialization
const b = 1;
})();
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "103"
} |
Q: Date Calculation with Javascript I am having problem to calculating the date in js. I have calendar picker in my form to pick a start date in the format of mm/dd/yy. With that start date value, I want to insert the incremental date into the rows up to 2 wks.
Plz, can anyone help me on this? thank you.
Danny
A: Don't know if this is what you want but.
var date = new Date(year, month, day );
date = date.setDate( date.getDate() + 14 ); // add 14 days to the date
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gradient mask on UIView I have a UIView and want to have the bottom part of it fade out to 0 opacity.
May this be done to a UIView (CALayer) in order to affect an entire UIView and its content?
A: Yes, you can do that by setting CAGradientLayer as your view's layer mask:
#import <QuartzCore/QuartzCore.h>
...
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.frame = view.bounds;
maskLayer.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor];
maskLayer.startPoint = CGPointMake(0.5, 0);
maskLayer.endPoint = CGPointMake(0.5, 1.0);
view.layer.mask = maskLayer;
P.S. You also need to link QuartzCore.framework to your app to make things work.
A: Using an Image as the mask to prevent Layout issues.
Although Vladimir's answer is correct, the issue is to sync the gradient layer after view changes. For example when you rotate the phone or resizing the view. So instead of a layer, you can use an image for that:
@IBDesignable
class MaskableLabel: UILabel {
var maskImageView = UIImageView()
@IBInspectable
var maskImage: UIImage? {
didSet {
maskImageView.image = maskImage
updateView()
}
}
override func layoutSubviews() {
super.layoutSubviews()
updateView()
}
func updateView() {
if maskImageView.image != nil {
maskImageView.frame = bounds
mask = maskImageView
}
}
}
Then with a simple gradient mask like this, You can see it even right in the storyboard.
Note:
You can use this class and replace UILabel with any other view you like to subclass.
Bones:
You can use any other shaped image as the mask just like that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: PHP SoapClient Constructor extremely slow I'm trying to do some tests on a SOAP API and am experiencing extremely slow execution times. I've done some digging and found that it's the SoapClient constructor that takes forever to execute. I also tried using a proxy for it to see if it's the http query resulting from it, but this query is executed relatively fast.. it's after the query that it lingers for about 30 seconds.
Here's a kcachegrind screenshot for reference:
And here's the WSDL query in Charles Proxy:
This same problem has also been reported a couple of months ago here:
PHP: SoapClient constructor is very slow (takes 3 minutes)
But he did not get an answer.
Any suggestions would be much appreciated.
Edit:
The code portion where the SoapClient is initiated (this is part of the NetSuite PHP toolkit)
$this->client = new SoapClient( $host . "/wsdl/v" . $endpoint . "_0/netsuite.wsdl",
array( "location" => $host . "/services/NetSuitePort_" . $endpoint,
"trace" => 1,
"connection_timeout" => 5,
"typemap" => $typemap,
"user_agent" => "PHP-SOAP/" . phpversion() . " + NetSuite PHP Toolkit " . $version
)
);
A: Are you using multiple users? I was getting 3-20 minute lags on the same line of code which turned out to be related to multiple users causing multiple copies of the wsdl to be fetched.
http://www.ozonesolutions.com/programming/2011/05/nsclient-login-time/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: App Engine problems using the command line I am developing an App Engine project on Windows using Eclipse and Python 2.5 and Django 0.96. Everything in my app, including Django, is working nicely.
My problems arise when I try to use command line. For example, I'm told that if I want to clear the local datastore I can enter "python manage.py reset" but when I do so the response is "python: can't open file 'manage.py'".
I feel as if I have missed a configuration step. I have checked my system variables and "Path" includes "C:\Python25" (which I had added manually) but nothing Django or App Engine related. My .py extension is associated with C:\Python25\python.exe.
In my quest to solve this, and in trying to understand what manage.py is, I see that I might have had to create a Django project using "django-admin.py startproject [myproject]" but because everything works nicely from Eclipse I'm not sure if this is necessary now. In any case, if I try to enter this from the command line I get "'django-admin.py' is not recognized..."
Please, what am I missing?
A: If you're using Django 0.96 templates within a 'normal' App Engine app, then manage.py isn't involved at all.
/path/to/dev_appserver.py --clear_datastore .
is what you want, assuming you're CD'd to the root of your app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Qmake and passing $ORIGIN to linker option -rpath I would like to use the -rpath linker option to set the .so search path. I'd like it to search [app_path]/../lib. I've tried add this to my qmake .pro file:
QMAKE_LFLAGS += -Wl,-rpath=$ORIGIN/../lib/
But qmake links my project this way:
g++ -Wl,-rpath=RIGIN/../lib/ -Wl,-O1 -o myoutput main.o [...]
How can I escape the $ORIGIN?
A: This is a really old question, but for people getting here through a search: the methods described in the old answers are not needed anymore. Modern Qt versions (5.9 in my case), allow you to just use this:
QMAKE_RPATHDIR += lib
This will add the needed entries (including $ORIGIN and -Wl,-z,origin where needed) automatically to the makefile, as long as you're using a relative directory. Meaning that lib will produce the needed "origin" entries, while something like /lib will not. Any relative directory you add to QMAKE_RPATHDIR will be made relative to $ORIGIN automatically.
A: I found here a way to properly escape it:
QMAKE_LFLAGS += '-Wl,-rpath,\'\$$ORIGIN/../mylibs\''
A: If you want $ORIGIN to be (properly) evaluated while building you can simply add this to your .pro file:
QMAKE_RPATHDIR += $ORIGIN/../mylibs
A: DOLLAR=$
QMAKE_LFLAGS += -Wl,-rpath=$${DOLLAR}$${DOLLAR}ORIGIN/../myLibs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Webview database corruption on Android I'm developing an Android app which uses a webview to display a webpage. Most of my code is related to the webview. My main activity contains a webview which displays an specific web site.
I'm trying to prevent an error when my webview.db is corrupted. I know that is not a common situation but I would like to make sure that my app will not crash.
Attempting to access the webview database when it has been
corrupted will result in a crash.
I added the method setUncaughtExceptionHandler to handle the exception. I can catch the exeption but when I tried to restart my app the webview never finishes loading.
I tried the follow code to "restart" my app:
Intent i = new Intent(context, Error.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
My last try was unsuccessfully then I added some code which displays an error message, removes the webview databases and closes the app.
AlertDialog alertDialog = new AlertDialog.Builder(
DiscoverMobile.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Application files have been deleted or corrupted. The app will close to fix this issue. You can restart the app later");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
webview.getContext().deleteDatabase(
"webview.db");
webview.getContext().deleteDatabase(
"webviewCache.db");
WebViewDatabase webViewDB = WebViewDatabase
.getInstance(getBaseContext());
System.exit(0);
}
});
alertDialog.show();
Could this be a good solution?
A: Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.clearCache(true);
}
Maybe you tried this, but maybe also set the WebView Cache size to something small. I'm not sure if 0 will work, so maybe 1:
webview.getSettings().setAppCacheMaxSize(1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding a WIF STS service to existing projects We have several websites that are set up in the following fashion:
Site1.Web - ASP.NET Web Project (.NET 4.0, WebForms)
Common.Core - Class Library Project (all db interaction)
The web project appears once for each site while the Common.Core project is shared among all sites. We have a login form in the web project that, in order to authenticate, calls into the class library. It would call off a code similar to below:
Common.Core.Authenticate auth = new Common.Core.Authenticate(conStr);
bool validLogin = auth.ValidateUser(userName, password);
if(validLogin)
{
Common.Core.User = auth.GetCurrentUser();
}
The higher ups are pushing for a middle layer service/app tier and want to use a more elegant solution to handle single sign on. Therefore, the decision has been made to use a WIF service to handle the login and validation. Furthermore, we want to try to minimize the code that has to change in each web project, i.e. try to keep as many changes as possible in Common.Core.
I have seen a few samples that show how to add an STS reference to a web project. This would work well in a scenario where the user validation isn't factored into another project like Core.Common. However, in our scenario, how could we handle validation while still going through the common class library?
Ideally, I would like to add an STS reference to the Core.Common class library and replace the direct db logic (auth.ValidateUser above) with a call to an STS service. However, is it even possible to do that? Does the request have to initiate in the web project? If so, is the STS reference required in both places?
Any tutorials or resources which follow the same web project -> class library -> STS service path would be greatly appreciated.
A: One way to achieve this is to FedUtil the ASP.NET project with an instance of ADFS. Essentially, authentication is now "outsourced" and you can simply remove the call to the core library from your app. ADFS is then setup to return whatever attributes the program needs for authorisation as claims. You may need to transform these claims attributes to whatever attributes are passed back to the common core in subsequent calls.
Or you could make the common core "claims aware" in the sense that it now recognizes "claims attributes" as opposed to "common core" attributes. This involves using different .NET classes - no hookup to ADFS is required.
Word of warning - your authentication seems to be all DB related. ADFS cannot authenticate against a DB. It can only authenticate against an instance of AD in the domain that ADFS is installed in (or other AD if trust relationship between AD).
If you want to authenticate against a DB you need a custom STS which is then federated with ADFS. See here: Identity Server.
A: I would also recommend using WIF :-)
In a claims based scenario the authentication process is "reversed". Your app will not call anyone, it will receive the needed information from a trusted source (the STS).
The "STS Reference" is not a library reference. It's a logical connection between your app and the trusted source of security tokens. A token is the artifact your app will use to decide what to do with the user request.
I'd agree with @nzpcmad that it is likely you could entirely remove the calls to you Common.Core library. It might be useful to see what else can you do with it. What does the Common.Core.User object give you?
If it is just properties of a user (e.g. name, e-mail, roles, etc) it is very likely you could just create a new version that simply wraps the IPrincipal supplied byt WIF (a ClaimsPrincipal).
For example (approx. no error handling, pseudo-code):
public User CurrentUser()
{
var user = new User();
var cu = HttpContext.Current.User as IClaimsPrincipal;
user.Name = cu.Name;
user.eMail = (cu.Identity as IClaimsIdentity).Claims.First( c=> c.ClaimType = "eMail" ).Value;
return user;
}
As @nzpcmad says, you can use ADFS or some other STS. Your apps would not care.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Hover effect doesn't finish animation when using Fancybox I'm having problems with a hover animation when I use Fancybox.
When I click on the image and the Fancybox pops up the animation doesn't finish.
$(".portfolio_item > a").fancybox();
$(".portfolio_item > a img").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});
It's like the animation freezes.
Here is the fiddle.
As you can see, if you click on the image, the Fancybox works but the image doesn't finish the animation.
How can I solve it?
A: If I understand your question correctly, the problem occurs because when fancybox is trigger, the browser couldn't detect the "onmouseout" event and hence the image doesn't get fade back into opacity 1.
An easy fix would be to manually trigger the opacity reset when fancybox is triggered:
// Abstract out the reset function
var resetOpacity = function() {
$(".portfolio_item a img").stop().animate({"opacity": "1"});
}
// Apply the reset on complete
$(".portfolio_item > a").fancybox({'onComplete': resetOpacity});
// Reuse the same reset function on hover out
$(".portfolio_item > a img").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
resetOpacity
);
You can try it out here: http://jsfiddle.net/6aDP5/2/
And here is the code to the final behavior you were looking for:
http://jsfiddle.net/6aDP5/9/
$(".portfolio_item > a").each(function() {
var thisAnchor = $(this);
var targetImg = $(this).find("img");
var fadeOpacity = function() {
targetImg.stop().animate({"opacity": "0"});
}
var resetOpacity = function() {
targetImg.stop().animate({"opacity": "1"});
}
thisAnchor
.mouseenter(fadeOpacity)
.mouseleave(resetOpacity)
.fancybox({
'onStart': function() {
thisAnchor.unbind('mouseleave');
fadeOpacity();
},
'onClosed': function() {
thisAnchor.mouseleave(resetOpacity);
resetOpacity();
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: trying to set numberOfRowsInSection with NSDictionary values I am trying to set up my uitableview for indexing, I have got number of sections working fine, now and the data is in the NSDictionary heres my output with nslog --->
Dictionary: {
H = (
Honda,
Honda,
Honda,
Honda,
Honda,
Honda,
Honda
);
M = (
Mazda,
Mazda,
Mitsubishi,
Mitsubishi,
Mitsubishi,
Mitsubishi,
Mitsubishi,
Mitsubishi
);
N = (
Nissan,
Nissan,
Nissan,
Nissan,
Nissan,
Nissan,
Nissan
);
T = (
Toyota,
Toyota,
Toyota
);
I am now trying to set up my table like so
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [arraysByLetter count];
//return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[arraysByLetter objectAtIndex:section] count];
//return 1;
}
however I am getting a warning 'NSMutableDictionary' may not respond to 'objectAtIndex:' inside my numberOfRowsInSection delegate method... How do I get around this?
A: You cannot index a dictionary as you would an array. You access dictionaries using keys. NSDictionary does provide two methods for getting arrays: allKeys and allValues.
I'm not sure what you are trying to accomplish, but if you want to organize the car makers alphabetically, you can get all the keys ([arraysByLetter allKeys]), sort them alphabetically, and then index into that sorted array. When you actually get the car makers' names you will then use objectForKey: to load the array of makers.
Update:
Assuming a sorted array named sortedLetters, you can change your numberOfRowsInSection to the following:
NSString *currentLetter = [sortedLetters objectAtIndex:section];
return [[arraysByLetter objectForKey:currentLetter] count];
You probably want to setup the sortedLetters array on initialization, unless it is dynamic.
A: The warning message is telling you exactly what the problem is: arraysByLetter is an instance of NSMutableDictionary not NSArray (or its subclass, NSMutableArray), and therefore doesn't respond to NSArray methods such as objectAtIndex:.
Instead, you should be using the NSDictionary method objectForKey:, and passing the letter of the alphabet that corresponds to the provided section number. You could use a switch statement or an array of strings to figure out which key to pick.
A: objectAtIndex is an array method, not a dictionary method. The way I use dictionaries for table data sources is as so:
- (NSInteger)tableView:numberOfRowsInSection:
{
NSArray *keys = [arraysByLetter allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(caseInsensitiveComapre:)];
return [[arraysByLetter objectForKey:[sortedKeys objectAtIndex:section]] count];
}
The reason we have to sort is because allKeys appears in no particular order and can change.
A: That is because you cannot use objectAtIndex on a dictionary. You need to first extract the objects on your dictionary using objectForKey on your dictionary and then create an array from those objects. Then you may use objectAtIndex on that array (array of array objects) and use count on the result. Or a simple allValues message to your dictionary would also suffice.
EDIT:
In your case if you need your first section to have seven rows (seven Hondas), create an array and place [dictionary allValues] as its content. Use that array inside your numberOfRowsInSection method like you do now with your dictionary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how reading nutch generated content data on the segment folder using java I am trying to read the content data inside the segment folder. I think the content data file is written in a custom format
I experimented with nutch's Content class, but it does not recognize the format.
A: import java.io.IOException;
import org.apache.commons.cli.Options;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.NutchConfiguration;
public class ContentReader {
public static void main(String[] args) throws IOException {
// Setup the parser
Configuration conf = NutchConfiguration.create();
Options opts = new Options();
GenericOptionsParser parser = new GenericOptionsParser(conf, opts, args);
String[] remainingArgs = parser.getRemainingArgs();
FileSystem fs = FileSystem.get(conf);
String segment = remainingArgs[0];
Path file = new Path(segment, Content.DIR_NAME + "/part-00000/data");
SequenceFile.Reader reader = new SequenceFile.Reader(fs, file, conf);
Text key = new Text();
Content content = new Content();
// Loop through sequence files
while (reader.next(key, content)) {
try {
System.out.write(content.getContent(), 0,
content.getContent().length);
} catch (Exception e) {
}
}
}
}
A: org.apache.nutch.segment.SegmentReader
has a map reduce implementation that reads content data in the segment directory.
A: spark/scala code to read data from the segments content folder.
How I read from the content folder in my project.
I have created a case class page which holds data read from the content folder
case class Page(var url: String, var title: String = null
,var contentType: String = null, var rawHtml: String = null,var language: String = null
,var metadata: Map[String,String])
Code to read from content folder
import org.apache.commons.lang3.StringUtils
import org.apache.hadoop.io.{Text, Writable}
import org.apache.nutch.crawl.{CrawlDatum, Inlinks}
import org.apache.nutch.parse.ParseText
import org.apache.nutch.protocol.Content
val contentDF = spark.sparkContext.sequenceFile(path.contentLocation, classOf[Text], classOf[Writable])
.map { case (x, y) => (x.toString, extract(y.asInstanceOf[Content])) }
/** converts Content object to Page **/
def extract(content: Content): Page = {
try {
val parsed = Page(content.getUrl)
var charset: String = getCharsetFromContentType(content.getContentType)
if (StringUtils.isBlank(charset)) {
charset = "UTF-8"
}
parsed.rawHtml = Try(new String(content.getContent, charset)).getOrElse(new String(content.getContent, "UTF-8"))
parsed.contentType = Try(content.getMetadata.get("Content-Type")).getOrElse("text/html")
// parsed.isHomePage = Boolean.valueOf(content.getMetadata.get("isHomePage"))
parsed.metadata = content.getMetadata.names().map(name => (name,content.getMetadata.get(name))).toMap
Try {
if (StringUtils.isNotBlank(content.getMetadata.get("Content-Language")))
parsed.language = content.getMetadata.get("Content-Language")
else if (StringUtils.isNotBlank(content.getMetadata.get("language")))
parsed.language = content.getMetadata.get("language")
else parsed.language = content.getMetadata.get("lang")
}
parsed
} catch {
case e: Exception =>
LOG.error("ERROR while extracting data from Content ", e)
null
}
}
/**Get Html ContentType **/
def getCharsetFromContentType(contentType: String): String = {
var result: String = "UTF-8"
Try {
if (StringUtils.isNotBlank(contentType)) {
val m = charsetPattern.matcher(contentType)
result = if (m.find) m.group(1).trim.toUpperCase else "UTF-8"
}
}
result
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Drupal Views argument - Provide default argument: PHP code I would like to pass an argument of 'home' to the View (which is a block) as the default argument when the current page is the front page. The 'else if' portion of the code works fine. Thanks.
This code goes in the "PHP Argument Code" text field when you select "provide default argument" in Views.
$path = explode('/', drupal_get_path_alias($_GET['q']));
if ($is_front) {
return 'home';
} else if (arg(0) = 'node' && arg(1) != 'add' && arg(2) != 'edit' && arg(2) != 'delete' && $path[0] != '') {
return $path[0];
}
A: Try:
$is_front = $_GET['q'] == '<front>' || $_GET['q'] == variable_get('site_frontpage', '<front>');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I configure TortoiseHg to open a file in the right program based on its extension? I'm using TortoiseHg v2.2.1 with Mercurial 1.9 in WindowsXP. How do I configure TortoiseHg to view a file based on the application Windows has associated with its extension?
For example, if I have a .docx file in the repository and I'm looking at its revision history, I'd like View at revision... to open the selected revision in MS Word. Likewise for other binary file types like ppt and xls, which I can't view using the default text editor or kdiff3.
Can I leverage that Windows already knows what program to use to open certain types of files or will I have to manually configure each file type of interest within the Tortoise config files?
I've found several SVN scripts in the TortoiseHg\diff-scripts folder that look like they solve a similar problem for diffing binaries rather than simply viewing them, but those don't seem to be activated and I'm not sure what if anything I need to mod in the MergePatterns.rc or Mercurial.ini files to make this all work.
A: To make "View at Revision" use whatever program is associated with the file's extension, try this trick: In the "Global Settings" in the "TortoiseHg" section, enter start "" as "Visual Editor". Note the empty "". This is necessary so that start will not use the file name, which gets passed in quotes by TortoiseHg, as the window title.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Improving Asp.NET MVC/Javascript url generation readability I need to generate urls for use in javascript. I don't think my current solution is very readable.
//Navigation during load: Id from MVC or hash or zero.
var m_departmentId = <%= ViewContext.RouteData.Values["id"] ?? 0 %>;
if(0 == m_departmentId)
{
var hash = location.hash;
//Only one hash value
var id = parseInt(hash.substring(2));
//If it's a real Id, use it.
if (!isNaN(id)) {
m_departmentId = id;
}
}
var gridUrl = '<%= Url.Action("GetEmployees", "Company", new { area = "" }) %>/' + m_departmentId;
This script is placed at top of my page javascript where I translate aspnet-variables to js-variables.
Can I get rid of the first javascript?
Can I improve the readability of the last row? Imho it's rather hideous, especially within my page javascript.
Other improvements?
Improvement 1:
var gridUrl = '<%= Url.Content("~/Company/GetEmployees/") }) %>' + m_departmentId;
T4MVC didn't work when the action was the default action for the route, because the action was stripped from the path when no action argument was used.
A: I think you need the JavaScript for the hash. You can't read hashes server-side.
T4MVC may help you with the "ugly" URL generation. It will at least get rid of the magic strings (still can't believe they went that route with the UrlHelper).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Paperclip wont upload image to S3 I am having problems uploading images to Amazon S3. I have installed the paperclip gem and the gem 'aws-s3'. My Amazon S3 server is the europen: http://s3-eu-west-1.amazonaws.com
When I submit my form the form is rendered again because the photographer is not saved. And I can see that nothing is uploaded to the cloud. And I get the message "Image ok" in view.
My controller:
def savenew
@photographer = Photographer.create(params[:photographers])
@photographer.sort_order = Photographer.count + 1
if @photographer.save
redirect_to :action => 'list', :id => params[:id]
else
render 'create', :id => params[:id]
end
end
My model:
attr_accessor :flv_file_size, :flv_updated_at, :flv_content_type, :image_file_size, :image_updated_at, :image_content_type,
:quicktime_file_size, :quicktime_updated_at, :quicktime_content_type
has_attached_file :image,
:storage => :s3,
:bucket => 'mybucket',
:path => "/photographer/image/:id/:filename",
:s3_credentials => {
:access_key_id => 'mykey',
:secret_access_key => 'mykey'
}
has_attached_file :flv,
:storage => :s3,
:bucket => 'mybucket',
:path => "/photographer/flv/:id/:filename",
:s3_credentials => {
:access_key_id => 'mykey',
:secret_access_key => 'mykey'
}
has_attached_file :quicktime,
:storage => :s3,
:bucket => 'mybucket',
:path => "/photographer/quicktime/:id/:filename",
:s3_credentials => {
:access_key_id => 'mykey',
:secret_access_key => 'mykey'
}
My create page:
<h2>Movie</h2>
<h3>Create new movie</h3>
<%= link_to 'back to movie list', {:action => 'list', :id => params[:id]}, {:class => "margin-left"} %>
<div class="spacer"> </div>
<%#= start_form_tag(:action => "savenew", :id => params[:id]) %>
<%= form_tag( {:action => "savenew", :id => params[:id] }, :multipart => true ) do |f|%>
<%= render(:partial => "linkform", :object => @photographer) %>
<p>
<label for="submit"> </label>
<%= submit_tag("create new") %>
</p>
<% end %>
My linkform:
<%= javascript_include_tag "tiny_mce/tiny_mce" %>
<%= javascript_include_tag "init_my_tiny_mce" %>
<p>
<label for="hyperlink:">name</label>
<%= text_field("photographer", "name") %>
</p>
<p>
<label for="hyperlink:">text </label>
<%= text_area("photographer", "text", :rows => 12) %>
</p>
<p>
<label for="hyperlink:">Upload/update image</label>
<%= file_field("photographer", "image") %>
</p>
<% if @photographer %>
<% if @photographer.image %>
<p class="ok">
<label for="dd">image ok</label>
<%= image_tag("/photographer/image/#{@photographer.id}/#{@photographer["image"]}", :size => "39x22" ) %>
</p>
<p>
<label for="sdd"> </label>
<%= link_to("remove", {:action => "remove_image", :id => @photographer.id }, {:confirm => "Are your sure?"}) %>
</p>
<% else %>
<p class="current">
<label for="dd"></label>
No image uploaded for movie
</p>
<% end %>
<br />
<% end %>
<br />
<p>
<label for="hyperlink:">Upload/update flv</label>
<%= file_field("photographer", "flv") %>
</p>
<br />
<% if @photographer %>
<% if @photographer.flv %>
<p class="ok">
<label for="dd">flv: <%= @photographer["flv"]%></label>
<%= link_to("remove", {:action => "remove_flv", :id => @photographer.id }, {:confirm => "Are your sure?"}) %>
</p>
<% else %>
<p class="current">
No flv uploaded
<br /><br />
</p>
<% end %>
<% end %>
<br />
<p>
<label for="hyperlink:">Upload/update quicktime</label>
<%= file_field("photographer", "quicktime") %>
</p>
<br />
<% if @photographer %>
<% if @photographer.quicktime %>
<p class="ok">
<label for="dd">quicktime: <%= @photographer["quicktime"]%></label>
<%= link_to("remove", {:action => "remove_quicktime", :id => @photographer.id }, {:confirm => "Are your sure?"}) %>
</p>
<% else %>
<p class="current">
<label for="dd"></label>
No quicktime uploaded
<br />
</p>
<% end %>
<% end %>
<%= error_messages_for("photographer")%>
My Rails console log:
Started POST "/admin/photographers/savenew" for 127.0.0.1 at 2011-09-21 23:32:40
+0200
Processing by Admin::PhotographersController#savenew as HTML
Parameters: {"utf8"=>"Ô£ô", "authenticity_token"=>"LDd/jde1bzb7NqaNfzDKHjMc4j4
PHdjflgSYVGL3z+k=", "photographer"=>{"name"=>"sadasdasd", "text"=>"asd", "image"
=>#<ActionDispatch::Http::UploadedFile:0x59ad680 @original_filename="IT_T_rgb.jp
g", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\
"photographer[image]\"; filename=\"IT_T_rgb.jpg\"\r\nContent-Type: image/jpeg\r\
n", @tempfile=#<File:C:/Users/Iceberg/AppData/Local/Temp/RackMultipart20110921-6
200-o7ckpi>>}, "commit"=>"create new"}
←[1m←[36mSQL (0.0ms)←[0m ←[1mBEGIN←[0m
←[1m←[35mSQL (1.0ms)←[0m ROLLBACK
←[1m←[36mSQL (1.0ms)←[0m ←[1mSELECT COUNT(*) FROM `photographers`←[0m
←[1m←[35mSQL (0.0ms)←[0m BEGIN
←[1m←[36mSQL (0.0ms)←[0m ←[1mROLLBACK←[0m
Rendered admin/photographers/_linkform.rhtml (5.0ms)
←[1m←[35mTextpage Load (1.0ms)←[0m SELECT `textpages`.* FROM `textpages` ORDE
R BY name ASC
Rendered admin/photographers/create.rhtml within layouts/admin (105.0ms)
Completed 200 OK in 190ms (Views: 119.0ms | ActiveRecord: 3.0ms)
A: The AWS-S3 gem works fine with European S3 buckets.
If you add this to the enviroment.rb:
AWS::S3::DEFAULT_HOST.replace "s3-eu-west-1.amazonaws.com"
A: AWS-S3 doesn't work with European S3 buckets - you need to use a US bucket as the structures are different.
Carrierewave/Fog work fine with European buckets though.
A: If you are using a newer version of paperclip you need to be using the aws-sdk gem not the aws-s3 gem. I had the same issue.
https://github.com/thoughtbot/paperclip#storage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove "NSObject may not respond to selector" warning when using a formal protocol? I'm trying to write a custom, formal protocol and I am having issues with Xcode's warnings. Specifically:
if([self.delegate conformsToProtocol:@protocol(myProtocol)]){
[self.delegate myProtocolMethod];
}
This works totally fine at runtime, but Xcode keeps giving me the "NSObject may not respond to -myProtocolMethod" warning. I'd really like to remove the warning, so am I doing something wrong here?
A: The compiler doesn't care if you just checked for the protocol. It only cares about the data type of the object you are calling the method on. The easiest thing to do is simply cast the result of self.delegate to a type which declares the protocol.
if([self.delegate conformsToProtocol:@protocol(myProtocol)]) {
[(NSObject * <myProtocol>)self.delegate myProtocolMethod];
}
Or, if the delegate property is supposed to always implement this protocol, you can change the property declaration to include it. This is even better because the compiler will warn you if you try to assign an object which doesn't implement the protocol as the delegate.
@property (modifiers) NSObject * <myProtocol> delegate;
A: You're seeing the warning because the type of self.delegate, whatever it happens to be, does not declare that method.
Cast self.delegate to the correct class or protocol to remove the warning. E.g.:
[(id<myProtocol>)self.delegate myProtocolMethod];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: List by date is it
* or
*? I have a list of newsletters like this:
*
*Newsletter Jan
*Newsletter Feb
*Newsletter Mar
*Newsletter May
I logically order them by date but the numeration does not really mean anything. So my question is what is semantically correct? to use <ol> or ul?
Thanks.
A: If they are listed in order, then <OL>. Although I don't think it is a huge deal either way.
A: From a UI perspective, there's no need to have a number and a date, it's just confusing. If you're going to be super anal about definitions though, I guess an appropriately styled ol would be better. But don't do that.
A: From a strictly semantic sense, any list of items that has an ordering to it (dates included) should be marked up as an <ol>, since the <ol> tag indicates it's contents are an ordered list.
That being said, I agree with @Dave that the numeric list indicators are unlikely to be needed (depending on the rest your design, of course), and could be hidden with CSS. Depending on the browsers you are targeting, adjusting the margin and/or padding will hide them.
The reason it matters is because non-visual browsers, such as screen readers or text-based browsers like Lynx can offer their users additional functionality for an ordered list than an unordered one. For example, it makes much more sense for a user to jump to the 8th item in an ordered list, since they are more likely to know what that item is based on ordering, than it does to jump to the 8th item in an unordered list. (ie. they can do a binary search on an ordered list, but not an unordered one)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: z-index issue of absolute element inside absolute div I need an idea about a z-index issue on IE. Here’s my html markup:
<div style="position:relative">
<div style="position:absolute">
<a style="position:absolute"> close button </a>
</div>
</div>
The anchor (close button) is partially outside of it’s parent (top: -4px; right: -4px;) but it gets cut at the parent’s border. Is there a way to make the anchor look right?
Later edit: http://jsfiddle.net/RTTkU/1/
A: Post whatever you have so far so we can take a look, but in the mean time i made a small demo that you can try out to see if its what you're looking for:
CSS
.box {
position:relative;
width:400px;
height:200px;
background-color:#ddd;
}
.close {
position:absolute;
top:-6px;
right:-6px;
}
.close a {
background: url(http://cdn3.iconfinder.com/data/icons/lynx/22x22/actions/dialog-close.png) no-repeat transparent;
display:inline-block;
height:22px;
width:22px;
text-indent:-9999px;
z-index:9999;
}
HTML
<div class="box">
<div class="close">
<a title="Close" href="#">close</a>
</div>
</div>
Demo
A: The IE specific "filter" property applied to a box acts as "overflow: hidden;" thus cropping every child element which crosses the boundaries of the box.
A: You probably need overflow: visible on the parent(s).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why would running Pex Explorations result in ignoring a previously Pex-generated test method? Code being tested:
public class TestReader
{
public string Content { get; private set; }
public void LoadFile(string fileName)
{
var content = FileSystem.ReadAllText(fileName);
if (!content.StartsWith("test"))
throw new ArgumentException("invalid file");
this.Content = content;
}
}
public static class FileSystem
{
public static string ReadAllText(string fileName)
{
return File.ReadAllText(fileName);
}
}
Pex method in test project:
[PexMethod]
public void CheckValidFileWithPex(string content)
{
// arrange
var fileName = "test.txt";
Moles_Example.Moles.MFileSystem.ReadAllTextString =
delegate(string f)
{
Assert.IsTrue(f == fileName); return content;
};
// act
var test = new TestReader();
test.LoadFile(fileName);
// assert
Assert.AreEqual(content, test.Content);
}
When I first run "Pex Explorations" on CheckValidFileWithPex(string content), five test methods are generated with the following values for content:
*
*null
*""
*"\0\0\0\0"
*"test"
*"\0\0\0\0\0"
However, if I run "Pex Explorations" again, no changes made to the generated tests, existing test project code, or main project prior to second execution, then only 4 tests are listed as generated and the test input from item 3 ("\0\0\0\0") is missing.
The source code of the Pex-generated test file still has a test method for this case, but I do not understand why this case is not listed in Pex Exploration Results.
Thank you for your insight.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Air for iOS: included files directory path Due to decisions out of my control I've created a iPad app by way of a CS5.5 Flash build and using the 'Air for iOS' publish.
In the 'Air for iOS' settings I've included a file.
The issue I'm having is in trying to call the file and not knowing what the path is.
I'm hoping this is a case where files added in this manner are placed in a consistent location.
Is that the case? And if so, what would the path be?
Thanks in advance for any responses.
A: All application files are placed in the "application" directory. You can access files in this directory using the app: URI scheme, as in: app://file.ext or app://assets/picture.jpg, etc.
You can also use File.applicationDirectory to get a file reference:
var file:File = File.applicationDirectory.resolvePath("file.ext");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: FTP framework to use in Java code I need to do some FTP'ing in Java, is there a best FTP framework to use?
I see apache has something, any opinions?
I just need to do some simple "sftp" puts and gets.
A: I'm unaware of a free Java solution that offers both ftp and sftp client support.
For sftp I have good experiences with the free and popular JSch library. One downside, the documentation is minimal, but there are a number of blogs that offer code to get you started.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ViewState on control inside page header I'm adding my js files to header on code-behind like this:
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
HtmlGenericControl js = new HtmlGenericControl("script");
js.Attributes["type"] = "text/javascript";
js.Attributes["src"] = "/js/jquery.js";
js.ID = "jquery";
js.EnableViewState = true;
Page.Header.Controls.Add(js);
}
}
this works pretty well on page load, but I lose my js on postbacks, I was expecting my control persist with HtmlGenericControl's ViewState enabled...
any way to persist ViewState on header or do I have to remove if (!IsPostBack) condition to add js every time?
A: your control is added dynamically and only when !IsPostBack, ViewState can keep values and status but the control has to exists by its own on the page.
In your case after a post back the control will not be added so even if the ViewState contained its status, there is no control to attach this status to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to rectify Routing error for rails 3 project I am doing a simple file upload using Rails 3, followed all the steps as given in the following link http://www.tutorialspoint.com/ruby-on-rails-2.1/rails-file-uploading.htm
getting following error in browser:
Routing Error
No route matches {:action=>"app/controllers/Upload/uploadFile", :controller=>"upload"}
I am getting following error in windows command prompt (for ruby and rails)
ActionView::Template::Error (No route matches {:action=>"app/controllers/Upload/uploadFile", :controller=>"upload"}):
1: <h1>File Upload</h1>
2: <% form_tag({:action => 'app/controllers/Upload/uploadFile'},
3: :multipart => true) do %>
4: <p><label for="upload_file">Select File</label> :
5: <%= file_field 'upload', 'datafile' %></p>
app/views/upload/uploadfile.html.erb:2:in `_app_views_upload_uploadfile_html_erb___217229071_35578596'
app/controllers/upload_controller.rb:3:in `index'
Rendered C:/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (1.0ms)
A: You just want
<% form_tag({:action => 'uploadFile'} ... %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript iFrame Drop Down Hover Over Is there a way in Javascript (no jquery) to make a hover menu that is inside a iFrame. So it would extend beyond the iframe area?
A: No, you simply cannot position content inside an iframe outside of its boundaries
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can the pudb debugger be used on windows? Is it possible to us the pudb python debugger on Windows? If yes, how do you get it installed and working?
When I try and install it using ez_setup, python ez_setup.py .\path\to\pudb-unpacked, it fails with ImportError: No module named termios, a module which appears to be for unix only.
I'm using Windows 7, x64.
A: I've got pudb running under Cygwin on windows. I installed it with pip
A: It appears the answer is No, pudb can't be used in Windows at present.
The underlying problem is that pudb relies on urwid, which expects a unix-like environment. There is a message in 2006 indicating 3 methods of using urwid on windows, namely: cygwin, cursesw, and pdcurses. So it there is an avenue of exploration for an adventurer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How do I split sentences? So, I found and am currently using Stanford Parser and it works GREAT for splitting sentences. Most of our sentences are from AP so it works very well for that task.
Here's the problems:
*
*it eats a LOT of memory (600M a lot)
*it really screws up the formatting of a body of text where I have to make a lot of edge cases for later on. (the document pre-processor API calls don't allow to specify ascii/utf8 quotes -- they immediately goto latex style, contractions get split into different words (obviously) and spurious spaces are put into different places)
To this end, I've already written multiple patches to compensate for what I really shouldn't be having to do.
Basically it's at the point where it is just as much of a hindrance to use as the problem of splitting sentences to begin with.
What are my other options? Any other NLP type of frameworks out there that might help out?
My original problem is just being able to detection sentence edges with a high degree of probability.
A: If you want to try sticking with the Stanford Tokenizer/Parser, look at the documentation page for the tokenizer.
If you just want to split sentences, you don't need to invoke the parser proper, and so you should be able to get away with a tiny amount of memory - a megabyte or two - by directly using DocumentPreprocessor.
While there is only limited customization of the tokenizer available, you can change the processing of quotes. You might want to try one of:
unicodeQuotes=false,latexQuotes=false,asciiQuotes=false
unicodeQuotes=true
The first will mean no quote mapping of any kind, the second would change single or doubled ascii quotes (if any) into left and right quotes according to the best of its ability.
And while the tokenizer splits words in various ways to match Penn Treebank conventions, you should be able to construct precisely the original text from the tokens returned (see the various other fields in the CoreLabel). Otherwise it's a bug.
A: There are lots of sentence splitters available, performance will depend on your specific application.
It's very easy to get started with Perl and Python versions. The Stanford Parser version I've found troublesome in the past; I ended up using a domain specific splitter (Genia). I also ran a regex based cleanup tool to look for badly split sentences and re-assemble them.
A: You have one way to split sentences from a text using the Stanford NLP and without having any character replaced by weird chars (such as for parentheses or apostrophes):
PTBTokenizer ptbt = new PTBTokenizer(
new StringReader(text), new CoreLabelTokenFactory(), "ptb3Escaping=false");
List<List<CoreLabel>> sents = (new WordToSentenceProcessor()).process(ptbt.tokenize());
Vector<String> sentences = new Vector<String>();
for (List<CoreLabel> sent : sents) {
StringBuilder sb = new StringBuilder("");
for (CoreLabel w : sent) sb.append(w + " ");
sentences.add(sb.toString());
}
}
The standard way of using DocumentPreprocessor will screw your original text.
A: You can use NLTK (especially, the nltk.tokenize package):
import nltk
sentence_detector = nltk.data.load('tokenizers/punkt/english.pickle')
text = "This is a test. Let's try this sentence boundary detector."
text_output = sentence_detector.tokenize(text)
print('text_output: {0}'.format(text_output))
Output:
text_output: ['This is a test.', "Let's try this sentence boundary detector."]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: EJB3 Unit Testing with embeddable container Testing EJB3 using glassfish embeddable container, but this call seems to return null all the time, any ideas?
//from JUnit
EJBContainer ejc = javax.ejb.embeddable.EJBContainer.createEJBContainer();
A: Got it to work using openejb. Here is how to get it to start openejb container for testing. Within your JUnit code, add the following (Ideally, in setUpClass)
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");
InitialContext context = new InitialContext(props);
MyEJB b = (MyEJB) context.lookup("MyEJBLocalBean");
You can now call business methods on your MyEJB object b.
A: Have a look at Jetty
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Indexoutofbound Exception invalid index size is I am getting error in this line..cant figure why?
private void method() {
for(int i=0;i<list.size();i++){
DbHelper.add(list.get(i),desc.get(i));
}
Thank you....
A: Sounds like desc.size() is less than list.size().
Three options:
*
*Validate this first:
// Using Guava or something similar
Preconditions.checkState(list.size() == desc.size());
*Only go as far as the minimum:
for (int i = 0; i < list.size() && i < desc.size(); i++)
*Combine both list and desc into one list of a composite type. When you have two collections which you iterate over together, quite often that's a sign that you'd be better off with a single collection capturing the combined entity. It depends on the situation, admittedly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Understanding the different clocks of clock_gettime() Hi I wanted to use the clock_gettime() function for measuring the performance of my code.
I am unable to understand the difference between the different kinds of clocks used in the function from the man page descriptions. esp
CLOCK_REALTIME,
CLOCK_PROCESS_CPUTIME_ID
CLOCK_THREAD_CPUTIME_ID
Can someone explaing what each of these clocks do?
A: CLOCK_REALTIME reports the actual wall clock time.
CLOCK_MONOTONIC is for measuring relative real time. It advances at the same rate as the actual flow of time but it's not subject to discontinuities from manual or automatic (NTP) adjustments to the system clock.
CLOCK_PROCESS_CPUTIME_ID is for measuring the amount of CPU time consumed by the process.
CLOCK_THREAD_CPUTIME_ID is for measuring the amount of CPU time consumed by the thread. It's supported by modern kernels and glibc since 2.6.12, but on older linux kernels glibc emulates it badly by simply returning the amount of CPU time consumed by the process since the moment the thread was created.
http://man7.org/linux/man-pages/man2/clock_gettime.2.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: redirect to 'www' before force_ssl I'm moving an app to heroku and am having some issues with ssl and redirects.
I'm on rails 3.1 and I've tried forcing ssl with middleware in the environments production.rb. I've all tried adding it to the application controller.
The problem is, when I do a full site force of ssl, I'm unable to redirect to www before it hits the SSL requirement. This is important because a user would be shown a bad SSL cert warning if they access https://mydomain.com. If they proceed, they then get redirect to 'www'.
SSL forcing is working, redirecting to 'www' subdomain is working, I just need to do the redirect first.
Any ideas?
Per Nathan's Comment:
I had an imperfect solution. My root_path is not forcing ssl. All parts with sensitive info are forcing it. Upon arriving, all traffic is directed to www with this in my routes.rb:
constraints(:host => "domain.com") do
match "(*x)" => redirect { |params, request|
URI.parse(request.url).tap { |x| x.host = "www.domain.com" }.to_s
}
end
This could hide most of the issues, as by the time to user clicked on sign in or anything else, they were now at the www domain. The browser will not giving a warning about certificates. This worked fine for this certain project. Another project I ended up paying the big bucks for a signed wild card cert.
Sorry, not a real solution. If you go to https://domain.com/forcedsslpath the project still gives the security warnings.
A: Since your 301 is being sent by the application, and the request can't even reach the application before hitting the middleware (on which rack-ssl runs), your only solutions are to change the middleware or to do the redirect before it even hits the middleware.
For the latter, you'd have to poke around Heroku. I don't use it myself. On a VPS deployment, you'd just add the redirect on your forward-facing web server (Apache, nginx) before it even hit the middleware. This seems like a common case, so I imagine Heroku might have something there for you.
For the former, it shouldn't be hard. The rack-ssl middleware is very, very simple, and it shouldn't be hard to monkeypatch it to suit your needs.
https://github.com/josh/rack-ssl/blob/master/lib/rack/ssl.rb#L58
I imagine that something like url.host = "www.myhost.com" might be what you'd want (although you can probably tell there are probably more FQDN-agnostic ways to do it).
A: Here is how I solved the problem. I removed config.force_ssl = true from production.rb and instead used:
Add this method to ApplicationController
def force_ssl
if Rails.env.production?
redirect_to :protocol => 'https' unless request.ssl?
end
end
And add it as a before filter on ApplicationController
before_filter :force_ssl
I am also using a ensure_domain which switches from http://example.com to http://www.example.com. Make sure such a before filter is called before force_ssl.
A: You should be able to do this by running a rack redirect before the force_ssl middleware.
This post shows you how to do it.
http://blog.dynamic50.com/2011/02/22/redirect-all-requests-for-www-to-root-domain-with-heroku/
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android - DBAdapter outside Activity throws Exception If I try to instantiate and use my applications DBAdapter outside my Activities, I get an exception thrown. I am trying to use it in a simple utility/helper class I made:
public class MyClass
{
Context context;
DBAdapter db;
public MyClass(Context c)
{
// Get the application context that is passed to the class
context = c;
// Instantiate the database using the application context
db = new DBAdapter(context);
// Open the database and do something
db.open(); // <---- Exception thrown here
db.dosomething();
db.close();
}
}
I call the MyClass like this
public class MainActivity extends Activity
{
@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyClass whatever = new MyClass(this);
}
}
Here is my DBAdapter, very simple and typical of any Android SQLite tutorial:
public class DBAdapter
{
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context c)
{
context = c;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper( Context context)
{
super(context, MY_DATABASE_NAME_HERE, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try
{
db.execSQL(/*CREATE TABLE CODE HERE*/);
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
/* UPDATE CODE HERE */
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public void dosomething()
{
// code here
}
// Other database abstraction layer methods down here...
}
And finally, the exception. It seems to me that the db object is null or invalid or something when I create it. But it seems like I'm doing it right. I'm passing the proper application/activity context.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.whatever.mysqltest/com.whatever.mysqltest.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.whatever.whatever.DBAdapter.open(DBAdapter.java:71)
at com.whatever.whatever.whatever.<init>(whatever.java:56)
at com.whatever.mysqltest.MainActivity.onCreate(MainActivity.java:22)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
Alternatively, if I call the db object from within the Activity, all is well...
public class MainActivity extends Activity
{
DBAdapter db;
@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new DBAdapter(this);
db.open(); // <--- does NOT thrown an exception.
db.dosomething();
db.close();
}
}
What is my problem here?
A: Your 'MyClass' is expecting a context but you're passing it an activity. Try passing the context to the constructor like this:
MyClass whatever = new MyClass(getContext());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Serial Port Port.Write() Command I'm curious as to why when I use the SerialPort.Write() command, the command I'm trying to send doesn't actually ever get sent. (Maybe it just sits in the buffer, or is just saved somewhere, I don't know). I have to use the SerialPort.BaseStream.BeginWrite() command to actually physically send that command. Why is that?
Thanks,
Carter
A: The BeginWrite method on a stream calls the Write method synchronously, which means that Write method might block on some streams. To determine whether the current instance supports writing, use the CanWrite property.
a link!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: "There is no device with id [generic] in wurfl" in Zend implementation of WURFL I've followed the guide in the Zend documentation:
http://framework.zend.com/manual/en/zend.http.user-agent.html
And included all the configs in my application.ini like this:
; Mobile device detection
resources.useragent.storage.adapter = "Session"
resources.useragent.wurflapi.wurfl_api_version = "1.1"
resources.useragent.wurflapi.wurfl_lib_dir = APPLICATION_PATH "/../library/wurfl-php-1.3.1/WURFL/"
resources.useragent.wurflapi.wurfl_config_array.cache.provider = "file"
resources.useragent.wurflapi.wurfl_config_array.cache.dir = APPLICATION_PATH "/../data/wurfl/cache/"
resources.useragent.wurflapi.wurfl_config_array.wurfl.main-file = APPLICATION_PATH "/../data/wurfl/wurfl.xml"
resources.useragent.wurflapi.wurfl_config_array.wurfl.patches = APPLICATION_PATH "/../data/wurfl/web_browsers_patch.xml"
resources.useragent.wurflapi.wurfl_config_array.persistence.provider = "file"
resources.useragent.wurflapi.wurfl_config_array.persistence.dir.dir = APPLICATION_PATH "/../data/wurfl/cache/"
The first time I run my app before the data/wurfl/cache is populated, I get this fatal error:
Cannot send headers; headers already sent in /Applications/MAMP/htdocs/thebirdy.com/library/wurfl-php-1.3.1/WURFL/Xml/VersionIterator.php, line 29
The second time I run my app, and every subsequent time, I get the application error:
There is no device with id [generic] in wurfl
/Applications/MAMP/htdocs/thebirdy.com/library/wurfl-php-1.3.1/WURFL/CustomDeviceRepository.php(70): WURFL_CustomDeviceRepository->getDevice('generic')
A: Your wurfl setting in application.ini does not need to include that many settings. Just having the following is enough:
resources.useragent.wurflapi.wurfl_api_version = "1.1"
resources.useragent.wurflapi.wurfl_lib_dir = APPLICATION_PATH "/../library/wurfl-php-1.1/WURFL/"
resources.useragent.wurflapi.wurfl_config_file = APPLICATION_PATH "/configs/wurfl-config.php"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a method to check whether the current Map is in Map or Satellite mode? I am setting the Map to Satellite view on click of a toggle button
mapToggle.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (mapToggle.isChecked())
{
mapV.setSatellite(true);
} else {
mapV.setSatellite(false);
}
}});
I want to programitically determine which mode it is in when the app restarts. Please advice.
A: The way I accomplished this is to set an int value in your SharedPreferences. Then onClick of that button, get the value and switch satellite on or off accordingly.
private static final int OVERLAY_STREET = 0;
private static final int OVERLAY_SAT = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
int currentOverlayMode = prefs.getInt("map_viewmode", 0);
mOverlayModeBtn = (Button)findViewById(R.id.googlemaps_overlay_btn);
mOverlayModeBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentOverlayMode < 1)
currentOverlayMode++;
else
currentOverlayMode = 0;
switch (currentOverlayMode) {
case OVERLAY_STREET:
mMaps.setSatellite(false);
mMaps.setStreetView(true);
prefsEditor.putInt("map_viewmode", OVERLAY_STREET);
break;
case OVERLAY_SAT:
mMaps.setStreetView(false);
mMaps.setSatellite(true);
prefsEditor.putInt("map_viewmode", OVERLAY_SAT);
break;
}
prefsEditor.commit();
mMaps.invalidate();
}
});
}
You may want to clean it up a little, but it works for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java: setting an icon in a jar application I've developed an application that I export into a runnable jar (including the libraries it needs). Everything works fine.
When running the app from Eclipse I'm able to change the icon that the application window shows:
BufferedImage image = null;
try {
image = ImageIO.read(this.getClass().getResource("AT42.png"));
} catch (IOException e) {e.printStackTrace();}
this.setIconImage(image);
The picture is placed in my .class files directory.
When I run it from Eclipse it shows the icon, but when I create a runnable jar and execute it I get the following exception:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at com.tools.at4.UserInterface.<init>(UserInterface.java:43)
at com.tools.at4.GeneradorInformes.main(GeneradorInformes.java:8)
... 5 more
I guess the icon is not include in the jar file, my question is, is there any way of incluiding it, so that when I run the jar file the windows that are created show my icon instead of the Java cup?
Thanks!!
A: With the path you are using your image needs to be put at the root of your jar file. Assuming you have your image in a directory in your project called "images", this ANT task would put the image(s) at the root of your jar:
<target name="construct-jar" depends="compile,javadoc">
<copy todir="${build.dir}">
<fileset dir="images"/>
</copy>
<jar destfile="${dist.dir}/${jar.name}" basedir="${build.dir}"/>
</target>
A: If I put the file where the .class files are I should modify my code like this:
image = ImageIO.read(this.getClass().getResource("/AT42.png"));
Thanks!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7506970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.