text stringlengths 8 267k | meta dict |
|---|---|
Q: How to create an auto-complete combobox? Does any one know the best way to create an autocomplete combobox with Knockout JS templates?
I have the following template:
<script type="text/html" id="row-template">
<tr>
...
<td>
<select class="list" data-bind="options: SomeViewModelArray,
value: SelectedItem">
</select>
</td>
...
<tr>
</script>
Sometimes this list is long and I'd like to have Knockout play nicely with perhaps jQuery autocomplete or some straight JavaScript code, but have had little success.
In addition, jQuery.Autocomplete requires an input field. Any ideas?
A: Here is my solution:
ko.bindingHandlers.ko_autocomplete = {
init: function (element, params) {
$(element).autocomplete(params());
},
update: function (element, params) {
$(element).autocomplete("option", "source", params().source);
}
};
Usage:
<input type="text" id="name-search" data-bind="value: langName,
ko_autocomplete: { source: getLangs(), select: addLang }"/>
http://jsfiddle.net/7bRVH/214/
Compared to RP's it is very basic but maybe fills your needs.
A: Minor improvements,
First of all these are some very useful tips, thank you all for sharing.
I'm using the version posted by Epstone with the following improvements:
*
*Display the label (instead of the value) when pressing up or down - apparently this can be done by handling the focus event
*Using an observable array as the data source (instead of an array)
*Added the disposable handler as suggested by George
http://jsfiddle.net/PpSfR/
...
conf.focus = function (event, ui) {
$(element).val(ui.item.label);
return false;
}
...
Btw, specifying minLength as 0 allows displaying the alternatives by just moving the arrow keys without having to enter any text.
A: I tried Niemeyer's solution with JQuery UI 1.10.x, but the autocomplete box simply didn't show up, after some searching i found a simple workaround here. Adding the following rule to the end of your jquery-ui.css file fixes the problem:
ul.ui-autocomplete.ui-menu {
z-index: 1000;
}
I also used Knockout-3.1.0, so I had to replace ko.dependentObservable(...) with ko.computed(...)
In addition, if your KO View model contains some numeric value make sure you change the comparison operators: from === to == and !== to != , so that type conversion is performed.
I hope this helps others
A: Fixed the clearing of input on load problem for RP's Solution. Even though it's kind of an indirect solution, I changed this at the end of the function:
$(element).val(modelValue && inputValueProp !== valueProp ?
unwrap(modelValue[inputValueProp]) : modelValue.toString());
to this:
var savedValue = $(element).val();
$(element).val(modelValue && inputValueProp !== valueProp ? unwrap(modelValue[inputValueProp]) : modelValue.toString());
if ($(element).val() == '') {
$(element).val(savedValue);
}
A: Disposal needed....
Both of those solutions are great (with Niemeyer's being much more fine grained) but they both forget the disposal handling!
They should handle disposals by destroying jquery autocomplete (prevent memory leakages) with this:
init: function (element, valueAccessor, allBindingsAccessor) {
....
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).autocomplete("destroy");
});
}
A: Here is a jQuery UI Autocomplete binding that I wrote. It is intended to mirror the options, optionsText, optionsValue, value binding paradigm used with select elements with a couple of additions (you can query for options via AJAX and you can differentiate what is displayed in the input box vs. what is displayed in the selection box that pops up.
You do not need to provide all of the options. It will choose defaults for you.
Here is a sample without the AJAX functionality: http://jsfiddle.net/rniemeyer/YNCTY/
Here is the same sample with a button that makes it behave more like a combo box: http://jsfiddle.net/rniemeyer/PPsRC/
Here is a sample with the options retrieved via AJAX: http://jsfiddle.net/rniemeyer/MJQ6g/
//jqAuto -- main binding (should contain additional options to pass to autocomplete)
//jqAutoSource -- the array to populate with choices (needs to be an observableArray)
//jqAutoQuery -- function to return choices (if you need to return via AJAX)
//jqAutoValue -- where to write the selected value
//jqAutoSourceLabel -- the property that should be displayed in the possible choices
//jqAutoSourceInputValue -- the property that should be displayed in the input box
//jqAutoSourceValue -- the property to use for the value
ko.bindingHandlers.jqAuto = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var options = valueAccessor() || {},
allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = allBindings.jqAutoValue,
source = allBindings.jqAutoSource,
query = allBindings.jqAutoQuery,
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp,
labelProp = allBindings.jqAutoSourceLabel || inputValueProp;
//function that is shared by both select and change event handlers
function writeValueToModel(valueToWrite) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(valueToWrite );
} else { //write to non-observable
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['jqAutoValue'])
allBindings['_ko_property_writers']['jqAutoValue'](valueToWrite );
}
}
//on a selection write the proper value to the model
options.select = function(event, ui) {
writeValueToModel(ui.item ? ui.item.actualValue : null);
};
//on a change, make sure that it is a valid value or clear out the model value
options.change = function(event, ui) {
var currentValue = $(element).val();
var matchingItem = ko.utils.arrayFirst(unwrap(source), function(item) {
return unwrap(item[inputValueProp]) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
}
//hold the autocomplete current response
var currentResponse = null;
//handle the choices being updated in a DO, to decouple value updates from source (options) updates
var mappedSource = ko.dependentObservable({
read: function() {
mapped = ko.utils.arrayMap(unwrap(source), function(item) {
var result = {};
result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString(); //show in pop-up choices
result.value = inputValueProp ? unwrap(item[inputValueProp]) : unwrap(item).toString(); //show in input box
result.actualValue = valueProp ? unwrap(item[valueProp]) : item; //store in model
return result;
});
return mapped;
},
write: function(newValue) {
source(newValue); //update the source observableArray, so our mapped value (above) is correct
if (currentResponse) {
currentResponse(mappedSource());
}
}
});
if (query) {
options.source = function(request, response) {
currentResponse = response;
query.call(this, request.term, mappedSource);
}
} else {
//whenever the items that make up the source are updated, make sure that autocomplete knows it
mappedSource.subscribe(function(newValue) {
$(element).autocomplete("option", "source", newValue);
});
options.source = mappedSource();
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).autocomplete("destroy");
});
//initialize autocomplete
$(element).autocomplete(options);
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
//update value based on a model change
var allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = unwrap(allBindings.jqAutoValue) || '',
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp;
//if we are writing a different property to the input than we are writing to the model, then locate the object
if (valueProp && inputValueProp !== valueProp) {
var source = unwrap(allBindings.jqAutoSource) || [];
var modelValue = ko.utils.arrayFirst(source, function(item) {
return unwrap(item[valueProp]) === modelValue;
}) || {};
}
//update the element with the value that should be shown in the input
$(element).val(modelValue && inputValueProp !== valueProp ? unwrap(modelValue[inputValueProp]) : modelValue.toString());
}
};
You would use it like:
<input data-bind="jqAuto: { autoFocus: true }, jqAutoSource: myPeople, jqAutoValue: mySelectedGuid, jqAutoSourceLabel: 'displayName', jqAutoSourceInputValue: 'name', jqAutoSourceValue: 'guid'" />
UPDATE: I am maintaining a version of this binding here: https://github.com/rniemeyer/knockout-jqAutocomplete
A: Niemeyer's solution is great, however I run into an issue when trying to use autocomplete inside a modal. Autocomplete was destroyed on modal close event (Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method 'option' ) I fixed it by adding two lines to the binding's subscribe method:
mappedSource.subscribe(function (newValue) {
if (!$(element).hasClass('ui-autocomplete-input'))
$(element).autocomplete(options);
$(element).autocomplete("option", "source", newValue);
});
A: I know this question is old, but I was also looking for a really simple solution for our team using this in a form, and found out that jQuery autocomplete raises an 'autocompleteselect' event.
This gave me this idea.
<input data-bind="value: text, valueUpdate:['blur','autocompleteselect'], jqAutocomplete: autocompleteUrl" />
With the handler simply being:
ko.bindingHandlers.jqAutocomplete = {
update: function(element, valueAccessor) {
var value = valueAccessor();
$(element).autocomplete({
source: value,
});
}
}
I liked this approach because it keeps the handler simple, and it doesn't attach jQuery events into my viewmodel.
Here is a fiddle with an array instead of a url as the source. This works if you click the textbox and also if you press enter.
https://jsfiddle.net/fbt1772L/3/
A: Another variation on Epstone's original solution.
I tried to use it but also found that the view model was only being updated when a value was typed manually. Selecting an autocomplete entry left the view model with the old value, which is a bit of a worry because validation still passes - it's only when you look in the database you see the problem!
The method I used is to hook the select handler of the jquery UI component in the knockout binding init, which simply updates the knockout model when a value is chosen. This code also incorporates the dispose plumbing from George's useful answer above.
init: function (element, valueAccessor, allBindingsAccessor) {
valueAccessor.select = function(event, ui) {
var va = allBindingsAccessor();
va.value(ui.item.value);
}
$(element).autocomplete(valueAccessor);
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).autocomplete("destroy");
});
}
...
<input class="form-control" type="text" data-bind="value: ModelProperty, ko_autocomplete: { source: $root.getAutocompleteValues() }" />
This is now working pretty well. It is intended to work against a preloaded array of values on the page rather than querying an api.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
} |
Q: How to use Zend Helper in Lithium i'm trying to migrate my cakephp apps to lithium, and already use Doctrine, and Twig as plugin, but now i'm also want to integrate Zend libraries into apps, and i have to integrate the Zend helper libraries.
I added the Zend library and ZendX on bootstrap, and i already can acessed the libraries in controller. But my problem is how to call helper like ZendX_JQuery_View_Helper_AjaxLink in view. So in view i can call like this :
<?php echo $this->ajaxLink("Show me something",
"/hello/world",
array('update' => '#content'));?>
it's possible to integrate those without touch anything in Zend Helper class?
A: Using Zend components in other frameworks based projects is generally very simple, except when it comes to components related to Zend's MVC or bootstrapping stack.
I would recommend that you take inspiration from the Zend's view helpers you're interested in and code your own Lithium view helpers. Here is a simple tutorial about writing Lithium view helpers, it could perhaps help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Homework Help. I have to "write" a sort I cannot use the API sorts I have to write a program that takes its arguments from the command line. There are 3 classes. The main app class, a class defining each member of the hall of fame, and then a hall of fame class that creates an array of the members of the hall of fame. The attributes for the HallOFFameMember class are firstName, lastName, yearInducted, and sport. I have to write a sort method within the HallOfFame class that sorts by the year inducted. I was trying to go about it with the comparable utility but I don't think that will work.
Here is the part of the assignment that says write the sort, so I cannot use Array.sort() or anything like that.
"Also define a method in the HallOfFame class named sortMembers that returns an array of HallOfFameMember objects that contains the objects in the members array, sorted on year of induction. Note: the sorting that is done in the sortMembers method, should not use a sort method from the API. You are to write your own sort routine (bubble sort, e.g., would be acceptable)."
I am unsure how to go about writing the sort for an attribute of an object in the array. Any help guiding me to where I can figure out how to do this would be greatly appreciated. Everything I find points to using Array.sort and compareTo method which I cannot use.
** edit **The question is can someone point me to where I can read about or find examples of how to write my own sort to sort by an attribute in an Array of Objects? Ill look into the suggestion of using comparable, as that was what I was leaning towards initially, just couldn't quite get it to work.
public class HW3 {
public static void main(String[] args) throws Exception {
if (args.length % 4 != 0) {
throw new Exception(
"First Name, Last Name, Year Inducted, Sport not entered correctly");
}
HallOfFame hallOfFameList = new HallOfFame();
hallOfFameList.setNumberOfMembers(args.length / 4);
HallOfFameMember[] tempMembers = new HallOfFameMember[args.length / 4];
for (int i = 0; i < args.length; i += 4) {
tempMembers[i/4].setFirstName(args[i]);
tempMembers[i/4].setLastName(args[i+1]);
tempMembers[i/4].setYearInducted(Integer.parseInt(args[i+2]));
tempMembers[i/4].setSport(args[i+3]);
}
hallOfFameList.setMembers(tempMembers);
HallOfFameMember[] sortedMembers = null;
hallOfFameList.sortMembers(sortedMembers);
HallOfFame.printReport(sortedMembers);
}
}
public class HallOfFameMember {
private String firstName;
private String lastName;
private String sport;
private int yearInducted;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getYearInducted() {
return yearInducted;
}
public void setYearInducted(int yearInducted) {
this.yearInducted = yearInducted;
}
}
public class HallOfFame {
private HallOfFameMember[] members;
private int numberOfMembers;
public HallOfFameMember[] getMembers() {
return members;
}
public void setMembers(HallOfFameMember[] members) {
this.members = members;
}
public int getNumberOfMembers() {
return numberOfMembers;
}
public void setNumberOfMembers(int numberOfMembers) {
this.numberOfMembers = numberOfMembers;
}
public void sortMembers(HallOfFameMember[] sortedMembers){
}
public static void printReport(HallOfFameMember[] print){
System.out.println("Java Sports Hall of Fame Inductees\n\n");
System.out.printf("%-30s\t%-30s\t%-30s\n","Name","Year Inducted","Sport");
for(int i = 0; i < print.length; i++)
System.out.printf("%-30s\t%-30s\t%-30s\n", print[i].getLastName()+","+print[i].getFirstName(), print[i].getYearInducted(), print[i].getSport());
}
}
A: To amplify on statements made in my comment:
Since this is homework, most of us will limit our advice some, but we can help you interpret the assignment. I see nothing in the instructions that prevents you from using a Comparator<HallOfFameMember> or implementing Comparable<HallOfFameMember>, and in fact I would do one or the other.
You do however have to write your own sort method, and I'd do this and have it use the Comparator helper class or Comparable interface to help with the sorting. I'd go to wikipedia, read up on the sorting algorithms and choose the easiest, perhaps bubble sort, since you aren't being graded on speed for this assignment, just on getting it done and getting it right.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Compilation error while using librsvg I am using librsvg in my C files to rasterize SVG, but as soon as I include rsvg.h, I start to get the following error:
/usr/include/librsvg-2.0/librsvg/rsvg.h:29:25: fatal error: glib-object.h: No such file or directory
*
*Does anyone know why it is happenning and how to get rid of it? I tried including the path of glib headers but then it again starts to report other missing headers.
*Is there any other open source library which I can use for rasterizing the SVG in C/C++?
A: You might want to use pkg-config to get the proper flags to add, like this:
g++ -c -o renderSVG.o renderSVG.cc $(pkg-config --cflags librsvg-2.0)
g++ -o renderSVG renderSVG.o $(pkg-config --libs librsvg-2.0)
A: Try including glib:
gcc renderSVG.cc -I/usr/include/librsvg-2.0/librsvg/ -I/usr/include/glib-2.0
A: I have the same problem using autotools on Ubuntu Natty.
I have added in configure.ac
PKG_CHECK_MODULES(LIBRSVG, librsvg-2.0 >= 2.0,
[],
[AC_MSG_FAILURE([librsvg not found])]
)
and in Makefile.am
myexe_CFLAGS=@LIBRSVG_CFLAGS@
myexe_LDFLAGS=@LIBRSVG_LIBS@
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenGL is it better to batch draw or to have static VBOs What is preferrable, from an effiency point of view (or another point of view if it's important) ?
Situation
An OpenGL application that draws many lines at different positions every frame (60 fps). Lets say there are 10 lines. Or 100 000 lines. Would the answer be different?
*
*#1 Have a static VBO that never changes, containing 2 vertices of a line
Every frame would have one glDrawArrays call per line to draw, and in between there would be matrix transformations to position our one line
*
*#2 Update the VBO with the data for all the lines every frame
Every frame would have a single draw call
A: The second is incredibly more efficient.
Changing states, particularly transformation and matrices, tends to cause recalculation of other states and generally more math.
Updating geometry, however, simply involves overwriting a buffer.
With modern video hardware on rather massive bandwidth busses, sending a few floats across is trivial. They're designed for moving tons of data quickly, it's a side effect of the job. Updating vertex buffers is exactly what they do often and fast. If we assum points of 32 bytes each (float4 position and color), 100000 line segments is less than 6 MB and PCIe 2.0 x16 is about 8 GB/s, I believe.
In some cases, depending on how the driver or card handles transforms, changing one may cause some matrix multiplication and recalculating of other values, including transforms, culling and clipping planes, etc. This isn't a problem if you change the state, draw a few thousand polys, and repeat, but when the state changes are often, they will have a significant cost.
A good example of this being previously solved is the concept of batching, minimizing state changes so more geometry can be drawn between them. This is used to more efficiently draw large amounts of geometry.
As a very clear example, consider the best case for #1: transform set triggers no additional calculation and the driver buffers zealously and perfectly. To draw 100000 lines, you need:
*
*100000 matrix sets (in system RAM)
*100000 matrix set calls with function call overhead (to video driver, copying the matrix to the buffer there)
*100000 matrices copied to video RAM, performed in a single lump
*100000 line draw calls
The function call overhead alone is going to kill performance.
On the other hand, batching involves:
*
*100000 point calculations and sets, in system RAM
*1 vbo copy to video RAM. This will be a large chunk, but a single contiguous chunk and both sides know what to expect. It can be handled well.
*1 matrix set call
*1 matrix copy to video RAM
*1 draw call
You do copy more data, but there's a good chance the VBO contents still aren't as expensive as copying the matrix data. Plus, you save a huge amount of CPU time in function calls (200000 down to 2). This simplifies life for you, the driver (which has to buffer everything and check for redundant calls and optimize and handle downloading) and probably the video card as well (which may have had to recalculate). To make it really clear, visualize simple code for it:
1:
for (i = 0; i < 100000; ++i)
{
matrix = calcMatrix(i);
setMatrix(matrix);
drawLines(1, vbo);
}
(now unwrap that)
2:
matrix = calcMatrix();
setMatrix(matrix);
for (i = 0; i < 100000; ++i)
{
localVBO[i] = point[i];
}
setVBO(localVBO);
drawLines(100000, vbo);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Hibernate session management for multiple transactions ? What is the best way for maintaning Hibernate session for multiple database transactions? Do I need to open and close each session every time or should I rely upon getCurrentSession()? Whats the best approach?
A: I think, the best approach will be to obtain sessions via openSession() and release them via disconnect(). This will cause the database connection to be returned to the Hibernate connection pool, and thus, if you're not executing all trasactions at once, your sessions will be created from the existing connections (where possible) and overall performance will be sane.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: :clouchdb error with ID I'm getting an error on one part of the :clouchdb example code (that's a link, but the examples.lisp file included doesn't work properly either).
Specifically, when I input
> (create-document '((:|name| . "wine") (:|tags| . ("beverage" "fun" "alcoholic"))))
I get a DOC-ERROR condition
Reason "Content-Type must be application/json", Document ID: "NIL"
[Condition of type DOC-ERROR]
Restarts:
0: [RETRY] Retry SLIME REPL evaluation request.
1: [*ABORT] Return to SLIME's top level.
2: [TERMINATE-THREAD] Terminate this thread (#<THREAD "repl-thread" RUNNING {10040D2E11}>)
Backtrace:
0: (POST-DOCUMENT ((:|name| . "wine") (:|tags| "beverage" "fun" "alcoholic")))
1: (SB-INT:SIMPLE-EVAL-IN-LEXENV (CREATE-DOCUMENT '((:|name| . "wine") (:|tags| "beverage" "fun" "alcoholic"))) #<NULL-LEXENV>)
--more--
The intended effect of the example is to have CouchDB assign an ID to the new document (this is made clear both in the linked page and in the comments of the code file).
I'm running SBCL 1.0.40.0, clouchdb_0.0.11 (straight out of quicklisp) and CouchDB 0.11 from the Debian repos, in case it matters. I'm also on a 64-bit Debian box.
Can anyone point me in the right direction?
A: CouchDB requires a "Content-Type: application/json" when POST'ing documents, this is a fairly new requirement so I think clouchdb simply isn't doing it yet.
Shorter version: Sounds like clouchdb is not compatible with recent releases of CouchDB.
A: Just checked the source. Robert Newson above is correct; clouchdb is still setting the content-type to "text/javascript" while posting and putting documents (the latter seems to work anyway, only the post errors).
If you don't feel like using chillax as I suggest above, you can go into the clouchdb.lisp file and change the definition of post-document such that it sets :content-type to "application/json".
You should then be able to create-document without an :id set, and CouchDB will respond by generating a new one for you.
Patch based on the quicklisp code for clouchdb (not that this is complicated enough to need one):
--- clouchdb.lispOLD 2011-09-24 09:38:20.000000000 -0400
+++ clouchdb.lisp 2011-09-24 09:38:58.000000000 -0400
@@ -753,7 +753,7 @@
the :ID property."
(let ((res (ensure-db ()
(db-request (cat (url-encode (db-name *couchdb*)) "/")
- :content-type "text/javascript"
+ :content-type "application/json"
:external-format-out +utf-8+
:content-length nil
:method :post
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How come my "calculate" will not work? I need to create a simple c# application to add some quarterly figures. I am using arrays to "store" the data and then place it in a textbox.
Anyways, I am having some issues with my calculate section. I have put comment tags around it so you guys can easily find it. The area works, but it requires two clicks and adds it to the line above. I have been looking at the same few lines for about an hour and can not seem to figure this one out. Any ideas out there?
//Global
int lastIndexUsed = -1;
int[,] quarters = new int[10, 5];
string[] Branch = new string[10];
public FrmSales()
{
InitializeComponent();
}
private void txtBranch_TextChanged(object sender, EventArgs e)
{
}
private void btnCalc_Click(object sender, EventArgs e)
{
int Q1;
int Q2;
int Q3;
int Q4;
Q1 = int.Parse(txtQ1.Text);
Q2 = int.Parse(txtQ2.Text);
Q3 = int.Parse(txtQ3.Text);
Q4 = int.Parse(txtQ4.Text);
lastIndexUsed = lastIndexUsed + 1;
quarters[lastIndexUsed, 0] = Q1;
quarters[lastIndexUsed, 1] = Q2;
quarters[lastIndexUsed, 2] = Q3;
quarters[lastIndexUsed, 3] = Q4;
Branch[lastIndexUsed] = txtBranch.Text;
//Display Results
int ctr;
int ctr2;
string outLine;
string tempName;
int row;
int col;
int accum;
txtInfo.Text = "";
outLine = " Branch Q1 Q2 Q3 Q4 Total " + "\r\n";
outLine = outLine + "========== ========== ========== ========== ========== ==========" + "\r\n";
txtInfo.Text = outLine;
for (ctr = 0; ctr <= lastIndexUsed; ctr++)
{
outLine = "";
tempName = Branch[ctr].PadLeft(10);
outLine = outLine + tempName + " ";
for (ctr2 = 0; ctr2 <= 4; ctr2 = ctr2 + 1)
{
outLine = outLine + quarters[ctr, ctr2].ToString().PadLeft(10) + " ";
}
txtInfo.Text = txtInfo.Text + outLine + "\r\n";
}
//Calculate ###########################################################
for (row = 0; row <= lastIndexUsed; row++)
{
accum = 0;
for (col = 0; col <= 3; col++ )
{
accum = accum + quarters[row, col];
}
quarters[row, 4] = accum;
}
//End Calculate #########################################################
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBranch.Text = "";
txtQ1.Text = "";
txtQ2.Text = "";
txtQ3.Text = "";
txtQ4.Text = "";
txtInfo.Text = "";
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
A: The problem is simple: you use the quarters array before you actually calculate the values for it. Move the "calculate" loop to be above the first loop.
Also (among other things):
*
*Too many blank lines and whitespace; makes it hard to read
*Don't try to make a formatted report using text; just use a DataGridView or similar
*If you click the button enough times, you will have an array index out of bounds exception, because lastIndexUsed will go above 10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Needing an elegant solution to a simple, C++ bingo board I'm trying to code a Bingo Board in C++, but I'm doing something very wrong. I'm not sure what, but for whatever reason when I initialize the number of rows and columns, and do a nested for loop on the arrays I created to implement this structure, I get what appears to be more than a hundred rows and 30+ columns, when I should just be getting a five, by five board. I'm also trying to specify a max and min value for my rand function, but it appears that there isn't a way to do this. Thus, what would be the best approach to accomplish this without giving away the solution? The reason why I mention that last bit is so I can learn how to do this lol.
Here is my code:
#ifndef BOARD_H
#define BOARD_H
#include <cstdlib>
#include <time.h>
#include <stdio.h>
class Board
{
public:
Board(unsigned int numberOfRows, unsigned int numberOfColumns, unsigned int seed, unsigned int max, unsigned int min);
void generate();
void setSeedValue(int seed);
private:
unsigned int m_rows[];
unsigned int m_columns[];
unsigned int m_max, m_min;
};
#endif // BOARD_H
Board::Board(unsigned int numberOfRows, unsigned int numberOfColumns, unsigned int seed, unsigned int max, unsigned int min)
{
this->m_rows[numberOfRows];
this->m_columns[numberOfColumns];
srand(seed);
this->m_max = max;
this->m_min = min;
printf("%d\n", size_t(m_rows));
printf("%d\n", size_t(m_columns));
}
void Board::generate()
{
for (int i = 0; i < size_t(m_rows); i++)
{
for(int j = 0; j < size_t(m_columns); j++)
{
this->m_columns[j] = (rand() % 10) + j;
std::cout << this->m_columns[j];
}
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Board * board = new Board(5, 5, time(NULL), 100, 1);
board->generate();
delete board;
return a.exec();
}
A: In order to create the 2-dimensional board your wanting, where the size is input at runtime, you're going to have to actually dynamically allocate a board in memory ... you can't declare your board the way you've done in your class as zero-length arrays.
Code like this:
this->m_rows[numberOfRows];
does not initialize your array-size ... rather it actually attempts to access memory allocated at that offset from the start of m_rows ... that could cause a segmentation fault or some other undefined behavior due to accessing memory beyond the end of the class/structure type.
It would be much better, since you're using C++, to create your board class using the STL's std::vector container. Your Board class would then look like the following:
class Board
{
public:
Board(unsigned int numberOfRows, unsigned int numberOfColumns,
unsigned int seed, unsigned int max, unsigned int min);
void generate();
void setSeedValue(int seed);
private:
vector<vector<unsigned int> > board; //use the STL vector container
unsigned int m_max, m_min;
};
Then in your constructor, you would actually allocate the necessary memory (through the STL's vector container) that your board will take up:
Board::Board(unsigned int numberOfRows, unsigned int numberOfColumns,
unsigned int seed, unsigned int max, unsigned int min)
{
for (int i=0; i < numberOfRows; i++)
{
this->board.push_back(vector<unsigned int>(numberOfColumns, 0));
}
srand(seed);
this->m_max = max;
this->m_min = min;
printf("%d\n", size_t(m_rows));
printf("%d\n", size_t(m_columns));
}
Finally, your Board::generate function would now look like the following:
void Board::generate()
{
for (int i = 0; i < this->board.size(); i++)
{
for(int j = 0; j < this->board[i].size(); j++)
{
this->board[i][j] = (rand() % 10) + j;
std::cout << this->board[i][j];
}
}
}
A: Let your board class store the row size and column size that as member variables. Use those member variables as your upper bounds in your for loops in the member function generate(). Also, use a 2D array rather an 1D array, as this better represents the structure of a bingo board. Currently, your initialization of temporary size_t's in your for loops is not correct. The array name is acts as a pointer to the first element of the array -- so that variable you create is not giving you the length of the array. You have to store the length of arrays separately from the array itself (or use boost::array).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is std::bitset::at() throwing out_of_range? This has stumped me for a few hours now, since I cannot see any problem in the math or code. (Dispite staring at it and working it out over and over again to be sure.) I'm hoping you folks can help me, here's my code:
#define SOLVE_POSITION(x, y, z) ( z*16 + y*4 + x )
std::bitset<64> block;
block.reset();
for(int z = 0; z < 4; ++z){
for(int y = 0; y < 4; ++y){
for(int x = 0; x < 4; ++x){
if(block.at(SOLVE_POSITION(3-x, y, 3-z))){ //<-- call to at() throws 'out_of_range'
// do stuff
};
};
};
};
With z being 0, the two inner most for loops run their course entirely (for a total of 16 passes.) However, once z becomes 1, that's when the exception is thrown from within std::bitset<64>::at().
The values of z, y, x are respectively 1, 0, 0 at that moment.
Can you tell me what is happening here to cause this exception?
Thanks in advance!
A: Macros! You have to be really careful about this:
You define:
#define SOLVE_POSITION(x, y, z) ( z*16 + y*4 + x )
so when you do:
SOLVE_POSITION(3-x, y, 3-z)
it expands to:
( 3-x*16 + y*4 + 3-z )
and because of operator precedence, 3-x*16 will be incorrect! You need to do:
#define SOLVE_POSITION(x, y, z) ( (z)*16 + (y)*4 + (x) )
so that it expands correctly to:
( (3-x)*16 + (y)*4 + (3-z) )
as expected.
A: Macros use text substitution, you're effectively telling the compiler
SOLVE_POSITION(3-x, y, 3-z) => SOLVE_POSITION( 3-z*16 + y*4 + 3-x )
To fix this, make sure you surround your macro arguments with parenthesis:
#define SOLVE_POSITION(x, y, z) ( (z)*16 + (y)*4 + (x) )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Restrict Entries in UITextField Is there a way to restrict a user to enter only certain information inside a UITextField? For example, I want to restrict a user to enter only U.S. states. I know I can use other controls, such as UIPickerView, but I want them to type this, if possible. Thanks.
A: check out:
- ( BOOL )textField:( UITextField * )textField
shouldChangeCharactersInRange:( NSRange )range
replacementString:( NSString * )string
Here's an article on autocomplete given an array of possible values (an NSMutableArray). You could probably change it slightly to limit the entries instead of suggestions for autocomplete.
http://www.raywenderlich.com/336/how-to-auto-complete-with-custom-values
Hope that helps.
A: The UITextField restriction is in turn restricted to certain limits. You can restrict the text field to accept only the Alphabets, Alphanumeric values, or Numeric values. But its almost impossible to restrict text field from accepting State names of other countries but US.
One way you can do this is by having a dictionary/list of the State names in US. And when the user finished entering the text in the text field, match the entered text with the list you have. If the list doesn't contain the text typed, then the user is not genuine, and he is trying to cheat your app. :-0
The best way is to let the user pick from a UIPickerView or UITableView with the State names you want the user to pick from. By this way the user is completely restricted and no way he can cheat your app. ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use a proxy in python and twisted to get a page Is it true that if you have a proxy such as http://222.126.99.99:8909 that you can access a url from the browser e.g. www.cnn.com as http://222.126.99.99:8909/www.cnn.com.
Is this is true, from twisted can I use the proxy to get a page as follows?
iUrl=http://222.126.99.99:8909/www.cnn.com
client.getPage(iUrl,method='GET').addCallback(self.processPage,iUrl).addErrback(self.printError,iUrl)
A:
if the proxy requires a username and password..how do I do modify the URL to use the credentials?
The format is:
url = 'http://username:password@host:port/path'
Though it is deprecated.
Note, it is not safe to send your username and password over http.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what's the difference between password and passphrase For private key file, it requires to be encrypted using pass phrase. I am wondering is there any difference between password and pass phrase?
A: Nothing is different beyond semantics. "Password" implies that you should use only one word while "passphrase" implies you can use multiple words. I have never seen a place where the strict meaning is enforced though, the two terms are usually completely interchangeable.
A: As an example:
Password: abc@123!@#
Passphrase: This is the passphrase for CA.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Conditional Layouts in ASP.NET MVC 3 So with layouts in MVC3 lets say I want to be able to specify on a page level if a particular section is displayed, what is the best way to go about it. Consider the following page:
@{
ViewBag.Title = "...";
Layout = "~/Views/Shared/Layout/_Layout.cshtml";
}
@section LetsBeFriends {
}
@section Header {
....
}
@section Body {
....
}
For the LetsBeFriends section to be conditional I have implemented the layout like this:
@{
if (IsSectionDefined("LetsBeFriends"))
{
@RenderSection("LetsBeFriends")
@Html.Partial("_LetsBeFriends")
}
}
@RenderSection("Body")
This seems hacky because LetsBeFriends will always be an empty section, its just a condition to decide whether to render the partial. Is there a better way?
A: Why not use the ViewBag? In your page:
@if (friendsCondition)
{
ViewBag.LetsBeFriends = true;
}
Then, in _Layout.cshtml:
@if (Viewbag.LetsBeFriends)
{
@Html.Partial("_LetsBeFriends")
}
However, it is even better to set this in the controller action, rather than the view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Background image attribute not support in Microsoft office outlook 2007 //this is my Email Template HTML code
<center>
<table border="0" cellspacing="0" cellpadding="0" width="650" style="margin:auto; border-spacing:0px;">
<tr>
<td height="177" width="650" background="http://dev.artoonsolutions.com/newsmtp/images/thankyou_email_top_bg.png" style="background-repeat:no-repeat;"></td>
</tr>
<tr>
<td height="100" width="650" background="http://dev.artoonsolutions.com/newsmtp/images/thankyou_email_middle.png" style="background-repeat:repeat-y;" valign="baseline">
<div style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:14px; color:#666666; line-height:150%; width:494px; margin:auto; word-break:loose; display:block;">
<p style="text-align:right; margin:0 0 10px 0; padding:0px;">May 26, 2 011</p>
<p style="text-align:left; margin:0 0 20px 0; padding:0px;">Dear {full name},</p>
<p style="text-align:left; margin:0 0 20px 0; padding:0px;">At CKR Interactive, we value relationships. Without them, we could not do what we do best and continue to provide our clients with extraordinary, and effective, recruitment solutions for their businesses. That is why we are sending you this note – to thank you for contacting us.</p>
<p style="text-align:left; margin:0 0 20px 0; padding:0px;">While we are confident that we can help you develop, plan, and follow through with unique and compelling recruitment strategies, we are
primarily thrilled to have had the chance to meet with you about {subject}. </p>
<p style="text-align:left; margin:0 0 20px 0; padding:0px;">We look forward to having the opportunity to work closely in the future and would be very glad to bring you the results you have been seeking.</p>
<p style="text-align:left; margin:0 0 20px 0; padding:0px;">If theres anything you need, you can always reach us at <strong>866.527.4952</strong> (Toll Free).</p>
<p style="text-align:left; margin:0 0 20px 0; padding:0px;">Here is to our mutual success! </p>
<p style="text-align:left; margin:0 0 20px 0; padding:0px;">Yours truly, </p>
</div>
</td>
</tr>
<tr>
<td height="525" width="650"><img src="http://dev.artoonsolutions.com/newsmtp/images/thankyou_email_bottom.png" alt="img" width="650" height="525" border="0" usemap="#Map" /></td>
</tr>
</table>
A: Change:
background="..."
To:
style="background: url('...');"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to write this nested query? Here are 2 queries. Which one is correct?
SELECT link.[xlink:Show].
Location.[xlink:show],
link.[xlink:actuate],
Location.[xlink:actuate],
FROM Sem
JOIN Location AND
Link join Location ON
link. link_id = Location.link_id);
Error: Incorrect syntax near the keyword 'AND'.
SELECT link.[xlink:Show],
Location.[xlink:show],
link.[xlink:actuate],
Location.[xlink:actuate],
Sem.SemRole
FROM Sem, Link
JOIN Location ON link. link_id = Location.link_id);
Error: The multi-part identifier " Sem. SemRoleId" could not be bound.
A: Try this:
SELECT LI.[xlink:Show],
LI.[xlink:actuate],
LO.[xlink:show],
LO.[xlink:actuate],
S.SemRole
FROM Sem AS S
INNER JOIN Location AS LO ON S.SemRoleId = LO.SemRoleId
INNER JOIN Link AS LI ON LI.link_id = LO.link_id;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Heroku Slug Size Shot up suddenly Locally my application is 7MB without tests and logs, etc. The .git folder is 29 MB. I also have no gems / plugins in vendor folder. 95% of images sit on S3. However on committing to Heroku it shows
-----> Compiled slug size is 62.7MB
What is wrong? It happened?
To add more context my .gitignore file is .bundle, db/.sqlite3, config/database.yml, log/.log, tmp/, .idea, .redcar, .sass-cache/, multi_xml/, test/, doc/
Please advice
A: The compiled slug size includes all of your gems as well. If you're on the Cedar stack, they've made some mistakes that will make your some gems with native extensions even bigger than they're supposed to be.
A: Moved to Cedar and then cleaned up public/assets everytime precompiling again. Reduced slug size drastically.
A: Look into having a .slugignore file in your root folder. It tells Heroku the files not to compile into slug. Checkout this answer. Redeploy your app if the reduction in slugsize is not instant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Any differce between mvn:assembly and mvn:package I knew mvn:package can be used to generate JAR or WAR, is there any difference between mvn:assembly?
A: They are quite different. 'package' is a simple command used for simple/single projects where you only have to create a jar/war.
The assembly plugin is much more powerful, and can be used to create full distribution packages for large projects. This can be just a simple jar file, but it can also be a large distribution archive for your project, including source code, documentation, etc. You configure what the assembly should look like by means of an XML file called the assembly descriptor.
A: Assembly is needed if you plan to create an archive that contains your classes plus the libraries + docs + ...
To create war (or any native Maven packaging) you can simply set <packaging>war</packaging>.
If you want to customize this war, you need the war (respectivelly jar) plugin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Having Issues with Custom Dialog Box I need some help with my custom dialog box. This is the first time I have built a custom dialog box and for some reason it keeps crashing. The below code is what I have in my onCreate() method. I want to click on the edittext box bring up the dialog box then enter the ticker symbol or stock price, hit OK and it will populate the edittext box. Please help
public void test() {
// Click on Stock Price to bring up dialog box
myStockPrice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create the dialog
final Dialog dialog = new Dialog(
OptionsPricingCalculatorActivity.this);
// Set the content view to our xml layout
dialog.setContentView(R.layout.enterstocksym);
// Set the title of the dialog. this space is always drawn even
// if blank so might as well use it
dialog.setTitle("Ticker Symbol");
dialog.setCancelable(true);
// dialog.setMessage("Enter Company Ticker Symbol");
// Here we add functionality to our dialog box's content. In
// this example it's the two buttons
// Set an EditText view to get user input
input = (EditText) findViewById(R.id.StockSymbol);
input2 = (EditText) findViewById(R.id.StockPrice);
Button okButton = (Button) dialog.findViewById(R.id.BtnOk);
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Tickervalue = input.getEditableText().toString().trim();
// Do something with value!
// Toast.makeText(getApplicationContext(), value,
// Toast.LENGTH_SHORT).show();
// Send Stock Symbol into Request
SoapObject request = new SoapObject(NAMESPACE,
METHOD_NAME);
request.addProperty("symbol", Tickervalue);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE httpTransport = new HttpTransportSE(
SERVICE_URL);
// httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive) envelope
.getResponse();
parseResponse(result.toString());
} catch (Exception e) {
Log.d("STOCK",
e.getClass().getName() + ": "
+ e.getMessage());
Toast t = Toast.makeText(
OptionsPricingCalculatorActivity.this,
e.getClass().getName() + ": "
+ e.getMessage(), 10);
t.show();
}
}
private void parseResponse(String response)
throws Exception {
// TODO Auto-generated method stub
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new InputSource(
new InputStreamReader(new ByteArrayInputStream(
response.getBytes()), "UTF-8")));
Element element = document.getDocumentElement();
NodeList stocks = element.getElementsByTagName("Stock");
if (stocks.getLength() > 0) {
for (int i = 0; i < stocks.getLength();) {
Element stock = (Element) stocks.item(i);
Element Tickervalue = (Element) stock
.getElementsByTagName("Last").item(0);
// Send data from response to OUTPUT object
EditText tv = (EditText) findViewById(R.id.txtStockPrice);
tv.setText(Tickervalue.getFirstChild()
.getNodeValue());
break;
}
}
}
});
Button cancelButton = (Button) dialog
.findViewById(R.id.BtnCancel);
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
Logcat
09-24 04:10:51.252: ERROR/AndroidRuntime(428): FATAL EXCEPTION: main
09-24 04:10:51.252: ERROR/AndroidRuntime(428): java.lang.NullPointerException
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at com.CSV.Buescher.OptionsPricingCalculatorActivity$2$1.onClick(OptionsPricingCalculatorActivity.java:186)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at android.view.View.performClick(View.java:2408)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at android.view.View$PerformClick.run(View.java:8816)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at android.os.Handler.handleCallback(Handler.java:587)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at android.os.Handler.dispatchMessage(Handler.java:92)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at android.os.Looper.loop(Looper.java:123)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at java.lang.reflect.Method.invoke(Method.java:521)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-24 04:10:51.252: ERROR/AndroidRuntime(428): at dalvik.system.NativeStart.main(Native Method)
09-24 04:10:51.282: WARN/ActivityManager(59): Force finishing activity com.CSV.Buescher/.OptionsPricingCalculatorActivity
09-24 04:10:51.865: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{44ece368 com.CSV.Buescher/.OptionsPricingCalculatorActivity}
A: It is difficult to tell with the nested anonymous inner classes but I think your widgets with ids StockSymbol and StockPrice are in the dialog. When you find them however you do this:
input = (EditText)findViewById(R.id.StockSymbol);
input2 = (EditText)findViewById(R.id.StockPrice);
Which is looking in the activity rather than the dialog. They are not being found so input is null when the button is clicked. Try this instead:
input = (EditText)dialog.findViewById(R.id.StockSymbol);
input2 = (EditText)dialog.findViewById(R.id.StockPrice);
You may want to break the inner classes out to make all this easier to read and debug.
A: The below code worked liked a charm, however I would like to get the custom layout to work.
Thanks
LinearLayout lila1= new LinearLayout(this);
lila1.setOrientation(1); //1 is for vertical orientation
final EditText input = new EditText(this);
final EditText input1 = new EditText(this);
lila1.addView(input);
lila1.addView(input1);
alert.setView(lila1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is the Zend Locale library usable with CodeIgniter? I've been reading some of the questions and answers regarding locales and some of the suggest the use of the Zend Locale library.
Would it be possible to use this library in CodeIgniter or does it depend on other components? I'd like to be able to convert values, currencies and dates if possible without letting go of CI language files.
What do you think? Would it be looking for trouble and hacks to get it working?
A: Zend Framework components are supposed to be usable separately, but some of them depend on other ZF components as well. So, maybe you'll need to provide some others together with Zend_Locale.
You can have a look at the files in Zend/Locale and Zend/Locale.php and grep for require_once statements. After a quick look at Zend/Locale.php it seems that you'll probably need Zend_Registry and Zend_Cache at least.
To make Zend's components work and "auto-require" the files they need, you just have to make sure their root folder 'Zend' is in you include path.
Hope that helps...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: reading a file while it's being written I've read some posts on stackoverflow about this topic but I'm still confused. When reading a file that is currently being written in Java, how do you keep track of how many lines have actually been written so that you don't get weird read results?
EDIT: sorry, I should have mentioned that the file writing it is in C++ and the one reading it is in Java so variables can't really be shared easily
A:
When reading a file that is currently being written in Java, how do you keep track of how many lines have actually been written so that you don't get weird read results?
The problem is that you can never be sure that the current last character of the file is the end of a line. If it is a line terminator, you are OK. If BufferedReader.readLine() will interpret it as a complete line without a line terminator ... and weird results will ensue.
What you need to do is to implement your own line buffering. When you get an EOF you wait until the file grows some more and then resume reading the line.
Alternatively, if you are using Java 7 or later, the file watcher APIs allow you to watch for file writes without polling the file's size.
By the way, there is an Apache commons class that is designed for doing this kind of thing:
http://commons.apache.org/io/api-2.0/org/apache/commons/io/input/Tailer.html
A: If I understand, the file is being written in C# in some process and another Java process wants to read it while it is being written.
Look at File Monitoring section on the tail command here. But I want to warn you that when I used the cygwin tail on Windows recently to follow log files that were rolling over, it sometimes failed under heavy load. Other implementations may be more robust.
A: To have a count of the number of lines, just keep a counter on the side that's doing the writing.
So, every time you write a line, increment a counter, and make that counter readable via a method, something like, public int getNumLinesWritten()
A: The obvious answer to me... Why not use a buffer? Use a string or whatever you need. (You could use a list/array of strings if you want, one for each line maybe?) Append to the string just as you would write to the file, then instead of reading from the file, read from that string. Would that work for you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Links contains #, would it affect SEO? If i have such links in my site (i am using mvcsitemap):
http://mysite.com/coollink
http://mysite.com/coollink#contanttab1
http://mysite.com/coollink#contenttab2
If i want to submit site map to google for example, should i use the links with # in mysite XML sitemap? or better not to use them in sitemap XML?
Because in such case there would be 3 links to the same resource as i understand and it is not so good for SEO? could some one correct me if i am wrong.
A: As far as I know so far, hashes will be ignored by most of the search engines and they have no use for SEO. It is user more for internal page navigation or some sort of JavaScript actions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery empty is very slow I am trying to empty an HTML table that has about 200 rows using $("#mytable").empty(). While it is emptying the rows, I cannot do anything else, looks like the UI is blocked.
Is this the right function to use? Can this operation be done in the background, in order to minimize the noticeable lag?
A: how about just:
document.getElementById('mytable').innerHTML = "";
A: $.empty() slow if many childrens, I'm using:
var containerNode = document.getElementById("content");
while (containerNode.hasChildNodes()) {
containerNode.removeChild(containerNode.lastChild);
}
A: I've never had that problem before, however, I would suggest this:
$("#mytable").children().detach().remove();
More than likely it is taking a while because of the clean-up jQuery does on the elements. With them detached, it may happen quicker.
A: You could just remove the table itself:
$('#mytable').remove()
Or the children of the table only:
$('#mytable').children().remove()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to obtain the maximum screen resolution that a monitor supports using C# I need to obtain the Maximum supported screen resolution of a monitor, not the current resolution which is easy. Any help would be appreciated.
Edit: This is the updated solution that worked for me.
public Size GetMaximumScreenSizePrimary()
{
var scope = new System.Management.ManagementScope();
var q = new System.Management.ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");
using (var searcher = new System.Management.ManagementObjectSearcher(scope, q))
{
var results = searcher.Get();
UInt32 maxHResolution = 0;
UInt32 maxVResolution = 0;
foreach (var item in results)
{
if ((UInt32)item["HorizontalResolution"] > maxHResolution)
maxHResolution = (UInt32)item["HorizontalResolution"];
if ((UInt32)item["VerticalResolution"] > maxVResolution)
maxVResolution = (UInt32)item["VerticalResolution"];
}
log.Debug("Max Supported Resolution " + maxHResolution + "x" + maxVResolution);
}
return new Size(maxHResolution, maxVResolution);
}
A: Get the results from the Management Scope.
var scope = new System.Management.ManagementScope();
var q = new System.Management.ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");
using (var searcher = new System.Management.ManagementObjectSearcher(scope, q))
{
var results = searcher.Get();
foreach (var item in results)
{
Console.WriteLine(item["Caption"]);
}
}
For more information about what information is available, refer to the CIM_VideoControllerResolution page.
A: Obtain newWidth & newHeight of screen resolution as below and use them where u required
Screen scr = Screen.PrimaryScreen;
int newWidth = scr.Bounds.Width;
int newHeight = scr.Bounds.Height;
A: Use primary screen property
http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.primaryscreen.aspx
Regards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: back-Updating tree of rows in DB from result of last update I'm not sure this is even possible, but I would really like to be sure in order to create the most efficient code...
I need to build a query that works like an affiliate -
when a user signs in, I need to see if someone invited him, or if he got there alone (basic URL param). If he was invited, I need to give him X points. If the inviter was invited by someone, I need to give him 1/2X points, and if he was also invited, I need to give his inviter 1/4 points. I need this to be endless until the parent of all has no more "invited_by" values (null/0)...
I did this with a php (while x), a counter to calculate the amount of points - 1/(X sqr $i), but i'm not happy because it takes me a select and update query each time...
I'm using php and mysql.
Is there someone who can think of a better way to do this?
Thanks!
A: I think that you will need an iterative solution. I don't see any hierarchical query operators in the MySQL manual that might help you out (but that isn't quite the same as saying there aren't any; my eyesight isn't perfect). You could perform it in a stored procedure, which would reduce the cost of the operation (less data transferred between database server and client).
Also, the X/2, X/4, X/8, sequence isn't captured by the expressions 1/2X or 1/(X sqr $i); I assume that there was no intent to give the invitrr a fraction of a point whereas the inviter's inviter gets X/4 points?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Send gps coordinates to server in XML I am making an app in which i want to send gps coordinates like latitude and longitude to server in xml .. Can anybody help me how to do this .. Any help will be appreciated ...
Thanks..
A: Google is really your friend on this one. Stackoverflow is more ment for programming issues, not tutorials on how to do something, noone will write the code for you.
What have you tried earlier?
Similar question How to send GPS data from android to a website?
Obtaining users location
Send to server:
Android (Java) Simple Send and receive with Server - Fast Setup Challenge
How to send a data to a web server from Android
Soap:
https://stackoverflow.com/questions/3112426/best-soap-tutorials
Android WSDL/SOAP service client
How to call a SOAP web service on Android
A: One way I can think of is to initiate a POST request via HTTP using a URL like:
http://server.example.com/postgps
(Assume server.example.com is the server to send the data to.)
The request body would then contain XML data.
The question, however, is too vague for us to help further.
A: What does your server accept as an interface? GML is a standard XML grammar for geographic information. You can simplify it by using GML Simple Features Profile. If you want something even easier, you might try GeoURI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Place client-side JavaScript templates in HTML or JavaScript? Should client-side templates like the following (using underscore's templating engine):
<p class="foo"><%= bar %></p>
be placed in an separate HTML file, or a separate JavaScript file? I know it could work both ways.
For example, a JavaScript file could just contain a list of string variables like so:
var cute = '<p class="the"><%= unicorn %></p>';
var fb = '<p class="new-design"><%= sucks %></p>';
But I have also seen the following:
<script type="text/template" id="omg-template">
<span id="swag-name"><%= name %></span>
</script>
Just from a Separation of Concerns standpoint, where does the template storage belong?
A: I usually will use an asset management system that concatenate and minify javascripts and css, and translate client side template files into JS strings hanging off a global var. This sort of thing depends on your platform, but in the rails world you want to look at jammit or sprockets (which is now part of rails)
If I don't have decent asset management, I will usually end up using the script tag method, with the templates split out into partials on the server, and included into the bottom of the page. It is sort of a pain to work with, but IMO anything more then your simple example string templates really shouldn't exist inline in your javascript file.
A: If you are using logicless client-side template engine like Transparency templates can be embedded in main HTML because the templates themselves are valid HTML.
Example:
<!-- Template -->
<div id="template">
<span class="greeting"></span>
<span class="name"></span>
</div>
// Data
var hello = {
greeting: 'Hello',
name: 'world!'
};
<!-- Result -->
<div id="template">
<span class="greeting">Hello</span>
<span class="name">world!</span>
</div>
For templates to be used in widget like manner a hidden <div> container does fine.
Putting HTML'ish code to Javascript codeblocks and Javascript strings is ugly and should be avoided if possible. It is not syntax highlightable and you miss errors easily.
A: I greatly prefer the second option, for the following reasons:
*
*Using strings means dealing with escaping quotes and the like.
*Multi-line templates are a pain in Javascript, as you can't have multi-line strings without concatenation. Templates of any length will be more legible on multiple lines.
*No syntax highlighting in JS strings.
But using the second option requires loading your template file somehow, or including it in your HTML, or sticking it into your HTML at build time. Plus there's more data overhead due to the script tag, AND you have to get the string from the DOM using jQuery's .html() or a similar method. So performance-wise, the string option might be better - which is why @Matt's suggestion of putting it into strings at build time is probably best.
A: You could use jQuery's templating engine and load all your templates in an external js file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Dynamic Style Sheet Is it possible to link a style sheet from code behind.
I want to link stylesheet_1 when the current day is < 15 th
and stylesheet_2 when current day is > 15 th
Thanks
A: You don't need to use code behind. Just use Javascript to link according to the date in onLoad() function in the body like the following example:
var d = new Date();
var fileName
if(d.GetDate()<15){
fileName="stylesheet_1"
}else{
fileName="stylesheet_2"
}
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", fileName)
document.getElementsByTagName("head")[0].appendChild(fileref)
A: Haven't tested this, but I think it will work.
Put this in the head of the aspx page
<link href="stylesheet.css" rel="stylesheet" type="text/css" id="stylesheet" />
and then you can use the in the code behind to change it
stylesheet.Href = "stylesheet_1.css";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: comparing two text files and remove duplicates in python I have two text files, file1 and file2.
File1 contains a bunch of random words, and file2 contains words that I want to remove from file1 when they occur.
Is there a way of doing this?
I know I probably should include my own attempt at a script, to at least show effort, but to be honest it's laughable and wouldn't be of any help.
If someone could at least give a tip about where to start, it would be greatly appreciated.
A: get the words from each:
f1 = open("/path/to/file1", "r")
f2 = open("/path/to/file2", "r")
file1_raw = f1.read()
file2_raw = f2.read()
file1_words = file1_raw.split()
file2_words = file2_raw.split()
if you want unique words from file1 that aren't in file2:
result = set(file1_words).difference(set(file2_words))
if you care about removing the words from the text of file1
for w in file2_words:
file1_raw = file1_raw.replace(w, "")
A: If you read the words into a set (one for each file), you can use set.difference(). This works if you don't care about the order of the output.
If you care about the order, read the first file into a list, the second into a set, and remove all the elements in the list that are in the set.
a = ["a", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
b = {"quick", "brown"}
c = [x for x in a if not x in b]
print c
gives: ['a', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP local array in function? I have a game that will display ten random cards based on number and suit, but I need to check an array to see if the card has already been displayed. But my local array $card is not being saved when it passes through the function. Here is all my code for right now please try running it and tell me what I am doing wrong if you want the images they are avaiable at.
http://storealutes.com/blackjack/cards.zip
here is my php:
<?php
//suit 1=Clubs | 2=Hearts | 3=Spades | 4=Diamonds//
//Color 1=1or11 | 2-10=# | 11-12=10//
$number;
$suit;
$card = array();
function newcard($number,$suit,$card){
$arrsuit = array (clubs, hearts, spades, diamonds);
$arrnumber = array (a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, k);
$number = $arrnumber[rand(0,12)]; //Creates card value
$suit = $arrsuit[rand(0,3)]; //Create card suit
$card .= array ($suit ." ". $number, hello); //difines card name
return "<img src='cards/" . $suit . "-" . $number . "-150.png'/>";
}
for($i = 0; $i < 10; $i++){
echo newcard($number,$suit,$card);
}
echo $number;
foreach($card as $value){
echo $value;
}
?>
A: Unlike most sane languages, there is little sense of lexical scope in PHP. So, your function doesn't recognize variables defined globally. The easy fix for this is to use global $card; inside of your function.
A: To access a variable inside of a function use the follow techniques.
$GLOBALS['card'][] = array ($suit ." ". $number, hello);
or
global $card;
$card[] = array ($suit ." ". $number, hello);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3.1, RSpec: testing model validations I have started my journey with TDD in Rails and have run into a small issue regarding tests for model validations that I can't seem to find a solution to. Let's say I have a User model,
class User < ActiveRecord::Base
validates :username, :presence => true
end
and a simple test
it "should require a username" do
User.new(:username => "").should_not be_valid
end
This correctly tests the presence validation, but what if I want to be more specific? For example, testing full_messages on the errors object..
it "should require a username" do
user = User.create(:username => "")
user.errors[:username].should ~= /can't be blank/
end
My concern about the initial attempt (using should_not be_valid) is that RSpec won't produce a descriptive error message. It simply says "expected valid? to return false, got true." However, the second test example has a minor drawback: it uses the create method instead of the new method in order to get at the errors object.
I would like my tests to be more specific about what they're testing, but at the same time not have to touch a database.
Anyone have any input?
A: CONGRATULATIONS on you endeavor into TDD with ROR I promise once you get going you will not look back.
The simplest quick and dirty solution will be to generate a new valid model before each of your tests like this:
before(:each) do
@user = User.new
@user.username = "a valid username"
end
BUT what I suggest is you set up factories for all your models that will generate a valid model for you automatically and then you can muddle with individual attributes and see if your validation. I like to use FactoryGirl for this:
Basically once you get set up your test would look something like this:
it "should have valid factory" do
FactoryGirl.build(:user).should be_valid
end
it "should require a username" do
FactoryGirl.build(:user, :username => "").should_not be_valid
end
Here is a good railscast that explains it all better than me:
UPDATE: As of version 3.0 the syntax for factory girl has changed. I have amended my sample code to reflect this.
A: in new version rspec, you should use expect instead should, otherwise you'll get warning:
it "should have valid factory" do
expect(FactoryGirl.build(:user)).to be_valid
end
it "should require a username" do
expect(FactoryGirl.build(:user, :username => "")).not_to be_valid
end
A: An easier way to test model validations (and a lot more of active-record) is to use a gem like shoulda or remarkable.
They will allow to the test as follows:
describe User
it { should validate_presence_of :name }
end
A: Try this:
it "should require a username" do
user = User.create(:username => "")
user.valid?
user.errors.should have_key(:username)
end
A: I have traditionally handled error content specs in feature or request specs. So, for instance, I have a similar spec which I'll condense below:
Feature Spec Example
before(:each) { visit_order_path }
scenario 'with invalid (empty) description' , :js => :true do
add_empty_task #this line is defined in my spec_helper
expect(page).to have_content("can't be blank")
So then, I have my model spec testing whether something is valid, but then my feature spec which tests the exact output of the error message. FYI, these feature specs require Capybara which can be found here.
A: Like @nathanvda said, I would take advantage of Thoughtbot's Shoulda Matchers gem. With that rocking, you can write your test in the following manner as to test for presence, as well as any custom error message.
RSpec.describe User do
describe 'User validations' do
let(:message) { "I pitty da foo who dont enter a name" }
it 'validates presence and message' do
is_expected.to validate_presence_of(:name).
with_message message
end
# shorthand syntax:
it { is_expected.to validate_presence_of(:name).with_message message }
end
end
A: A little late to the party here, but if you don't want to add shoulda matchers, this should work with rspec-rails and factorybot:
# ./spec/factories/user.rb
FactoryBot.define do
factory :user do
sequence(:username) { |n| "user_#{n}" }
end
end
# ./spec/models/user_spec.rb
describe User, type: :model do
context 'without a username' do
let(:user) { create :user, username: nil }
it "should NOT be valid with a username error" do
expect(user).not_to be_valid
expect(user.errors).to have_key(:username)
end
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "73"
} |
Q: Redirect URL type 301 in Java I learn to know where actually link redirect from an URL.
After testinf on redirect URL web site, it give url redirect type 301.
So, I test based on link below to get real link.
Get hold of redirect url with Java org.apache.http.client
Code looks like below:
HttpGet httpget = new HttpGet(filename);
HttpContext context = new BasicHttpContext();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute((HttpUriRequest) httpget, context);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw new IOException(response.getStatusLine().toString());
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
String currentUrl = currentHost.toURI() + currentReq.getURI();
System.out.println(currentUrl);
but I got this message:
The method execute(HttpUriRequest, HttpContext) in the type AbstractHttpClient is not >applicable for the arguments (HttpGet, HttpContext)
Would some body help me, what's wrong in this code?
A: Your code works well for me with this httpclient dependency:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.1.2</version>
</dependency>
and with these imports:
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
Check that you are using the correct dependencies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Split NSString by number of whitespaces I have an NSString that contains some values separated by an unknown number of whitespace characters. For example:
NSString* line = @"1 2 3";
I would like to split the NSString into an NSArray of values like so: {@"1", @"2", @"3"}.
A: This should do the trick (assuming the values don't contain whitespace):
// Gives us [@"1", @"2", @"", @"", @"", @"", @"3"].
NSArray *values = [line componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
// Remove the empty strings.
values = [values filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"SELF != ''"]];
A: Get the components separated by @" " and remove all objects like @"" from the resultant array.
NSString* line = @"1 2 3";
NSMutableArray *array = (NSMutableArray *)[line componentsSeparatedByString:@" "];
[array removeObject:@""]; // This removes all objects like @""
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Jquery Chrome extension help? I am making a Chrome extensions where you can drag and drop links and it'll bookmark it in the extension. I found this from a stackoverflow thread, it does what I want it to but the only problem is that I want it to make a new element with the link and not replace the old link. Can someone point me to the right direction. I'm stuck.
A: I modified that fiddle to match your request. Each dropped link now creates a new LI element within a UL. I suggest you read up on the Chrome Bookmark API if you haven't already, and I commented the fiddle to show locations where you would use API functions. If you want to remember which bookmarks the user has created through the extension, you may want to set up localStorage as well to save the ID of the created bookmark.
JSFiddle: http://jsfiddle.net/ArkahnX/jwsdm/5/
LocalStorage: http://www.kirupa.com/html5/html5_local_storage.htm
Chrome Bookmarks API:http://code.google.com/chrome/extensions/bookmarks.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Quine-McCluskey algorithm in Python I'm trying to write the Quine-McCluskey algorithm in python, but I wanted to see if there were any versions out there that I might use instead. A google search showed few useful results. I'm looking for 4x4 map reduction, not 2x2 or 3x3. Any ideas or references?
A: def combine(m, n):
a = len(m)
c = ''
count = 0
for i in range(a):
if(m[i] == n[i]):
c += m[i]
elif(m[i] != n[i]):
c += '-'
count += 1
if(count > 1):
return None
else:
return c
def find_prime_implicants(data):
newList = list(data)
size = len(newList)
IM = []
im = []
im2 = []
mark = [0]*size
m = 0
for i in range(size):
for j in range(i+1, size):
c = combine( str(newList[i]), str(newList[j]) )
if c != None:
im.append(str(c))
mark[i] = 1
mark[j] = 1
else:
continue
mark2 = [0]*len(im)
for p in range(len(im)):
for n in range(p+1, len(im)):
if( p != n and mark2[n] == 0):
if( im[p] == im[n]):
mark2[n] = 1
for r in range(len(im)):
if(mark2[r] == 0):
im2.append(im[r])
for q in range(size):
if( mark[q] == 0 ):
IM.append( str(newList[q]) )
m = m+1
if(m == size or size == 1):
return IM
else:
return IM + find_prime_implicants(im2)
minterms = set(['1101', '1100', '1110', '1111', '1010', '0011', '0111', '0110'])
minterms2 = set(['0000', '0100', '1000', '0101', '1100', '0111', '1011', '1111'])
minterms3 = set(['0001', '0011', '0100', '0110', '1011', '0000', '1000', '1010', '1100', '1101'])
print 'PI(s):', find_prime_implicants(minterms)
print 'PI2(s):', find_prime_implicants(minterms2)
print 'PI3(s):', find_prime_implicants(minterms3)
A: In the Wikipedia of which you gave the link, there are some "External links" at the bottom, among which are these, interesting relatively to your project:
*
* " Python Implementation by Robert Dick "
Wouldn't this fulfil your need ?
*" A series of two articles describing the algorithm(s) implemented in R: first article and second article. The R implementation is exhaustive and it offers complete and exact solutions. It processes up to 20 input variables. "
You could use the rpy Python interface to R language to run the R code of the Quine-McCluskey algorithm. Note that there is a rewrite of rpy : rpy2
Also, why not, write yourself a new Python script, using the enhancement of the algorithm done by Adrian Duşa in 2007 , lying in the second article ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Have a javascript function privately track it's number of calls I'm trying to figure out how I can have a javascript function privately track the number of times it has been called. The objective is to be able to query this value in the console during debugging by doing func.run
My first attempt:
function asdf() {
if (!asdf.run) {
asdf.run = 0;
} else {
asdf.run++;
console.error('run: ' + asdf.run);
}
console.error('asdf.run def: ');
console.error(asdf.run);
}
asdf();
This is a good lesson of why one should ALWAYS aim to use === in nearly all javascript booleans, cause they could secretly be ==
A: Closures are the way to go here:
var asdf = (function () {
var runs = 0;
var f = function () {
++runs;
// your function here
};
f.runs = function () {
return runs;
};
return f;
}());
Usage:
asdf();
asdf();
asdf.runs(); // 2
asdf();
asdf.runs(); // 3
Or, you could use a mocking framework like (shameless self plug) Myrtle.
A: Your first try would work fine except you've forgotten that 0 is a "falsy" value in JavaScript, so on the first run and every run thereafter !this.run will evaluate to true and your else block will never be reached. This is pretty easy to work around.
function foo() {
if(typeof(foo.count) == 'undefined') {
foo.count = 0;
} else {
foo.count++;
}
console.log(foo.count);
}
foo(); # => 0
foo(); # => 1
foo(); # => 2
# ...
A: I haven't actually tried this, but I looked up "static function variables in JavaScript", and I found this resource. I think the main difference between what you wrote and what's in that solution is how the first run of the function is detected. Perhaps your !asdf.run test is not working the way you thought it was, and you should use typeof asdf.run == 'undefined' to test instead.
A: OK, here is a method that I came up with that does not require the function to be modified at all.
So if you have this.
function someFunction() {
doingThings();
}
you could add a counter like this...
addCounter(this, "someFunction");
where this is the scope you are in, you could use any object that has a method you want to count.
Here's the code for it.
<html>
<head>
<script>
function someFunc() {
console.log("I've been called!");
};
// pass an object, this or window and a function name
function wrapFunction(parent, functionName) {
var count = 0, orig = parent[functionName];
parent[functionName] = function() {
count++;
return orig.call(this, Array.prototype.slice(arguments));
}
parent[functionName].getCount = function() {
return count;
};
}
var someObj = {
someFunc: function() {
console.log("this is someObj.someFunc()");
}
}
wrapFunction(this, "someFunc");
wrapFunction(someObj, "someFunc");
someFunc();
someObj.someFunc();
someObj.someFunc();
someObj.someFunc();
console.log("Global someFunc called " + someFunc.getCount() + " time" + (someFunc.getCount() > 1 ? "s" : "")) ;
console.log("Global someObj.someFunc called " + someObj.someFunc.getCount() + " time" + (someObj.someFunc.getCount() > 1 ? "s" : "")) ;
</script>
</head>
A: So, !asdf.run is a form of the double equals operator == and I had set asdf.run to 0 so it was false.
Using the triple equals === :
typeof asdf.run === "undefined" for the boolean solves my issue.
So a final usable and useful version:
function sdf() {
if (typeof sdf.run === "undefined") { sdf.run = 0; }
sdf.run++;
}
To query the number of times sdf has been called:
sdf.run;
To actually make this variable private and protect it from change, one would implement a closure.
A: //using a closure and keeping your functions out of the global scope
var myApp = (function() {
//counter is a private member of this scope
var retObj = {}, counter = 0;
//function fn() has privileged access to counter
retObj.fn = function() {
counter++;
console.log(counter);
};
//set retObj to myApp variable
return retObj;
}());
myApp.fn(); //count = 1
myApp.fn(); //count = 2
myApp.fn(); //count = 3
A: You don't necessarily need a closure. Just use a static variable.
var foo = function(){
alert( ++foo.count || (foo.count = 1) );
}
// test
function callTwice(f){ f(); f(); }
callTwice(foo) // will alert 1 then 2
or
callTwice( function bar(){
alert( ++bar.count || (bar.count = 1) );
}); // will alert 1 then 2
the second one is a named anonymous function. And note this syntax:
var foo = function bar(){ /* foo === bar in here */ }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: bad planing with mysql_fetch_assoc? I am making a page where people can make posts. All of those posts are then shown in a table of 24 cells. I can have the last 24 posts shown with no problem, but now I don't know how to show the prior group(s) of posts. How can I fix my code to do that? I actually have this:
(I'm removing lines to make it easy to read)
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC";
// ---check everything is fine---- //
function retrieve_info($result)
{
if($row = mysql_fetch_assoc($result))
{echo $topic_if; echo $topic_subject; //and what I want in every cell
}
}
<table width="100%" height="751" >
<tr><td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td></tr>
<!-- repeat a few more times :-) -->
</table>
I though that by changing the variable $row with a number before the if statement would alter the output, but I still see the same data printed on screen. What should I do to be able to show next group of posts?
Thanks!!!
A: function retrieve_info($result)
{
while($row = mysql_fetch_assoc($result))
{
$topic_id = htmlspecialchars($row['topic_id']);
$topic_subject = htmlspecialchars($row['topic_subject']);
echo '<td>';
echo $topic_if;
echo $topic_subject; //and what I want in every cell
echo '</td>';
}
}
A: At some point when you have hundreds or thousands of records, you are going to want to paginate the results and not just select all records from the table.
To do this you will run one query per 24 records, your sql would be more like this:
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC
LIMIT 0, 24
";
and for the next 24,
LIMIT 24, 24
then
LIMIT 48, 24
and so on.
You would then make next/previous buttons to click which would refresh the page and dispay the next 24, or you would get the next results with an AJAX request and append the next 24 through the DOM.
This suggests having to take a slightly different approach then calling the same function from each table cell.
More like get the relevant 24 results based on the page number you are on, then loop through the results array and print out the table code with values inside it. Based on if the iterator of the loop is divisible by 4 (looks like your grid is 4x6), you print out new tags for the new row, and that sort of thing.
Search around a bit for pagination in php and mysql to get a sense of how this all fits together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery - Object ... has no method 'css' Why can't I change the CSS of this element?
$("div.example ul li").mouseover(function () {
var ul_teirs = $("div.example ul li").find('ul');
var second_teir = ul_teirs[0];
var third_teir = ul_teirs[1];
second_teir.css({
...
});
});
error I'm getting:
Uncaught TypeError: Object #<HTMLUListElement> has no method 'css'
A: Try
var second_teir = ul_teirs.eq(0);
var third_teir = ul_teirs.eq(1);
A: When you use [] to access an item in a jQuery array, you get the DOM element, not a jQuery object, so it doesn't have any jQuery methods.
Try .eq() instead:
var second_tier = ul_tiers.eq(0);
second_tier.css({ ... });
(Note that I changed the spelling of "tier" in the variable name. Sorry, I can't help myself.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to print libssl and libnspr version from c++ code? How can I print the version of libssl and libnspr in c++ code ?
I want to print version for both defined in header and library .
A: The header file opensslv.h #define 's the macro variable OPENSSL_VERSION_TEXT, describing the version. For instance "OpenSSL 0.9.8o-fips 01 Jun 2010".
For the library itself, the name of the lib file contains the version number. In ubuntu, in the folder /lib/, the file is called libssl.so.0.9.8. If you felt like it, you could use boost::filesystem to grab the particular filename and then parse it, perhaps using boost::regex.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How should I split up a Python module into PyPi packages? I have written a Python module that I'd like to make available for others. Right now, it is one large module nested into sub-folders:
*
*wraith
*
*util
*ext
*color
I think it's best to split these sub-folders up into separate packages. The tipfy project does this. However, the ext and color modules depend on util.
What's the best way to organize and release these modules? Do I split them up and name them wraith.util, wraith.ext, and wraith.color like tipfy? Do I include util when people install ext or color?
A: If wraith.ext etc. are not useful on their own it is not necessary to split. Can you imagine someone would use wrait.util without installing wraith.color?
If you decide to split you need to set install_requires in setup.py which tells setuptools etc. the package dependencies. Also you need to set-up namespace_packages telling that wrait namespace will receive other packages too.
More info
*
*http://tarekziade.wordpress.com/2011/08/19/5-tips-for-packaging-your-python-projects/
*http://packages.python.org/distribute/setuptools.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Wix Bind Substring or Split I'm trying to get a Wix installer written that does some TypeLib registration.
I'm already pulling the FileVersion off a registered file elsewhere using
!(bind.FileVersion.#InteropDll)
but I want to do the same thing for the TypeLib, which only has separate MajorVersion and MinorVersion attributes. Ideally, I'd like to do
<TypeLib ...
MajorVersion="!(bind.FileVersion.InteropDll).Split('.')[0]"
MinorVersion="!(bind.FileVersion.InteropDll).Split('.')[1]">
How can I accomplish this (or the like)? ...Or should I just not bother with all this and invoke regasm on the dll file at install time?
Thanks.
A: The WiX toolset doesn't support doing that today. It's an interesting feature request. I would never call regasm during an install. It's way to hard to get rollback and patching and all that working correctly by shelling out to an external executable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is str_replace faster with array? My question is if using array on str_replace is faster than doing it multiple times. My question goes for only two replaces.
With array
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables");
$yummy = array("pizza", "beer");
$newphrase = str_replace($healthy, $yummy, $phrase);
each search word once
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$newphrase = str_replace("fruits", "pizza", $phrase);
$newphrase = str_replace("vegetables", "beer", $phrase);
A: From PHP Docs on str_replace :
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
Looking at those examples, PHP is applying the str_replace for each $search array node so both of your examples are the same in terms of performance however sure using an array for search and replace is more readable and future-prof as you can easily alter the array in future.
A: I don't know if it's faster but I tend do go with the array route because it's more maintainable and readable to me...
$replace = array();
$replace['fruits'] = 'pizza';
$replace['vegetables'] = 'beer';
$new_str = str_replace(array_keys($replace), array_values($replace), $old_str);
If I had to guess I would say making multiple calls to str_replace would be slower but I'm not sure of the internals of str_replace. With stuff like this I've tended to go with readability/maintainability as the benefit to optimization is just not there as you might only get around 0.0005 seconds of difference depending on # of replacements.
If you really want to find out the time difference it's going to be close to impossible without building up a hugh dataset in order to get to the point where you can see an actual time difference vs anomalies from test confounds.
Using something like this ...
$start = microtime(true);
// Your Code To Benchmark
echo (microtime(true) - $start) . "Seconds"
... will allow you to time a request.
A: Try using this before and after each different method and you will soon see if there is a speed difference:
echo microtime()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Get value from GridView when a button is clicked I have a GridView , and the GridView has an item template. Now I need to get the value of the first cell which contains the value I need but I have tried the following and does not work, it eturns a ""
int id = Convert.ToInt32(GridView.Rows[index].Cells[0].Text);
Here is the code I have in the gridview
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="lblDepartmentID" Text='<%#DataBinder.Eval(Container.DataItem,"DepartmentID")%>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
I have to emphazise that I do not want to use the GridView_RowCommand or other GridView events.. I need to pull this value upon clicking a button on the same page.
How can I do this?
A: If you are trying to access the text value of Label then you have to first get the reference to Label control like this:
Label lbl = (Label)GridView.Rows[index].FindControl("lblDepartmentID");
and then use it's Text property to get the value required:
int id = Convert.ToInt32(lbl.Text);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Change the alignment of Toast by Programmatically?
Possible Duplicate:
how to change position of Toast in android?
How to change the Alignment for Toast? Basically, toast it'll displays information bottom of the device. How can we change that? Anyone help me to find out this? Thanks in Advance.
A: It would be a nice idea to create a Custom Toast like this,
TextView textview = new TextView(context);
textview.setText(text);
textview.setBackgroundColor(Color.GRAY);
textview.setTextColor(Color.BLUE);
textview.setPadding(10,10,10,10);
Toast toast = new Toast(context);
toast.setView(textview);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
By this you can place the Toast to anywhere you want using Gravity
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Add address annotation when finding route via google maps api I'm using google maps to get directions from one place to another. Here is the code
NSString *mapAPIString = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f",
sourceAddress.coordiate.latitude,
sourceAddress.coordiate.longitude,
destAddress.coordiate.latitude,
destAddress.coordiate.longitude,
];
NSURL *url = [[NSURL alloc] initWithString:mapAPIString];
[[UIApplication sharedApplication] openURL:url];
The code works perfect. But both addresses are marked as 'Unknown address' in iOS Map App. Is it possible to add custom title for each address ?
A: iOS 6 is still under NDA, but if you have access to the docs have a look at them and you will probably find useful information for this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Layout of columns which automatically fill fixed width container vertically? I've got elements with different heights but fixed width in a container element. When I set the elements to inline-block, the columns fill up automatically, but horizontally, like this. Please notice the numbers, indicating an element.
1## 2## 3##
### ### ###
### ###
###
4## 5## 6##
### ### ###
###
7## 8## 9##
### ### ###
###
What I'd like is to have them fill up vertically too, like this.
1## 2## 3##
### ### ###
### 5## ###
4## ### ###
### 8## 6##
### ### ###
7## 9##
### ###
###
And lets assume the width of the container element is increased.
1## 2## 3## 4##
### ### ### ###
### 6## ### ###
5## ### ### 8##
### 7## ###
9## ###
###
###
Is there any way to do this with just HTML and CSS?
A: CSS layouts don't support this. You'll have to use a Javascript layout tool like Masonry to achieve the effect you're looking for.
A: You can use CSS3 Columns (Compatibility table) to do this. For example:
ol {
list-style: decimal outside;
-moz-column-count: 3;
-webkit-column-count: 3;
column-count: 3;
}
The multi-column module is not supported in IE9 (but it will be in IE10). To avoid the child elements being split up you need the break-inside property:
ol li {
-webkit-column-break-inside: avoid;
break-inside: avoid;
}
Unfortunately this is not supported in Firefox (Bugzilla).
Here's a demo: http://jsfiddle.net/Q4BNm/2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wix Event Log Not Getting Created I'm trying to create an Event Log and Event Source at install time using Wix. The install doesn't fail or give any error...but I don't see any Event Log called MyApp getting created.
<PropertyRef Id="NETFRAMEWORK40FULLINSTALLROOTDIR"/>
<Component Id="EventLog" Guid="AD09F8B9-80A0-46E6-9E36-9618E2023D67">
<util:EventSource Log="MyApp" Name="MyApp" EventMessageFile="[NETFRAMEWORK40FULLINSTALLROOTDIR]EventLogMessages.dll" />
</Component>
I previously had a .NET Installer class that did this and it worked without a problem.
What am I doing wrong?
A: I had problems with this, and it was because I was missing a <CreateFolder /> element; my code ended up looking like this:
<Component Id="CreateEventLog32Bit" Guid="{some-guid}" Permanent="yes">
<Condition><![CDATA[NETFRAMEWORK40FULLINSTALLROOTDIR AND NOT VersionNT64]]></Condition>
<CreateFolder />
<util:EventSource Log="Application" Name="MyApp" EventMessageFile="[NETFRAMEWORK40FULLINSTALLROOTDIR]EventLogMessages.dll" />
</Component>
<Component Id="CreateEventLog64Bit" Guid="{some-other-guid}" Permanent="yes">
<Condition><![CDATA[NETFRAMEWORK40FULLINSTALLROOTDIR64 AND VersionNT64]]></Condition>
<CreateFolder />
<util:EventSource Log="Application" Name="MyApp" EventMessageFile="[NETFRAMEWORK40FULLINSTALLROOTDIR64]EventLogMessages.dll" />
</Component>
(so it can handle both 32-bit and 64-bit installs of .NET 4)
A: Can you post an installer log? The EventSource element is really just some syntatical sugar. WiX translates these into simple registry keys/values and I've never seen it fail in any of the installs I've used it in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: XML DTD - What does the asterisk mean when it's outside the bracket I understand that
<!ELEMENT tagname (source*)>
means that source can appear zero or more times, but I don't understand what this means
<!ELEMENT story (#PCDATA | date)*>
Is that asterisk outside the bracket applied to everything inside or to story or something else?
Thanks!
A: It's a (possibly empty) sequence over { #PCDATA | date }. To be clear a production rule for (x|y)* is
(x|y)* = {} | x(x|y)* | y(x|y)*
In your language of "zero or more times" it means that you repeatedly choose one of #PCDATA or date where you make zero or more choices.
Clear?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically detect if the browser displays a temporary status bar? With the recent Firefox and Chrome browser releases, the default status bar has been taken from us to free up more screen space and de-clutter the UI. The status bar was used to display the URL of any link the user rolls over, among other things.
The browser makers couldn't completely remove the status part of the status bar, because users need to be shown where they will be going if they roll over a link. They've settled into displaying a temporary, tooltip-style modeless text bar that appears at the bottom left or right of the browser window's client area on link rollover.
I'll put aside my displeasure with the browser makers invading MY beautiful client area and smearing their chrome all over with distracting fade-in transitions and weak color/contrast choices. I'd just like some suggestions on how to best deal with this current situation.
I use absolute positioning to keep some of my DOM elements in the lower left and right of the visible client area on the page. Is there a way to detect in javascript how tall these temporary status bars will be so that I can vertically offset my elements far enough from the bottom of the page so that they are not occluded by the temporary status bar?
Browser plugins like StatusBar-4-Evar are not a good solution for me because I could never suggest that my users install anything to view my website. I'd like solutions to work with the browsers' default settings.
I don't want to work too hard for this; I'd like to avoid browser/version detection to know when I should vertically offset my elements. I am ready to accept if my page design is not workable and to assume the bottom of the page is now off-limits to any content other than that page content which flows there naturally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery validation - breaking on change? Here is our code:
http://jsfiddle.net/ajLkz/1/
Basically, if we wrap the if statements for each input box in a jquery function like change or keyup - the whole thing returns true for everything.
Basically what we are aiming for is if EVERY if statement returns false, the button then becomes full opacity and disabled false.
But we want to put these if statements in a jquery change/keyup function.
Its really starting to annoy me >.<
A: is that resolving the problem ?
jsfiddle.net/ajLkz/3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Need recommendation for templating configuration files and auditing I am looking for a template engine for pushing and pulling data from configuration files. To be more specific, Cisco router configuration files. My goal has two parts
1) To be able to template my router config and insert unique data (hostname, interface IP's, ...etc) from an authoritative source (Mysql). Afterwards, I have a mechanism for loading the configs.
2) Once a device is configured and placed into production, I need a way of auditing against the latest version of my template. This would allow us to discover when operators change the running configuration.
Thoughts?
A: Let's take the simplest approach.
*
*Use whatever language and templating engine you want, write a script that generates a config by e.g. a device name.
*To check, generate a config for a device, download the actual config from that device, run diff. Mail the differences, if any, to people in charge of auditing.
The templating engine makes no difference in your case: you have no performance constraints, it seems. I'd take Python + Mako / Jinja / Cheetah, or Ruby + Rails, but even a bash + sed script could work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ruby on rails: Avoid drop down if values are already selected I am pretty new to Ruby on rails. I have one query
I have one view (say view1) in which I am showing a drop down. For that I have passed and array and populating the drop down using that array like dis
<td><=% select_tag, options_for_select(@businessApprovers)></td>
So when I submit the form it goes to an action which intrun renders another view which has 5 tabs in body and each tab has a partial view. one of them calls my previous view view1. Now when it calls the view1 it again shows the drop down. instead it should show only one value and that too non editable.
we are having some other drop down too but they have hard coded values. We are doing that like this:
<td><=% f.field :contries, :condition_select, [abc,pqr] ....
and above thing is working fine. For that it is not showing drop down.
So I wanted to know how to avoid that drop down. Also what is the use of "f.field" because I removed that and from then on it is causing this problem.
A: Firstly, field is for CSV, text_field is a thing. Is that what that should be? Also, I'm hoping that's not exact code.
Instead of:
<td><=% f...
It should be:
<td><%= f...
That aside, if you're simply looking to display a select field when no selection has yet been made and simply text when it DOES have a value, then it would be as simple as using a conditional:
<% if thing.something.empty? %>
<%= f.select ... %>
<% else %>
<%= thing.something %>
<% end %>
If my assumptions were incorrect, please reply and I'll revise.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: creating unique yet ordered ,order number for a customer's order In my java app I need to generate a unique order number for a customer's order.I thought the time of creation of order is a good enough unique value.Two orders cannot be created at the same second.
To prevent others from using the ordernumber, by guessing some creationtime value,I appended a part of hash of the creationtime string to it and made it the final order number string.
Is there any unseen pitfall in this approach?Creating the order number based on time of creation was intended to give some sort order for the created orders in the system..
The code is given here
public static String createOrderNumber(Date orderDate) throws NoSuchAlgorithmException {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String datestring = df.format(orderDate).toString();
System.out.println("datestring="+datestring);
System.out.println("datestring size="+datestring.length());
String hash = makeHashString(datestring);//creates SHA1 hash of 16 digits
System.out.println("hash="+hash);
System.out.println("hash size="+hash.length());
int datestringlen = datestring.length();
String ordernum = datestring+hash.substring(datestringlen,datestringlen+5);
System.out.println("ordernum size="+ordernum.length());
return ordernum;
}
private static String makeHashString(String plain) throws NoSuchAlgorithmException {
final int MD_PASSWORD_LENGTH = 16;
final String HASH_ALGORITHM = "SHA1";
String hash = null;
try {
MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
md.update(plain.getBytes());
BigInteger hashint = new BigInteger(1, md.digest());
hash = hashint.toString(MD_PASSWORD_LENGTH);
} catch (NoSuchAlgorithmException nsae) {
throw(nsae);
}
return hash;
}
A sample output is
datestring=20110924103251
datestring size=14
hash=a9bcd51fc69d9225c5d96061d9c8628137df14e0
hash size=40
ordernum size=19
ordernum=2011092410325125c5d
A: One potential issue cn arise if your application runs on cluster of servers.
In this case if it happens that this code is executed simultanesously in two JVMs tha same orders will be generated.
If this is not the case, the unique order number generation based on the dates sounds ok to me.
I didn't really understood the meaning of hash here.
I mean from the cryptography point of view it doesn't really add a security to your code. If a "malicious" client guesses the order number, its enough to know that the SHA1 hash is applied, the algorithm itself is known, and may be applied to determine the order number.
Hope this helps
A: If needed an unique it should always be from a 3rd party system which is common and the receiving/calculating method should be through a synchronized method where this will happens sequential or can be generated through database system which will be almost always unique.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass argument to delegate method in Rails I would like to have a Dashboard to display summary of multiple models, and I implemented it using Presenter without its own data. I use an ActiveModel class (without data table):
class Dashboard
attr_accessor :user_id
def initialize(id)
self.user_id = id
end
delegate :username, :password, :to => :user
delegate :address, :to => :account
delegate :friends, :to => :friendship
end
By delegate, I want to be able to call Dashboard.address and get back Account.find_by_user_id(Dashboard.user_id).address.
If Dashboard was an ActiveRecord class, then I could have declared Dashboard#belongs_to :account and delegate would work automatically (i.e., Account would know it should return address attribute from account with user_id equals to user_id in Dashboard instance).
But Dashboard is not an ActiveRecord class, so I can't declare belongs_to. I need another way to tell Account to lookup the right record.
Is there a way to overcome this problem? (I know I can fake Dashboard to have an empty table, or I can rewrite User's instance methods to class methods that take argument. But these solutions are all hacks).
Thank you.
A: When you write delegate :address, :to => :account, this creates a new address method on Dashboard which basically calls the account method on the same object and then calls address on the result of this account method. This is (very roughly) akin to writing:
class Dashboard
...
def address
self.account.address
end
...
end
With your current class, all you have to do is to create an account method which returns the account with the correct user_id:
class Dashboard
attr_accessor :user_id
def initialize(id)
self.user_id = id
end
delegate :username, :password, :to => :user
delegate :address, :to => :account
delegate :friends, :to => :friendship
def account
@account ||= Account.find_by_user_id(self.user_id)
end
end
This would allow you to access the address like this:
dashboard = Dashboard.new(1)
# the following returns Account.find_by_user_id(1).address
address = dashboard.address
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Using Linq Zip function to merge collections for a view in Silverlight Based upon a prior question I had Here. I wanted to join two collections together so that the merged data could be then displayed within a DataGrid of a Silverlight UI.
Using the Linq Zip function I was able to merge my two collections as follows
public void CombineAllCollections()
{
var combineAll = Persons.Zip(PhoneNumbers, (x, y) => new
{
FirstName = x.FirstName,
LastName = x.LastName,
Address = x.Address,
State = x.State,
Zip = x.Zip,
AreaCode = y.AreaCode,
PhoneNumber = y.Number
});
}
This seems to do just what I wanted. However the output is an Anonymous Type. How can I cast the combinedAll type to a collection (List, ObservableColl. IENum) that I can then pass to a view in my UI ( Bind to a datagrid) . The output should then display within the grid a column and value for each item ( as listed above seven columns).
Thanks in advance
-Cheers
A: Instead of making an anonymous type, you could create a concrete type specifically for the merged results with all of the properties you specified on the anonymous type.
For example:
public void CombineAllCollections()
{
var combineAll = Persons.Zip(PhoneNumbers, (x, y) => new PersonWithPhoneNumber
{
FirstName = x.FirstName,
LastName = x.LastName,
Address = x.Address,
State = x.State,
Zip = x.Zip,
AreaCode = y.AreaCode,
PhoneNumber = y.Number
});
}
Where PersonWithPhoneNumber is the type with all of the specified properties.
Then you can call ToList() on the result to convert it to an IList<PersonWithPhoneNumber> or you can leave it in the form it is in as an IEnumerable<PersonWithPhoneNumber>
EDIT
Given the information that you provided, it would appear about the only effective way to store so many values while maintaining the ability to use LINQ and not have to define a separate type would be to create a dictionary for each item in the zipped collection, for example:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var xs = new[] {1, 2, 3, 4, 5, 6};
var ys = new[] {7, 8, 9, 10, 11, 12};
var zipped = xs.Zip(ys, (x, y) =>
new Dictionary<string, object>
{
{ "X", x},
{ "Y", y}
});
foreach (var pair in zipped.SelectMany(tuple => tuple))
{
Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
}
}
}
}
This way, you can have as many Key/Value pairs in the dictionary for each item as you would like. However, you essentially lose any type safety using this method and will end up boxing all value types for each property. This means you will have to know the type to cast back to. I would honestly not recommend doing this. I would simply just make a type, even if that type needs 100 properties. In this scenario auto-properties and a good text editor are your best friend.
You could also us the new dynamic type in C# 4 with the .NET 4.0 framework as in the following example:
using System;
using System.Dynamic;
using System.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var xs = new[] {1, 2, 3, 4, 5, 6};
var ys = new[] {7, 8, 9, 10, 11, 12};
var zipped = xs.Zip(ys, (x, y) =>
{
dynamic value = new ExpandoObject();
value.X = x;
value.Y = y;
return value;
});
foreach (var pair in zipped)
{
Console.WriteLine("X = {0}, Y = {1}", pair.X, pair.Y);
}
}
}
}
This will introduce dynamic into your code, though. Which may not have the performance metrics you desire and can lead to a lot of run-time errors if you don't keep an eye out on what you're doing. This is because you could misspell a property while creating or accessing it (this is also an issue with the dictionary setup) which will lead to a run-time exception when you attempt to access it. Again, probably best to just use a concrete, named typed in the end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JFrame Icon in Netbeans I'm Building a Swing Application and I need to know how to set an Icon for my JFrames through Netbeans 7.0 if it is possible.
Thank you for your cooperation.
Best Regards.
A: This might help you: YouTube: Change the Icon in Java Frame. It's from 2009, so it's not the latest, but it is still likely applicable.
Note that JFrame has a method, setIconImage that will do this for you and is easy to use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Codeigniter/Datamapper "where_related" causing too many queries I have a many-to-many mapping between profiles and categories. This query:
$profiles = new Profile();
$profiles->where('foobar_flag',1);
$profiles->where_related($category);
$profiles->get();
Is taking almost 30 seconds to run, with about 1000 entries in that profiles table. There is also a category table, and a profiles_categories table. I end up with a staggering 4000 queries per execution.
How do I make this faster?
A: If you are unhappy with a function in datamapper, either find a simplified way of doing it as your active record query might just be too costly as you say.
Always run your profiler:
$this->output->enable_profiler(TRUE);
This will give you a true idea of what is being done behind the scenes. Optimize from there on. Otherwise we need more code to go on here to give relevant answers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rmagick resize and flatten_image error I am trying to use Rmagick to combine two images.
*
*The image on top can be resized and dragged using Jquery-UI. I get size of the image after resize using Jquery code such as follows:
ui.size["height"] and ui.size["width"]
*I send this data using Ajax to Rails server.
*The next step I resize the image using Rmagick resize_to_fit and then use flatten_image to combine the two images as follows:
images=ImageList.new(img1, img2)
images[1]=images[1].resize_to_fit!(height, width)
images[1].page=Rectangle.new(height, width, x_coord+offset, y_coord-offset1)
com_img=images.flatten_images
com_img.write(tmpfile.path)
My problem is that the resize image does not seem to work correctly. I am always getting an image smaller than what I want (for different heights and widths tested by resizing image). The image's left top corner is correctly placed (meaning page command is working correctly). I checked my Jquery UI code and ajax and its sending the correct size information. Somehow the information is not being processed correctly by Rmagick resize or flatten_image.
Can someone provide pointers what could be wrong here?
Thanks!
PS: Offsets account for the first image's position with respect to page top-left corner.
A: I found the solution to the problem Rmagick requires the images when they are resized that they should fit into a square. So the resize_to_fit function works correctly when both dimensions are the same and are the larger one among height or width.
So I changed the code to do the following
if height > width
images[1]=images[1].resize_to_fit!(height, height)
else
images[1]=images[1].resize_to_fit!(width, width)
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add user to group but not reflected when run "id" R creates a group called staff and I want to be able to update packages without starting R as sudo. So I added myself to staff using:
sudo usermod -G adm,dialout,cdrom,plugdev,lpadmin,admin,sambashare,staff matt
(side question is there a way to add yourself to a group without listing every other group you're a member of?)
If i check /etc/groups i see
staff:x:50:matt
and the same for /etc/shadow
staff:*::matt
however if i run groups or id i'm not a member of staff. Also, I can't make changes to anything in /usr/local/lib/R.
A: Did you log the "matt" account out and back in after running the sudo usermod command? Changes to the groups a user is in under unix only take affect at login time.
A: In answer to your side question, yes you can add a user to a group without listing them all. If you run a Debian based system, you can do it with
sudo adduser matt staff
The adduser utility is just a friendly wrapper around useradd/usermod etc.
If you don't have the adduser utility, you can still do it with usermod:
sudo usermod -a -G staff matt
The -a flag means append (as opposed to overwrite).
A: https://superuser.com/questions/272061/reload-a-linux-users-group-assignments-without-logging-out
check that out ~
both
newgrp groupname
OR
su - username
will do the trick well ~
A: I know the original question is for Linux but OSX users can do the same with this command:
sudo dseditgroup -o edit -a newusertoadd -t user grouptobeaddedto
A: Explanation: The operation succeeded - that's why your name appears in the right linux files on /etc/passwd & /etc/group but as soon as you open a new terminal process the bash will be updated with this setting and you can perform id matt as well.
Clarification: You added yourself to additional group so you should have used append option -a (and not editing the all bunch of groups names to your user).
sudo usermod -aG staff matt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Delete contents of textbox and automatically deleting another I have 2 input box fields, one linked to an autocomplete and the other is hidden
I have an action on select that takes the id of the selected item into the hidden field.
code:
$('#id_emp_name').autocomplete({
source: '/mycompany/employees.json',
minLength: 1,
dataType: 'json',
max: 12,
select: function(event, ui) {
$('#id_emp_id').val(ui.item.id);
}
});
I want to change it so that whenever I delete contents (even a single character) on the autcomplete textbox it would set the hidden textbox's to ''
A: Would this work for you?
$('#id_emp_name').autocomplete({
source: '/mycompany/employees.json',
minLength: 1,
dataType: 'json',
max: 12,
select: function(event, ui) {
$('#id_emp_id').val(ui.item.id);
}
}).keyup(function(){
$('#id_emp_id').val('');
});
You may need to put some conditions on it of course.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: undefined variable javascript - lightbox im trying to open a lightbox when webpages loads using the javascript library "lytebox"
here is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="lytebox.js"></script>
<link rel="stylesheet" href="lytebox.css" type="text/css" media="screen" />
<script>
function ShowIntro()
{
$lb.launch('example.jpg','showPrint:true','Orion Nebula','This is my description, which is optional');
}
</script>
</head>
<body onLoad="ShowIntro()">
</body>
</html>
the code works fine on firefox and chrome, but on internet explorer 8 it doesn't works and I get the following error:
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
Timestamp: Sat, 24 Sep 2011 05:10:04 UTC
Message: '$lb' is undefined
Line: 12
Char: 3
Code: 0
URI: file:///C:/Users/User/Desktop/lytebox_v5.1/lytebox.html
How can I fix it?
p.s. im using lytebox because it doesnt need jquery, and i dont want cause conflicts with other parts on my page (like "videolightbox")
A: Here's a guess: Lytebox uses window.onload itself in order to set up the $lb variable (you can see this at the very end of the script), and when you do <body onload"..."> you're basically clobbering Lytebox's window.onload function before it has a chance to fire. Here's another SO question that seems to confirm this behavior in IE.
So, how do you add an onload event when Lytebox needs its own? Simon Willison actually came up with a solution seven years ago in a rather classic article. In your case his advice is straightforward to implement:
<body><!-- no onload --->
<script>
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = ShowIntro;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
ShowIntro();
}
}
</script>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: multi-column ListView onClickListener responds to a column in a row? In Android ListView it has OnItemClickListener() which responds to a ROW I clicked. But what if my ListView has multicolumn and I want to have an event that responds to a column in a row?
A: In your getView(...) of your listadapter simply use setOnClickListener() on what makes up the columns in you list row - ie as the row was a normal layout outside the listview.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to add textfield and button programmatically? I have a tableView and I want to apply search facility on tableView. For that I require textField and search Button but I don't know how to create these programmatically. so plz tell me how to create these two tools.
thanx.
A: Try with the following link which describes for asynchronous scrollbar example
http://blog.patrickcrosby.com/2010/04/27/iphone-ipad-uisearchbar-uisearchdisplaycontroller-asynchronous-example.html
But you can also refer the previous post
UISearchBar Sample Code
For more methods of implementing and getting results as you type, go to apples document and refer UISearchBarDelegate Protocol Methods
A: Here's the documentation for UITextField and UIButton. You might also find UISearchBar useful, which incorporates both a text field and a button.
Add your views to the table view's header view.
A: You have a table delegate tableview:cellForRowAtIndexPath. In this delegate add the following code.
//Suppose you want to add textfield and button at the first row
if(indexPath.Row == 0)
{
UITextField *txtSearch = [UITextField alloc] initWithFrame:CGRectMake(0,0,150,35)];
UIButton *btnSearch = [UIButton buttonWithType:UIButtoTypeCustom];
btnSearch.frame = CGRectMake(160,0,50,35);
[[cell contentView] addSubView:txtSearch];
[[cell contentView] addSubView:btnSearch];
}
Also You can add event for button like
[btnSearch addTarget:self action:@selector(eventName) forControlEvents:UIControlEventTouchUpInside];
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to allow abstraction in MVC while maintaining SOC? I'm refactoring a large web game, and making some models to represent my database objects (you read that right - there were none before.) Now I know that traditionally subclassing of models isn't really done because it can be tricky, but it seems to fit what I'm doing. Some of my tables represent things of which there can be a few closely related types. For example, an attack launched against another player can take a few forms, but they share almost all of their db information. So there's just a single field in the table distinguishing type.
To represent these in code, I have an abstract class Attack, and the subtypes defined. It works fine; that's not the problem. The problem I'm having is how I should refactor the UI part of them. Each type displays slightly differently.
On the one hand, in any other app, the different subtypes would overload a method to describe how they display their information. That would be the proper use of polymorphism. But this is MVC we're talking about. Putting UI code in the models is a mortal sin! But if I leave it where it should be, I have to have extra cruft like switching on subtypes, and now I'm violating LSP!
How can I reconcile this conflict between design principles? Is this why subclassing models is discouraged?
PS I'm sure the title of this question could be much better, I just couldn't describe it succinctly. Feel free to revise.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can add Tab widget to the botton in android? I am working on android, i want to add tab widget to the bottom of page. this is the code of my xml file:-
<HorizontalScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:scrollbars="none">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="0dip" android:layout_marginRight="0dip"
android:layout_alignParentBottom="true"/>
</HorizontalScrollView>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</RelativeLayout>
by this code the tabwidget is adding to the top of the layout as shown in below picture:-
please tell what should i so to add these "Albums" tabWidget ?
Thank you in advance...
A: here is code for bottom tab,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_weight="1"/>
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
</LinearLayout>
A: This is the correct way to do this.
<RelativeLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp">
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:layout_alignParentTop="true"
android:layout_above="@+id/ScrollView01"/>
<HorizontalScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:scrollbars="none" android:layout_alignParentBottom="true">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dip" android:layout_marginRight="0dip"
android:layout_alignParentBottom="true"/>
</HorizontalScrollView>
</RelativeLayout>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: fastest way to split a text file at spaces in Javascript I'm looking at doing some text processing in the browser and am trying to get a rough idea of whether I am going to be CPU bound or I/O bound. To test the speed on the CPU side of the equation, I am seeing how quickly I can split a piece of text (~8.9MB - it's Project Gutenberg's Sherlock Holmes repeated a number of times over) in Javascript once it is in memory. At the moment I'm simply doing:
pieces = theText.split(" ");
and executing it 100 times and taking the average. On a 2011 Macbook Pro i5, the average split in Firefox takes 92.81ms and in Chrome 237.27ms. So 1000/92.81ms * 8.9MB = 95.8MBps on the CPU, which is probably a little faster than the harddisk I/O, but not by much.
So my question is really three parts:
*
*Are there Javascript alternatives to split() that tend to be faster when doing simple text processing (e.g. splitting at spaces, newlines, etc. etc.)?
*Are the lackluster CPU results I'm seeing here likely due to fundamental string matching/algorithmic constraints, or is the Javascript execution just slow?
*If you think Javascript is likely the limiting factor, can you demonstrate substantially better performance on a comparable machine/comparable text in any other programming language?
Edit: I also suspect this could be sped up with WebWorkers, though for now am primarily interested in single-threaded approaches.
A: As far as i know split with for loop is the fastest way to do simple text processing in javascript. It is faster than regex, here is the link to jsperf http://jsperf.com/query-str-parsing-regex-vs-split/2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to set permalink of your blog post according to date and title of post? I am having this website http://www.finalyearondesk.com . My blogs post link are set like this.. http://www.finalyearondesk.com/index.php?id=28 . I want it to set like this ... finalyearondesk.com/2011/09/22/how-to-recover-ubuntu-after-it-is-crashed/ .
I am using the following function to get these posts...
function get_content($id = '') {
if($id != ""):
$id = mysql_real_escape_string($id);
$sql = "SELECT * from cms_content WHERE id = '$id'";
$return = '<p><a href="http://www.finalyearondesk.com/">Go back to Home page</a></p>';
echo $return;
else:
$sql = "select * from cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) != 0):
while($row = mysql_fetch_assoc($res)) {
echo '<h1><a href="index.php?id=' . $row['id'] . '">' . $row['title'] . '</a></h1>';
echo '<p>' . "By: " . '<font color="orange">' . $row['author'] . '</font>' . ", Posted on: " . $row['date'] . '<p>';
echo '<p>' . $row['body'] . '</p><br />';
}
else:
echo '<p>We are really very sorry, this page does not exist!</p>';
endif;
}
And I am using this code to dispaly it on my index.php page...
<?php
if (isset($_GET['id'])) :
$obj -> get_content($_GET['id']);
else :
$obj -> get_content_summary();
endif;
?>
Any suggestions how to do this? And can we do this by using .htaccess?
A: The unfortunate thing about using mod_rewrite is that the data you are supplying in the form of a url is not the best way to query a database. But none the less you have year, month, day and title variables so you will need to rewrite your get_content function to query soomething like (depending on how you date is stored in the database.):
select * from cms_content
WHERE date='mktime(0,0,0,$month,$day,$year)'
AND title='$title'
ORDER BY id DESC
.htaccess would be something like:
RewriteRule ^(.*)/(.*)/(.*)/(.*)$ index.php?year=$1&month=$2&day=$3&title=$4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I get this form submit to work properly? The following code is what I am using to e-mail me the contents of a form.
I am having two problems with it and was hoping someone could help.
*
*I have checkboxes on the form, and when multiple boxes of the same
group are checked, the e-mail I receive only shows the last box that
was checked and not all that were checked.
*I have a <textarea> on
the form and it doesn't show up in the e-mail sent to me either.
The PHP code:
<?php
header('Location: thank-you.html');
$from = $_POST['email'];
$to = 'email@example.com';
$subject = "subject";
$message = "";
foreach ($_POST as $k=>$v)
{
if (!empty($message)) { $message .= "\n\n"; }
$message .= ucwords(str_replace('_',' ',$k)).": ".$v;
}
$headers = "From: $from";
mail($to, $subject, $message, $headers);
?>
A: you probably have checkbox groups like this:
<input type=checkbox name=box value='one'>
<input type=checkbox name=box value='two'>
when they should look like this (with square brackets after the name)
<input type=checkbox name=box[] value='one'>
<input type=checkbox name=box[] value='two'>
php will then store the values in an array in $_POST['box'], which you can then join into comma delimited string inside your existing print code somewere with implode(', ', $_POST['box']) for formatting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RewriteRule that will force a trailing slash Currently I have a folder [contact-us]
mydomain.com/contact-us/
Im planning to remove this folder and will just add a contact-us.php
mydomain.com/contact-us.php
How can I create a RewriteRule that will map
mydomain.com/contact-us/ -> mydomain.com/contact-us.php
(Note I want to force a trailing slash)
A: Use:
RewriteEngine On
RewriteRule ^contact-us$ http://domain.com/contact-us/ [R,L]
RewriteRule ^contact-us/?$ /contact-us.php [NC,QSA,L]
This way is someone type: contact-us or contact-us/ it will go to your contact-us.php
A: RewriteRule ^contact_us/$ /contact_us.php [QSA]
I can't remember if you need a / at the start, so if this doesn't work try ^/contact_us/$
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What will be the fastest way to access an element from a collection? What will be the fastest way to access an element from a collection?
I am thinking should be in the order (low to high):
Indexing an Array <= indexing a collection/list <= use key on Dictionary
But I am not sure...
1) Is indexing an array has same speed as indexing a list?
2) And will the indexing speed will grows as the size of the array/list grows?
From my understanding... indexing array should kind of using a pointer to point to the index of the element, which is caculated by the element size. So it should has same speed as indexing collection/list?
From what I know if we use Dictionary to look for a value, the speed of getting a value will grows as the size of Dictionary grows.
3) I just wonder what will be the fastest way to access an element from a collection?
Have been wondering for long time is my assumption is correct :)
Thanks
A: The amortized cost of finding an element by key with a Dictionary is O(1) or constant (also see "Resizable hash tables and amortized analysis" for the CS fundamentals). The underlying data structure is not an array or list, but a hashtable - given an appropriate hashing function the speed of accessing a value cost does not grow significantly larger (hence is constant) with the number of elements, unless many or most of those elements have the same hash code.
A: In C# a List is backed by an array, so both an array and a list/collection can access elements by indexing in O(1) time. Performance for a Dictionary is similar because it is backed by a hash table. However, it should be noted that the performance of access on a hash table is relative to the quality of the hash function and the number of collisions which occur in a particular data set. In C#, each type may override GetHashCode(), which will determine the hash function and thus the performance of accessing such an object within a particular set of such objects in a dictionary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need help understanding etree xml for python working with tag structure i'm having some problems to unterstand the python etree library to read a xml file.
I pretty new with programming in python...so xml is kind of kinky for me...
I have the following xml structure in a file:
<sss version="1.2">
<date>2011-09-23</date>
<time>12:32:29</time>
<origin>OPST</origin>
<user></user>
<survey>
<name>Test</name>
<version>2011-09-02 15:50:10</version>
<record ident="A">
<variable ident="10" type="quantity">
<name>v_682</name>
<label>Another question</label>
<position start="23" finish="24"/>
<values>
<range from="0" to="32"/>
</values>
</variable>
<variable ident="11" type="quantity">
<name>v_683</name>
<label>another totally another Question</label>
<position start="25" finish="26"/>
<values>
<range from="0" to="33"/>
</values>
</variable>
<variable ident="12" type="quantity">
<name>v_684</name>
<label>And once more Question</label>
<position start="27" finish="29"/>
<values>
<range from="0" to="122"/>
</values>
</variable>
<variable ident="20" type="single">
<name>v_685</name>
<label>Question with alternatives</label>
<position start="73" finish="73"/>
<values>
<range from="1" to="6"/>
<value code="1">Alternative 1</value>
<value code="2">Alternative 2</value>
<value code="3">Alternative 3</value>
<value code="6">Alternative 4</value>
</values>
</variable>
</record>
</survey>
</sss>
to read elements i developed a pretty bad loop, that does not match the capabilities of the etree library i guess...
from xml.etree.cElementTree import parse
et = parse(open('scheme.xml','rb'))
root = et.getroot()
for i in range(4):
a= str(root[4][2][i][0].text)
if a.startswith('v'):
print root[4][2][i][1].text
How can i make use of the tag structure: for instance to read the "value" tag for appending the text into a list?
For me these etree tutorials are pretty difficult to gasp...maybe someone can show me how to use a tag based search...? These loops are so fragile...
Thanx a lot
A: If the file is small and you only need <value/> elements:
#!/usr/bin/env python
import xml.etree.cElementTree as etree
tree = etree.parse('scheme.xml')
for value in tree.getiterator(tag='value'):
print value.get('code'), value.text
If the file is large:
def getelements(filename, tag):
context = iter(etree.iterparse(filename, events=('start', 'end')))
_, root = next(context) # get root element
for event, elem in context:
if event == 'end' and elem.tag == tag:
yield elem
root.clear() # free memory
for elem in getelements('scheme.xml', 'value'):
print elem.get('code'), elem.text
Output
1 Alternative 1
2 Alternative 2
3 Alternative 3
6 Alternative 4
To find out more, read Searching for Subelements and The ElementTree XML API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parsing sequential ASCII file for editing - Visual C# I have been recently assigned a task in which I need to create a program to edit files in Visual C#. The file is a sequential ASCII text file with multiple fixed character width rows, and the basic structure looks like this:
Each group is a single parameter, and there can be hundreds of these within a file. Each PA has a set number of columns, but each PA varies in column numbers. Additionally, there are some optional fields within each record, so that accounts for the extra spaces between some of the fields. Each field also has a separator of 1 space. I am unsure if I am being too thorough, but I figure the more information I give, the easier it will be for someone to help me.
Essentially, I want to create a GUI in which the user can select one a parameter mnemonic and then be able to edit any of the fields within the entire group of parameters
I have a little C# experience, but I am having trouble figuring out what would be the best way to accomplish this. My initial thinking was to parse the file into an array, search for each parameter name (maybe using regular expressions?), display all the parameter names in a browser. From there the user would be able to select which parameter they wish to edit. The program would then search the array again for the selected parameter, and then parse the records into text boxes, to allow for editing.
I am unsure if this is the most efficient way of accomplishing this, and I am somewhat stuck on how to actually parse the file to read the fields into the text boxes. I have searched many different forums for file parsing, but most of the topics I find related to comma delimited files which does not really apply to the file type I am working with. Any help would be greatly appreciated, and if you need me to elaborate on anything, please feel free to ask me. Thank for the help.
A: This isn't C# advice, but more general programming advice. If I were you, I would create a class to represent each PA you have, and have them each inherit from the interface IPAObject (or something like that). That way you can treat them as subtypes of a abstract PA object.
Then, I would make an class called PAGroup, which holds an array of IPAObject's.
Each individual concrete PA object class would then have fields for each parameter it has, and can be responsible for serializing itself to or deserializing itself from a stream (in your case, this stream is probably an input or output file), using C# file API's. You could use regular expressions, but since each PA object has fixed-length lines, you might as well read the line in all at once, using ReadLine() and parse it using array operations, like you said yourself. If you go this route, my advice to you is to store offsets for each columns starting offset and length in each class object, rather than littering your code with a whole bunch of literal numbers.
These classes would also each contain the logic for what their columns are and how to modify that data. Some of your columns seem open ended, so they would probably just be represented by strings. Others look like they come from a finite list of choices. These would probably be represented by constants, which belong to the relevant PA object class. The class would be responsible for converting the constants and other object to and from the actual ASCII representation from the file.
This way, when you read the whole PA file, you end up with a nice hierarchical data structure that represents the structure of your file, and from a coding perspective, all of the logic is separated very nicely, which makes it very easy to maintain. This nice data structure could serve as the model in your model-view-controller architecture. Then you just need to worry about implementing the user interface for interacting with your data.
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTC OpenSense SDK repository.xml url link Anyone knows HTC OpenSense SDK repository.xml url link?I'm not ok to download HTC OpenSense SDK.After downloaded file,I got only incomplete damage zip file.
A: Direct repository link not available. Just follow the steps.
*
*Download HTC Open Sense from here (Requires registration) Just a 10 MB ZIp file
*Unzip download to reveal 5 files, README.txt, 2 add-on zip files and 2 corresponding repository xml files used for installing the and tablet add-on extensions.
(Do not unzip the extension Add-on zip files, these are installed using the Android SDK and AVD Manager.)
The following steps illustrate installing the phone add-on extension. The same applies to the tablet add-on extension.
Click on Add Add-on Site for the HTC SDK Add-ons and specify a file:// URL pointing to the xml file for the Add-on site.
For example, on Windows:
file:///c://addon_htc_phone.xml
Now just create your AVD for the HTC Phone extension and enjoy !!
A: You can add the following repository to the user defined sites in the AVD manager.
http://dl.htcdev.com/apis
You can get more details at HTC's own site: http://www.htcdev.com/devcenter/opensense-sdk/download-install
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to skip precompilation of unused vendor assets In Rails 3.1 "rake assets:precompile" precompiles all separate .css and .js that are in vendor/assets/.. folders. For example, it creates separate precompiled files for jquery, jqueryui libraries and all other files from "vendor" folder.
My web site only references application.css and application.js. Why does it precompile every single vendor asset as a separate file? I am not using those files directly. Is there a way to remove those vendor files from precompilation list?
My concern is that it takes extra time and disk space to precompile those files that I will never use in production.
A: This is actually a bug in 3.1.
The regex that is used to capture assets to precompile was a little to broad and was including files that it wasn't supposed to.
This is fixed in in 3-1-stable, but is after the 3.1.1 RC1 tag so will probably be in 3.1.2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cant find the newline character in a file (java) I am trying to get the last line of a file, but my output shows that it never finds it. I also tried looking for "[" which all the lines start with, but unless the jumps were perfect the program will not skip "[". I tried looking for "\r\n", System.getProperty("line.separator"), \r and \n. Most probably its a dumb mistake, but if I had it and I couldn't find it, then someone else may run into it too.
RandomAccessFile raf = new RandomAccessFile(fileLocation, "r");
//Finds the end of the file, and takes a little more
long lastSegment = raf.length() - 5;
//**Looks for the new line character \n?**
//if it cant find it then take 5 more and look again.
while(stringBuffer.lastIndexOf("\n") == -1) {
lastSegment = lastSegment-5;
raf.seek(lastSegment);
//Not sure this is the best way to do it
String seen = raf.readLine();
stringBuffer.append(seen);
}
//Trying to debug it and understand
int location = stringBuffer.lastIndexOf("\n");
System.out.println(location);
FileInputStream fis = new FileInputStream(fileLocation);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
BufferedReader br = new BufferedReader(isr);
br.skip(lastSegment);
System.out.println("br.readLine() " + br.readLine());
}
The idea from the code comes from
Quickly read the last line of a text file?
The file I use is this
http://www.4shared.com/file/i4rXwEXz/file.html
Thanks for the help, and if you see any other places where my code could be improve let me know
A: It is just because you are using readline.
It returns you the line String without the newline character whatever it was (CR/LF/CRLF).
The Javadoc or RandomAccessFile#readLine() says:
A line of text is terminated by a carriage-return character ('\r'), a newline character ('\n'), a carriage-return character immediately followed by a newline character, or the end of the file. Line-terminating characters are discarded and are not included as part of the string returned.
If you try to find the last line, you can read you file until its end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rails 3.1.0, geokit, with error acts_as_mappable I am getting the
undefined local variable or method `acts_as_mappable'
error when using geokit, and after tons of Goggling and attempts, I cannot seem to be able correct the problem.
Basically, I have the following gems installed:
geokit (1.6.0, 1.5.0)
geokit-rails31 (0.1.3)
and have the following in my model
class House < ActiveRecord::Base
acts_as_mappable
end
and Gemfile:
gem 'geokit', '>= 1.5.0'
gem 'geokit-rails31'
I get the error with or without doing the following in my local app.
rails plugin install git://github.com/jlecour/geokit-rails3.git
A: Okay - Here is the solution for anyone that needs help on how I got it to work...
Make sure your project Gemfile does not contain any geokit info of any kind.
install geokit
> gem install geokit
> gem list geo
*** LOCAL GEMS ***
geokit (1.6.0, 1.5.0)
uninstall geokit-rails3 and geokit-rails31
> gem uninstall geokit-rails31 geokit-rails3
in your project, at the root level:
> rails plugin install git://github.com/jlecour/geokit-rails3.git
edit the spec
> vi vendor/plugins/geokit-rails3/geokit-rails3.gemspec
change rails dependency line to be
s.add_runtime_dependency 'rails', '>= 3.1.0'
now, edit the Gemfile to include the gem
gem 'geokit-rails3', :path => 'vendor/plugins/geokit-rails3'
Note, the Gemfile only contains an entry for the geokit-rails3, and no entries for normal geokit gem. i.e. there is not a "gem 'geokit', '>= 1.5.0'" entry
then in your application root, do a
bundle install
It should be setup, and you can now follow a typical tutorial - as described in the git instructions
https://github.com/jlecour/geokit-rails3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VS10 Additional library directories fails when using a relative path When I set up my project with relative paths, it fails.
// Does not work
properties-linker-general-additional library directories
..\..\libraries
// works fine
C:\Users\NAME\Desktop\project\libraries
How do I get the relative paths to work?
A: Try making it relative to your project directory or solution directory (as appropriate). I avoid playing guessing games with my current directory. Use the convenient variables defined by Visual Studio to avoid hard coding a path.
$(ProjectDir)\..\..\libraries
or
$(SolutionDir)\..\..\libraries
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Binary search tree insertion Need help to figure out why the following code for basic Binary Search Tree insertion is not working. Since I have been working on C# for sometime now, I'm afraid I forgot some of my C++. Also, any suggestions to improve coding style would be very helpful. (I know I'm not freeing memory as of now)
struct Node
{
int data;
Node* lChild;
Node* rChild;
Node(int dataNew)
{
data = dataNew;
lChild = NULL;
rChild = NULL;
}
};
class BST
{
private:
Node* root;
void Insert(int newData, Node* &cRoot) //is this correct?
{
if(cRoot == NULL)
{
cRoot = new Node(newData);
return;
}
if(newData < cRoot->data)
Insert(cRoot->data, cRoot->lChild);
else
Insert(cRoot->data, cRoot->rChild);
}
void PrintInorder(Node* cRoot)
{
if(cRoot != NULL)
{
PrintInorder(cRoot->lChild);
cout<< cRoot->data <<" ";;
PrintInorder(cRoot->rChild);
}
}
public:
BST()
{
root = NULL;
}
void AddItem(int newData)
{
Insert(newData, root);
}
void PrintTree()
{
PrintInorder(root);
}
};
int main()
{
BST *myBST = new BST();
myBST->AddItem(5);
myBST->AddItem(7);
myBST->AddItem(1);
myBST->AddItem(10);
myBST->PrintTree();
}
A: It appears to me that
Insert(cRoot->data, cRoot->lChild);
should instead be
Insert(newData, cRoot->lChild);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I save a textarea value to a Rails session? I have a form with one input field -- a textarea -- and when the user submits the form I want to save the value of the textarea to the session. How do I do that, in Rails?
I'm using Devise, and the page I'm sending the user to after they submit the form is my Devise registration page.
So I imagine I need something like this in the registrations controller action:
session[:text_entered] = params()
...but Devise doesn't give me a registrations controller. Do I need to make one?
Am I stuck with a super long URL when the form gets submitted? Should this be a POST or a GET? How do I pass the textarea value to the registrations page without sending it as a URL parameter?
Sorry I'm a newbie. Thanks for any help!
A: So, you have a controller for the page that the textarea is on, let's call it "SomethingsController." And the controller the form on that page submits to is, I gather, RegistrationsController. Instead of handling the submission of that form in RegistrationsController, what I would do is let SomethingsController handle it.
When you POST the form to SomethingsController (and yes, you should POST) it will fire the create action, and there you'll get the value from params (which is a Hash--you access its values with []) and put it in session. Once you've done that you can redirect the user to the registration page. Something like this:
SomethingsController < ActionController::Base
def create
if text = params[:text_area_name] && text.present?
session[:text_entered] = text
redirect_to new_user_registration_path
else
flash[:error] = "You didn't enter any text!"
render :action => :new
end
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How does R handle object in function call? I have background of Java and Python and I'm learning R recently.
Today I found that R seems to handle objects quite differently from Java and Python.
For example, the following code:
x <- c(1:10)
print(x)
sapply(1:10,function(i){
x[i] = 4
})
print(x)
The code gives the following result:
[1] 1 2 3 4 5 6 7 8 9 10
[1] 1 2 3 4 5 6 7 8 9 10
But I expect the second line of output to be all '4' since I modified the vector in the sapply function.
So does this mean that R make copies of objects in function call instead of reference to the objects?
A: Yes, you're right. Check the R Language Definition: 4.3.3 Argument Evaluation
AFAIK, R doesn't really copy the data until you're trying to modify it, thus following the Copy-on-write semantics.
A: The x that is inside the anonymous function is not the x in the global environment (your workspace). It is a copy of x, local to the anonymous function. It is not so simple to say that R copies objects in function calls; R will strive to not copy if it can, though once you modify something R has to copy the object.
As @DWin points out, this copied version of x that has been modified is returned by the sapply() call, your claimed output is not what I get:
> x <- c(1:10)
> print(x)
[1] 1 2 3 4 5 6 7 8 9 10
> sapply(1:10,function(i){
+ x[i] = 4
+ })
[1] 4 4 4 4 4 4 4 4 4 4
> print(x)
[1] 1 2 3 4 5 6 7 8 9 10
Clearly, the code did almost what you thought it would. The problem is that the output from sapply() was not assigned to an object and hence is printed and thence discarded.
The reason you code even works is due to the scoping rules of R. You really should pass in to a function as arguments any objects that the function needs. However, if R can;t find an object local to the the function it will search the parent environment for an object matching the name, and then the parent of that environment if appropriate, eventually hitting the global environment, the work space. So your code works because it eventually found an x to work with, but was immediately copied, that copy returned at the end of the sapply() call.
This copying does take time and memory in many cases. This is one of the reasons people think for loops are slow in R; they don't allocate storage for an object before filling it with a loop. If you don't allocate storage, R has to modify/copy the object to add the next result of the loop.
Again though, it isn't always that simple, everywhere in R, for example with environments, where a copy of an environment really just refers to the original version:
> a <- new.env()
> a
<environment: 0x1af2ee0>
> b <- 4
> assign("b", b, env = a)
> a$b
[1] 4
> c <- a ## copy the environment to `c`
> assign("b", 7, env = c) ## assign something to `b` in env `c`
> c$b ## as expected
[1] 7
> a$b ## also changed `b` in `a` as `a` and `c` are actually the same thing
[1] 7
If you understand these sorts of things, reading the R Language Definition manual which covers many of the details of what goes on under the hood in R.
A: x is defined in the global environment, not in your function.
If you try to modify a non-local object such as x in a function then R makes a copy of the object and modifies the copy so each time you run your anonymous function a copy of x is made and its ith component is set to 4. When the function exits the copy that was made disappears forever. The original x is not modified.
If we were to write x[i] <<- i or if we were to write x[i] <- 4; assign("x", x, .GlobalEnv) then R would write it back. Another way to write it back would be to set e, say, to the environment that x is stored in and do this:
e <- environment()
sapply(1:10, function(i) e$x[i] <- 4)
or possibly this:
sapply(1:10, function(i, e) e$x[i] <- 4, e = environment())
Normally one does not write such code in R. Rather one produces the result as the output of the function like this:
x <- sapply(1:10, function(i) 4)
(Actually in this case one could write x[] <- 4.)
ADDED:
Using the proto package one could do this where method f sets the ith component of the x property to 4.
library(proto)
p <- proto(x = 1:10, f = function(., i) .$x[i] <- 4)
for(i in seq_along(p$x)) p$f(i)
p$x
ADDED:
Added above another option in which we explicitly pass the environment that x is stored in.
A: You need to assign the output of sapply to an object, otherwise it just disappears. (Actually you can recover it since it also gets assigned to .Last.value)
x <- c(1:10)
print(x)
[1] 1 2 3 4 5 6 7 8 9 10
x <- sapply(1:10,function(i){
x[i] = 4
})
print(x)
[1] 4 4 4 4 4 4 4 4 4 4
A: If you want to change a "global" object from within a function then you can use non-local assignment.
x <- c(1:10)
# [1] 1 2 3 4 5 6 7 8 9 10
print(x)
sapply(1:10,function(i){
x[i] <<- 4
})
print(x)
# [1] 4 4 4 4 4 4 4 4 4 4
Although in this particular case you could just have it more compactly as x[]<-4
That is, by the way, one of the nice features of R -- instead of sapply(1:10,function(i) x[i] <<- 4 or for(i in 1:10) x[i]<-4 (for is not a function, so you don't need <<- here) you can just write x[]<-4 :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Raphael JS nested canvases? I'm using Raphael JS to draw vector graphics on a webpage, and I have a rectangle (Raphael.rect) that I'd like to use as a seperate canvas from its parent.
Is there any way to do this?
EDIT: I'd just draw in the rectangle like normal, but it wouldn't cut off the contents at its border.
A: You currently can not use a Raphael rect as the equivalent of a regular Raphael object: nesting is unfortunately not supported. What you will probably have to do is use the position of the rect as an offset for all your drawing operations that should appear inside the rect.
A: Apparently clip-rect works for this.
Oh the power of searching after all hope is lost.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Calling Console.WriteLine before allocating the console I've recently encountered the following problem with my application: it didn't show any console output, though the console had been allocated by using AllocConsole. I managed to figure out soon that it was caused by an attempt (hidden deeply in code) to write to the console before the AllocConsole was called. So it looked like this:
Console.WriteLine("Foo"); // no console allocated yet
AllocConsole(); // console window appears
Console.WriteLine("Bar"); // expecting "Bar" in the console, but the console is blank
So my question is: why does this happen? I don't see any exceptions (though I suppose they are there).
A: The first time you use Console.WriteLine, the Console class creates a TextWriter and associates it with the Console.Out property. The way it does this is to use Win32 to open the low-level file handle associated with the standard output file handle. If the standard output handle is invalid, Console.Out is set to TextWriter.Null, which discards all output.
The Win32 AllocConsole function, creates and sets the standard output handle so after calling it the standard output handle is either different or now valid. In either case, Console.Out has already been set either to use the old standard output or to discard all output.
To force a re-open of Console.Out after calling AllocConsole, you can use this method:
*
*Console.OpenStandardOutput
A: Probably because the static constructor of the Console class sets up the output stream the first time you call Console.WriteLine. Since there's no console attached, and therefore no standard output handle, output gets routed to the bit bucket. And when you call AllocConsole later, nothing in the Console class is notified that a console now exists. It doesn't have the opportunity to attach Console.Out to the newly created standard output handle.
A: A process can be associated with only one console, so the AllocConsole function fails if the calling process already has a console. And the console application is already has the console. See details in here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I change a label when other labels change? I am trying to make a label change when other 2 labels change. The 2 labels constantly change randomly.
Here's the code:if ([labes.text isEqualToString:@"haha"] && [alizz.text isEqualToString:@"hoho"]) {
laab.text = @"hello";
}
Maybe refreshing every 0.0005 seconds will work?
A: You Can try nstimer for call method in time intervel.
A: How you are changing other two labels? you can add some function that update you third label just after updating the other two.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What really makes up Direct Traffic in Google Analytics? My site has been getting substantial direct traffic for a while in Google Analytics. I had been assuming that it was mostly due to link shortened traffic from Twitter. However, after Twitter introduced t.co, and shortened links from Twitter started coming in as "referrer" I started taking a look at what might be the actual cause of my higher than expected direct traffic stats.
Here are some hypotheses of things contributing to direct traffic. Please feel free to shoot them down if it is impossible that they are being counted as direct traffic by Analytics.
*
*Google Chrome's url autocompletion.
*Desktop Twitter clients like Tweet Deck.
*Mobile clients for Twitter other than the official Twitter app.
*Links sent through Outlook and Gmail.
*Bookmarked pages.
*Right clicking and opening a link in a new window.
*People typing in the site url.
*Right clicking and opening a link in an incognito window.
*301 and 302 Redirects.
*Switching back and forth between http and https.
Any ideas? Can anybody think of any other sources that could potentially be contributing to a Google Analytics Direct Traffic? Is anything on my list flat out wrong?
A: What portion of the traffic is new customers and what portion is returning? I would look at the landing pages for clues. I believe the general thought is most if not all direct traffic is either typed in directly or from a bookmark, but I see a lot of new customers in my direct traffic so they must come from somewhere else...
A: I agree with most of the list but:
1) Google Chrome's url autocompletion: I don't think this loses the referral information, although I believe iOS has started removing all referral data from its Google searches.
6) Right clicking and opening a link in a new window: I just did this in chrome (to the Gordon Choi page) and opened up a new tab with right click, and it appeared as a referral
I've also discussed this topic here:
https://webmasters.stackexchange.com/questions/32978/a-lot-of-direct-none-traffic-in-google-analytics/33816#33816
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Write a custom syntax interpreter in java? I am about to begin coding a demo program for a lecture I'm about to give. I want to let each student in the class download this application, then be able to create instances of objects (and their graphical representations) interactively via a command line. I decided to write in java, not because it's the language I'm most familiar with, but because it's got easy graphics classes and I can be pretty sure that the jar is going to run on their computers.
Intro over. Now the question:
What is a good way to implement some custom command line syntax for this program? I want to use a simple, arbitrary syntax like:
CREATE Monster Bob;
Bob.jump();
LS Bob //to list Bob's methods or something.
LS CREATE //to list all the classes
First I'll spiel about what first came to mind when I thought of this problem.
I can imagine that I could have a set of maps in a tree type linkage. I could parse each key word as the key to the next map. So "CREATE Monster Bob" could be evaluated like
1) Search keyword map for key "CREATE". Return the value, which is a reference to the map of classes.
2) Search classes map for key "Monster". Return the value, which is a factory class implementing some interface Leaf that lets me know it is a leaf value (I'll check using instanceof).
3) Maybe the Leaf interface will contain a method called execute() that will do whatever it wants. In this case it would create an object of Monster, adding this object to a map called Objects with the name Bob. (This Leaf business sounds ugly but it could be cleaned up.)
Cool. But this statement is a little harder for me:
Bob.jump();
1)Search some map of objects for "Bob". Return some object implementing an interface with a method like "evaluate(String s)" and pass it the string "jump()"
2)Bob searches some internal map of methods for "jump()", then...? In c++ I would have the key be a pointer to the member function Monster.jump() which would be executed. But there is no such thing as a function pointer in java I don't believe. I have read you can use an anonymous class to accomplish this, though I haven't tried. Looks like it would work.
So, this will work, but is there a more elegant way to go about this? I've never written any type of interpreter before. I'd like to do it a nice way and learn something in the process if somebody has some tips. This seems like a potentially error prone way to do things if I'm not very structured, especially when Bob and every other object start parsing their own instructions and using anonymous functions. In addition, it looks like every class will need a runtime-ready interface besides its normal code.
I also don't know Java all that well, so if there are some spots where I might hit a brick wall, then I'd like to know too.
Thanks for the help in advance.
A: If you really not going to build a new programming language, you may just split commands into parts (using space as separator) and then perform a lookup for the first part:
CREATE Monster Bob; => create, monster, bob:
String operation = parts[0];
if(operation.equals(`create`)) {
String type = parts[1];
String name = parts[2];
// your logic here
} else if(operation.equals(`...`)) {
...
}
A: I would actually suggest using Python -- unless there is a really good reason not to.
This is because:
*
*Python has a really nice IDE/REPL called IDLE. I can't say enough about using a good Read-Eval-Print-Loop: the short feedback cycle is very good for learning/playing. Adventurous students might even jump right in!
*Graphics support is cross-platform and well-supported via TkInter.
*I find it a better language for beginners and/or non-programmers than Java. (Python actually is not my favorite language, but it is very beginner-friendly and again, has a very nice IDE/REPL.)
*It is much less work for you ;-)
This is how the Python code for the demo might look:
Bob = BigMonster()
Bob.jump()
dir(Bob)
dir(Monters)
Since all of this is just regular Python syntax there is no parsing -- just create a few classes, perhaps implement the __dir__ protocol, and everything is ready to go. If Java integration is a requirement there is also Jython, although I have never tried that with IDLE (or know if it's supported as such).
Happy coding.
An Image-based SmallTalk such as Sqeak is far more interactive than Python as the code is part of the persistent running environment. However, it takes some time to find a good image -- Squeak is hardly the best implementation, but it is free -- and learn the particular SmallTalk environment. Thus, while the integration can ultimately have big payouts it does take more acclimatization :)
But, alas, to pursue a simple parser in Java, these will be of interest:
*
*A lexer which turns the input text into a steam of tokens, and;
*And a recursive descent parser (this is a really easy parsing approach) which either
*
*Builds an AST (Abstract Syntax Tree) which can be walked (read: "run") later, or;
*Or "does stuff" right now (immediate evaluation)
A Simple Recursive Descent Parser is a Java crash-course introduction to the concepts above. Here is some code for a recursive-descent parser for "neutrino syntax", whatever that is -- look at the comments and how well a recursive-descent parser can match the EBNF grammar.
Now, it's "just" a matter of defining the semantic rules of this pseudo/mini-language and implementing it ;-)
Exploring the semantics/Java approach a little bit more (parts are just a simplification/re-statement of the original post):
CREATE Monster Bob
Would create a new MonsterObject. Some approaches might be:
*
*Create the object with reflection, or;
*a map of Factory classes (from String -> FactoryObject) as talked about, or;
*a simple static if-else-branch.
The result would be stored in in a "variable hash" which maps Name -> MonsterObject.
Bob.jump()
Parse this to [object Bob] [method jump] [p1], [p2], ..., [pn], look up the object in the "variable hash" and then:
*
*Use reflection to invoke a method, or;
*have a map (retrieved via a method of the MonsterObject) of Name -> MethodEvaluatorObject (e.g. has eval(Object ... params) method), or;
*call a method of the form eval(String action, String[] ... parameters) and have it use an if-else-branch to "do stuff" (note that the parameters, if any, are already separated out during the parsing).
LS Bob and LS Monster rely a good bit on how the previous two are implemented.
While Java does not have "function pointers", they can be emulated through the use of objects with a given interface (that is, the objects themselves function as the pointers). Functional Java has F/F2/.../F8 classes to attempt to handle this uniformly with generics. However, in Java there is usually a separate one-off interface (or class) created like Runnable with a single "action" method that is modified to accept the appropriate parameters and return the appropriate result (such as the MethodEvaluatorObjects or FactoryObjects).
If there are any specific questions about one of the topics (reflection, recursive descent, anonymous types, [emulated] closures, etc.), then feel free to ask another SO question with a specific focus. (And, as always, due-diligence in research pays off ;-)
A: Have you considered using a parser generator like ANTLR? It can produce parsers for many kinds of languages and output the parser in a variety of languages including Java. It could speed up your task considerably and the software is free (although the books are for sale, but hey, your time is worth something, right?).
http://en.wikipedia.org/wiki/ANTLR
On the other hand, you could probably roll your own parser for a simple language like PST is talking about, but I wouldn't overcomplicate it. Just make yourself a function to break up the file into string tokens (lexer), and another that requests a token at a time and determines what to do with it. If your language is simple, that might be enough.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Interactive console programming for c/c++? So I've written a small program which takes in commands by the users, and then displays the output (after connecting to a server). It's an interactive console of sorts.
However, after using the mongodb and redis command-line clients (which work interactively on the console/terminal), it seems that there must be a library somewhere which provides functionalities such as recording user inputs, accepting up/down keypresses to browse through command history, as well as tab completion framework (not sure how that one would work, but yeah).
What's an ideal library to use for such a thing?
A: The readline library is a common choice: http://www.gnu.org/s/readline
If you are more ambitious, ncurses gives you more control, but has less functionality to begin with and a steeper learning curve.
Edit:
icktoofay mentioned that readline is licensed under the GPL. If this is a problem for your software, tecla is an alternative licensed under an X11 style license, so it can be used in proprietary projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Why won't IRB work after I mistyped a string? I started to learn Ruby using IRB and wrote the wrong code below:
irb(main):001:0>"amefurashi".delete(aiueo")
I noticed it was missing a double-quote mark, and the prompt changed to:
irb(main):002:1"
I wrote the correct code:
irb(main):001:1"amefurashi".delete("aiueo")
but why won't it work?
A: The IRB lines that prompt you with > are for new statements.
When the prompt says " instead, that means you are inside a string, and IRB is expecting you to finish entering your text and close your string with another quotation mark.
It looks like what you are doing is trying to enter your statement again, before you get a new (>) prompt.
If you are stuck in the middle of an incorrect statement and want to start over, press Ctrl-C, then Enter and you will get a clean > prompt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Not Able to include header file? Hi I have created a project in vs 2005. I have created a header file A.h.
Similarly I have added A.cxx in a folder called implementation. In .cxx file I have included A.h.
I have used #include "A.h". But when I am compiling it is telling A.h not found.
A: You can include files one of two ways:
*
*As a relative path to your .cpp file (example assumes a.h is in a folder above your .cpp file)
#include "..\a.h"
*Or by adding the header location to your project include directories
Right click on project, goto properties, under configuration properties, goto VC++ Directories (add the path in the ";" separated list)
A: Is the header file A.h in the same directory as A.cxx? It needs to be, if you use the #include statement you mention above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How do I know that the image shown is cached? I am using timThumb that has a cache engine. As the script/tutorials say, you have to have a cache file with permission 0777. This is what I have already.
When an image is viewed in the page, using the below
timthumb.php?src=http://farm3.static.flickr.com/2340/2089504883_863fb11b0a_z.jpg
it creates a 9c9313eced007f38eb59791dad91edb1.jpg file in the cache folder.
I checked the image and it is the same I saw. On my next refresh, I view the page source and I get again
timthumb.php?src=http://farm3.static.flickr.com/2340/2089504883_863fb11b0a_z.jpg instead of the cached image.
My question is, shouldn't show a domain.com/9c9313eced007f38eb59791dad91edb1.jpg ?
This is the code I use http://codepad.org/pVzET9Dv ( It is a modified version to accept all domains )
Note: I tried it also with the official release, but again the same. Maybe it's how cache works, I don't know.. But if is so, how can I check that what I saw is the cached?
A: You have the wrong idea about the concept of caching here.
Notice that when a file is in the cache_dir, php checks whether the user has sent him the header HTTP_IF_MODIFIED_SINCE.
If the browser sends this header, then this means that the browser has a local copy of this file which has had a Last-Modified value of HTTP_IF_MODIFIED_SINCE when it was downloaded.
Now, if this date is the really the last modification date of the image, the server sends the header HTTP/1.1 304 Not Modified.
Notice the check in function show_cache_file.
One more thing, it seems php is re-sizing the image and saving the re-sized image in its own cache folder. So in this way, the re-sizing process is not repeated again.
I am not aware whether there is a browser that allows you to know if a displayed image is fetched from cache or downloaded. Anyway this is irrelevant since the user must be sure that it is the most recent image.
A: The URL timthumb.php?src=http://farm3.static.flickr.com/2340/2089504883_863fb11b0a_z.jpg
will not change. The logic of the script is like this:
I have been given a URL to an image "http://farm3.static.flickr.com/2340/2089504883_863fb11b0a_z.jpg"
Do I have a cached copy on disk that is not expired?
NO: go retrive the image from "http://farm3.static.flickr.com/2340/2089504883_863fb11b0a_z.jpg", write it to cache, then display it.
YES: read the file from the disk and display it.
So even though you are saying the image is here (through the query string parameter src=) "http://farm3.static.flickr.com/2340/2089504883_863fb11b0a_z.jpg" it doesn't mean the script actually retrieves it from there every time.
I would say the fact that your permissions are correct and cache files are being written to the folder, that is verification enough it is working.
Any kind of verification beyond this would be kind of a waste of time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: upload file to a folder in asp.net? if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs("C:\\Users\\Vinay\\Documents\\Visual Studio 2010\\WebSites\\Onlinedoctorsportal\\vini" +
FileUpload1.FileName);
Label10.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label10.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label10.Text = "You have not specified a file.";
}
//Stream obj = FileUpload1.FileContent;
//Session["file"] = obj;
//Response.Redirect("Form3.aspx");
}
}
what i want is to save the uploaded file to a folder named vini but it is showing the file but not saving it to the specified folder as shown please help
A: Firstly you need to escape your string literal that points to the directory
You can do this by adding an @ before the string, or by putting double backslashes.
FileUpload1.SaveAs(@"C:\Users\Vinay\Documents\Visual Studio 2010\WebSites\Onlinedoctorsportal\vini" + FileUpload1.FileName);
OR
FileUpload1.SaveAs("C:\\Users\\Vinay\\Documents\\Visual Studio 2010\\WebSites\\Onlinedoctorsportal\\vini" + FileUpload1.FileName);
Secondly, check that the user that your ASP.NET application pool process is running under has permissions to write to the specified folder.
A quick check to see if this is the problem is to impersonate your local admin account in your web.config file.
You can do this by configuring the impersonate tag as follows:
<identity impersonate="true"
userName="domain\user"
password="password" />
A: This is your answer Try it....
This is Button click event Code -
protected void Button1_Click(object sender, EventArgs e)
{
if (fu1.HasFile)
{
String filePath = "~/PDF-Files/" + fu1.FileName;
fu1.SaveAs(MapPath(filePath));
}
}
I this will solve your problem.
A: string x = "C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\"+FileUpload1.PostedFile.FileName;
System.Drawing.Image image = System.Drawing.Image.FromFile(x);
string newPath = FileUpload1.FileName;
image.Save(Server.MapPath(newPath)) ;
Image1.ImageUrl = "~//" + newPath ;
Image1.DataBind();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to persist data with Serializable interface in java android I have a problem that, I have a webservice which returns 3 arrays from JSON response. I want to persist those lists from one class to another in our android app with the help of Serializable interface and Setter and Getter Methods. But I don't know how to achieve this? Please help me out about this problem.
Thanks in advance
A: SharedPreferences or Sqlite can be the way you can use to store persist data.
You can use SharedPreferences for persist data between Activities.
Some examples for Shared Preferences
Example1
Example 2
Some examples for Sqlite
Example 1
Example 2
Example 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Auto-accept bluetooth pairing possible? In the Android 2.3.3 BluetoothChat example with with createInsecureRfcommSocketToServiceRecord() API, users are still prompted to accept the pairing request, even though no PIN code is presented.
Is there a way to automate Bluetooth pairing request without user intervention? Or is this never possible due to security concerns? I have been looking online for 2 days now and haven't really found much, so if anybody knows, please post.
Thanks!
A: So, I had this cuestion, if some one needs the answer to this working in android 4.4.2
IntentFilter filter = new IntentFilter(
"android.bluetooth.device.action.PAIRING_REQUEST");
/*
* Registering a new BTBroadcast receiver from the Main Activity context
* with pairing request event
*/
registerReceiver(
new PairingRequest(), filter);
and the code for the Receiver
public static class PairingRequest extends BroadcastReceiver {
public PairingRequest() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
try {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
//the pin in case you need to accept for an specific pin
Log.d("PIN", " " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",0));
//maybe you look for a name or address
Log.d("Bonded", device.getName());
byte[] pinBytes;
pinBytes = (""+pin).getBytes("UTF-8");
device.setPin(pinBytes);
//setPairing confirmation if neeeded
device.setPairingConfirmation(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and in the manifest file
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
and the broadcastReceiver
<receiver android:name=".MainActivity$PairingRequest">
<intent-filter>
<action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
<action android:name="android.bluetooth.device.action.PAIRING_CANCEL" />
</intent-filter>
</receiver>
A: Not with the standard API, no: if the MAC address is not already in the pairing database there will always be the prompt. I'm told that if you have a device that has been rooted and have public read/write access to the bluetooth service's DBus endpoint you can work around that but I've never seen that actually implemented.
A: i came across the same problem, i hope the following code will help:
firsly we need:
<receiver android:name=".broadcast.PairingRequest">
<intent-filter>
<action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
<action android:name="android.bluetooth.device.action.PAIRING_CANCEL" />
</intent-filter></receiver>
secondly we need the BluetoothDevice class, and:
public class PairingRequest extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals("ACTION_PAIRING_REQUEST")) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234");
device.setPin(pinBytes);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java: MouseEvent on transparent JPanel I have a LayeredPane with two JPanels, all in a JFrame. Both JPanels are set to be transparent with setOpaque(false). However, I would like to capture mouse events on the (top, if it makes a difference) transparent panel. Is this possible, or should I just do it from the underlying JFrame? (It would definitely work to capture from the JFrame; it just makes more logical sense to capture the events from the transparent frame).
A: You can capture mouse events on whichever JPanel has a MouseListener attached to it, and is not encumbered by components that also have MouseListeners added, and who are laying on or above the original JPanel. This looks like a situation perfect for creating a small test class that is the most simple of GUI's, that has none of the bells and whistles of your GUI, but that illustrates your problem and hopeful solution.
Also, please know that the transparency does not play into any of this at all except as a distraction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Property getter setter in C# I have a class library project. I have a property there like below. It's not a read only property
private Int32 ABC ;
public Int32 ABCD
{
set
{
this.ABC = value;
}
get
{
return this.ABC;
}
}
My question is, Is it necessary to declare the private variable for the same and the getter / setter ?
EDIT
I mean could it be like below ?
public Int32 ABCD {}
A: Automatic property declarations require the get; set; statements in the braces (which is what you had in your original question):
public Int32 ABCD { get; set; }
An empty property block isn't valid.
A: Use auto-implemented properties introduced in C# 3.0 (VS 2008) or later.
http://msdn.microsoft.com/en-us/library/bb384054.aspx
public Int32 Abcd {get;set;}
The compiler creates the backing field for you. However it is anonymous and cannot be accessed. If later on you find the need to access the backing field, you can explicitly declare it and reimplement the getter and setter using that field without breaking your interface.
A: Use auto implemented property, It interduced from 2008 :
public Int ABCD
{
set;
get;
}
But difference is default value, i.e in property with backing field you can set a default value in variable but in this case default is .net defaults. (in fact you should initiate it in constructor for default value).
A: If you do the second choice, C# will create the first one for you.
A:
Is it necessary to declare the private variable for the same and the getter / setter ?
If you mean is it necessary to use the private variable then yes, it is (unless you use the automatic method mentioned by BoltClock).You should keep in mind that it is a full code block, so you can do pretty much anything you like in there - although you should do it within reason, as you don't want anything that is going to slow down the access to the properties too much.
For example, there can be side effects to changing a property, i.e. another property may have to be updated, or you may have to notify that other properties have changed as well.
If you are not notifying or doing anything else, then the automatic getter/setter method is the quicker to develop (that is not claiming it is the fastest (or slowest) to execute though).
A: you can do like this
public string ABCD { get;set;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access phpMyAdmin on Ubuntu LAMP I have installed all LAMP, and phpMyAdmin too. But how do I access phpMyAdmin via my browser? Which URL do I need to open?
A: you should probably see these instructions
https://help.ubuntu.com/community/phpMyAdmin
but phpmyadmin must be at /usr/share/phpmyadmin
A: Since you are on ubuntu, try which phpmyadmin and then set your search paths accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WPF Toolkit Data Grid , Selected Item Prevent changing
*
*I have a WPF Toolkit DataGrid,
*First Item is selcted
*User clicks on any other item on the Grid
*I do some validations (any validation on selection change event of the WPF Toolkit DataGrid)
*If validations returns false
*I want prevent User from changing the previously selected Item
*I tried saving previous index in a variable and set it again but it's not working
A: look at ICollectionView event Currentchanged, Currentchanging and the MoveCurrentTo methods.
this.MyGridItemsSource = new ObservableCollection<MyDataItems>();
this.view = (ICollectionView)CollectionViewSource.GetDefaultView(this.MyGridItemsSource)
this.view.CurrentChanging += your eventhandling goes here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: webserivce messages in listview with smileys I am working on a chat application with smileys. I have a image button that shows a pop up of smileys in grid view when clicked. I can select any smiley in that and it will get displayed in Edit Text.
My problem is : Now i have smiley image and text in my edittext. when i click on send i need to display this message with smiley in listview. Is it possible to display images with text in listview where i get mesages from webservice.
List view is used here as a place to display messages from web service. How can i work further in this.
Please guide me in this issue.
Regards,
Raghav Rajagopalan
A:
Is it possible to display images with text in listview where i get mesages from webservice.
*
*Yes it is possible of course. If you are using some complex way to get the messages from the webservice into the adapter, you must integrate this with sending these to the adapter.
Is it possible to send images to webservice and fetch them back in my listview. I am using .Net web service. I return XML from web service as my response.
*
*Don not do that. Put your smileys in drawable or download them only once. Use your own tags inside text for smileys. For example when string :) occurs put a smiley.
I created a Db and added 4 fields to it: ID , Position, Special Character, URL. So i was able to display the corresponding specialcharcter when clicked. When i submit how can i convert that specialcharcter into smiley image. I tried to use functions like "Contains()" and "Replace". But nothing worked when i submited the message to listview. I get the same specialcharcter and text. I don get the image instead of specialcharcter. Please guide me
*
*I suppose you are inserting the message inside a textView. You can use to replace the occurances of the special character with "<img src=\"the source\" />"
*Use this to get the image shown setText(Html.fromHtml("hi how are you <img src=\"yourimage.png\" />"));
*To replace :) with <img src=\"yourimage.png\" />.. use yourString.replaceAll(":)","<img src=\"yourimage.png\" />");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to return a Bool from a Where Filter using Entity Framework and Esql I use c# and ef4.
I have a Model with an Entity with two proprieties int Id and string Title.
I need to write an ESQL query that is able to return bool TRUE if Id and Title are present in the DataSource. Please note Id is a PrimaryKey in my data storage.
Any idea how to do it?
A: You can do it by each code-snippets below:
1)
using (YourEntityContext context = new YourEntityContext ()) {
var queryString =
@"SELECT VALUE TOP(1) Model FROM YourEntityContext.Models
As Model WHERE Model.Id = @id AND Model.Title = @title";
ObjectQuery<Model> entityQuery = new ObjectQuery<Model>(queryString, context);
entityQuery.Parameters.Add(new ObjectParameter("id", id));
entityQuery.Parameters.Add(new ObjectParameter("title", title));
var result = entityQuery.Any();
}
2)
using (YourEntityContext context = new YourEntityContext ()) {
ObjectQuery<Model> entityQuery =
context.Models
.Where("it.Id = @id AND it.Title = @title"
, new ObjectParameter("id", id)
, new ObjectParameter("title", title)
);
var result = entityQuery.Any();
}
3)
var context = new YourEntityContext();
using (EntityConnection cn = context.Connection as EntityConnection) {
if (cn.State == System.Data.ConnectionState.Closed)
cn.Open();
using (EntityCommand cmd = new EntityCommand()) {
cmd.Connection = cn;
cmd.CommandText = @"EXISTS(
SELECT M FROM YourEntityContext.Models as M
WHERE M.Id == @id AND Model.Title = @title
)";
cmd.Parameters.AddWithValue("id", _yourId);
cmd.Parameters.AddWithValue("title", _yourTitle);
var r = (bool)cmd.ExecuteScalar();
}
}
4)
using (YourEntityContext context = new YourEntityContext ()) {
var queryString =
@"EXISTS(
SELECT M FROM YourEntityContext.Models as M
WHERE M.Id == @id AND Model.Title = @title
)";
ObjectQuery<bool> entityQuery = new ObjectQuery<bool>(queryString, context);
entityQuery.Parameters.Add(new ObjectParameter("id", id));
entityQuery.Parameters.Add(new ObjectParameter("title", title));
var result = entityQuery.Execute(MergeOption.AppendOnly).FirstOrDefault();
}
4 is the best way I suggest you. Good lock
A: What javad said is true, but another way is:
bool result = entities.Any(x=>x.Id == id && x.Title == title) ;
In fact because Id is primary key, DB prevent from occurrence of this more than one time .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Copying sets Java Is there a way to copy a TreeSet? That is, is it possible to go
Set <Item> itemList;
Set <Item> tempList;
tempList = itemList;
or do you have to physically iterate through the sets and copy them one by one?
A: Starting from Java 10:
Set<E> oldSet = Set.of();
Set<E> newSet = Set.copyOf(oldSet);
Set.copyOf() returns an unmodifiable Set containing the elements of the given Collection.
The given Collection must not be null, and it must not contain any null elements.
A: With Java 8 you can use stream and collect to copy the items:
Set<Item> newSet = oldSet.stream().collect(Collectors.toSet());
Or you can collect to an ImmutableSet (if you know that the set should not change):
Set<Item> newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());
A: Java 8+:
Set<String> copy = new HashSet<>(mySet);
A: The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from).
When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:
findbugs says
The entrySet() method is allowed to return a view of the underlying
Map in which a single Entry object is reused and returned during the
iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so.
When iterating through such a Map, the Entry value is only valid until
you advance to the next iteration. If, for example, you try to pass
such an entrySet to an addAll method, things will go badly wrong.
As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.
Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:
Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));
Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.
A: Another way to do this is to use the copy constructor:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);
Or create an empty set and add the elements:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);
Unlike clone these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.
Note that the result of copying a Set is a new Set containing references to the objects that are elements if the original Set. The element objects themselves are not copied or cloned. This conforms with the way that the Java Collection APIs are designed to work: they don't copy the element objects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
} |
Q: Prevent users from having the same username I have just found a pretty major vulnerability in my code while doing some testing,
Basically if my username was "admin" and password was say "12345"...
and a user joined with and chose the name "Admin" and the same password "12345"
when he/she goes to login they will be in my account on the website, As you can imagine I have created quite a flaw, as this would affect every potential user on the site.
So, my question is what can I change in this statement to make it check for an EXACT match.
WHERE login_name ='$user' AND user_password ='$pass' LIMIT 1";
Heres the login_process.php file
<?php
require_once("includes/session.php");
$connection = mysql_connect("localhost", "user", "password");
if(!$connection)
{
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("game", $connection);
if(!$db_select)
{
die("Database selection failed: " . mysql_error());
}
$user = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);
$pass = sha1($pass);
// Need to make a change to the below query, as it doesn't match for case sensitivity.
$query = "SELECT user_id, user_name, user_level FROM users WHERE login_name ='$user' AND user_password ='$pass' LIMIT 1";
$result=mysql_query($query);
if(mysql_num_rows($result) == 1)
{
$found_user = mysql_fetch_array($result);
$_SESSION['user_id'] = $found_user['user_id'];
$_SESSION['user_name'] = $found_user['user_name'];
$_SESSION['user_level'] = $found_user['user_level'];
header("Location: index.php");
}
else
{
echo "The username or password you entered was incorrect. <br/> Please click <a href='login.php'>Here</a> to try again.";
}
?>
A: the default collation of database is case insensitive . so the user admin and Admin or adMin are the same. While creating user check the database whether same username already exist or not.
it seems that you are using case sensitive collation.. you can use case insensitive collation for that user table so that your query will work fine.
or
while creating user and checking the database for duplicate entry use LCASE function as follows
SELECT * FROM USERS WHERE LCASE(username) = 'admin'
A: You should have a UNIQUE constraint on your login_name column:
alter table users add constraint unique (login_name)
That should take care of any new entries that are added that only differ from existing entries by case (assuming of course that you're using the default case insensitive collations). If you get complaints like
ERROR 1062 (23000): Duplicate entry 'XXX' for key 'login_name'
then you already have duplicates and you'll need to clean those up before adding your UNIQUE constraint.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7537366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.