text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Multiple RemoteObjects - Best Practices I have an application with about 20 models and controllers and am not using any particular framework. What is the best practice for using multiple remote objects in Flex performance-wise?
1) Method 1 - One per Component - Each component instantiates a RemoteObject for itself
2) Method 2 - Multiple in Application Root - Each controller is handled by a RemoteObject in the root
3) Method 3 - One in Application Root - Combine all controllers into one class and handle them with one RemoteObject
I'm guessing 3 will have the best performance but will be too messy to maintain and 1 would be the cleanest but would take a performance hit. What do you think?
A: Best practice would be "none of the above." Your Views should dispatch events that a controller or Command component would use to call your service(s) and then update your model on return of the data. Your Views would be bound to the data, and then the Views would automatically be updated with the new data.
My preference is to have one service Class per different piece or type of data I am retrieving--this makes it easier to build mock services that can be swapped for real services as needed depending on what you're doing (for instance if you have a complicated server setup, a developer who is working on skinning would use the mocks). But really, how you do that is a matter of personal preference.
So, where do your services live, so that a controller or command can reach them? If you use a Dependency Injection framework such as Robotlegs or Swiz, it will have a separate object that handles instantiating, storing, and and returning instances of model and service objects (in the case of Robotlegs, it also will create your Command objects for you and can create view management objects called Mediators). If you don't use one of these frameworks, you'll need to "roll your own," which can be a bit difficult if you're not architecturally minded.
One thing people who don't know how to roll their own (such as the people who wrote the older versions of Cairngorm) tend to fall back on is Singletons. These are not considered good practice in this day and age, especially if you are at all interested in unit testing your work. http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/
A: A lot depends on how much data you have, how many times it gets refreshed from the server, and of you have to support update as well as query.
Number 3 (and 2) are basically a singletons - which tends to work best for large applications and large datasets. Yes, it would be complex to maintain yourself, but that's why people tend to use frameworks (puremvc, cairgorm, etc). much of the complexity is handled for you. Caching data within the frameworks also enhances performance and response time.
The problem with 1 is if you have to coordinate data updates per component, you basically need to write a stateless UI, always retrieving the data from the server on each component visibility.
edit: I'm using cairgorm - have ~ 30 domain models (200 or so remote calls) and also use view models. some of my models (remote object) have 10's of thousands of object instances (records), I keep a cache with/write back. All of the complexity is encapsulated in the controller/commands. Performance is acceptable.
A: In terms of pure performance, all three of those should perform roughly the same. You'll of course use slightly more memory by having more instances of RemoteObject and there are a couple of extra bytes that get sent along with the first request that you've made with a given RemoteObject instance to your server (part of the AMF protocol). However, the effect of these things is negligible. As such, Amy is right that you should make a choice based on ease of maintainability and not performance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Result Capture in webpage output I have a PHP file.
Based on the PHP the server generates a output string for example say
111 success: id:12345678 |value:10000045
Is it possible to store this output in variable and use it? say
$input = 12345678
I also do not want to store the entire output generated by the server in $input variable ,i just want to save some part of the output in it.
For example i only want to save only id not value.
How can i do these?
A: $server_said = file_get_contents('http://serveroutput.com/theoutput.php');
if (preg_match('/id\:(\d*)/', $server_said, $matches)) {
$input = $matches[1];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ASP.Net Membership Password recovery Current state of Application
We got a huge user base currently and we had requiresUniqueEmail="false" setting from day one bcse business required such.
So our password recovery was done via UserName.
Issue/Problem
Suddenly the business wants the password recovery to be done either by Username or Email. But bcse we never had unique emails in the system (in few cases no email), we are having quite a few duplicate emails in the system. For example, [email protected] is assigned to 10 different usernames.
How can I tackle this situation in best possible way?
I was thinking along the lines, if a user selects by email, I will go ahead and send all the usernames which are associated with this email. Is that a good option?
Would love to have more ideas on this. I am sure someone should have had this sort of issue before.
A: When accounts were set up did it send out a validation email to ensure people only subscribed using email addresses they owned? If so then you could send out all username's safe in the knowledge the owner of the email created them. If you didn't require validation then possibly anyone could get the email and read someone else's account.
A: You can use email to narrow down to a single username recovery. For example:
Given a set of 10 usernames with the same email "[email protected]"
When I click "Recover Password By Email"
And I enter "[email protected]"
Then I should see the message "select which username you want to recover"
And I should see a list of the 10 usernames
When I click on the username "username1"
Then I should receive a password recovery email for the "username1" account
at the "[email protected]" address
This way, you're still doing recovery by username, but only when the email has more than 1 username match.
I don't like the idea of sending the password recovery to all usernames. The user may have only forgotten one password.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Matplotlib: align origin of right axis with specific left axis value When plotting several y axis in Matplotlib, is there a way to specify how to align the origin (and/or some ytick labels) of the right axis with a specific value of the left axis?
Here is my problem: I would like to plot two set of data as well as their difference (basically, I am trying to reproduce this kind of graph).
I can reproduce it, but I have to manually adjust the ylim of the right axis so that the origin is aligned with the value I want from the left axis.
I putted below an example of a simplified version of the code I use. As you can see, I have to manually adjust scale of the right axis to align the origin of the right axis as well as the square.
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
grp1 = np.array([1.202, 1.477, 1.223, 1.284, 1.701, 1.724, 1.099,
1.242, 1.099, 1.217, 1.291, 1.305, 1.333, 1.246])
grp2 = np.array([1.802, 2.399, 2.559, 2.286, 2.460, 2.511, 2.296,
1.975])
fig = plt.figure(figsize=(6, 6))
ax = fig.add_axes([0.17, 0.13, 0.6, 0.7])
# remove top and right spines and turn ticks off if no spine
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('left')
# postition of tick out
ax.tick_params(axis='both', direction='out', width=3, length=7,
labelsize=24, pad=8)
ax.spines['left'].set_linewidth(3)
# plot groups vs random numbers to create dot plot
ax.plot(np.random.normal(1, 0.05, grp2.size), grp2, 'ok', markersize=10)
ax.plot(np.random.normal(2, 0.05, grp1.size), grp1, 'ok', markersize=10)
ax.errorbar(1, np.mean(grp2), fmt='_r', markersize=50,
markeredgewidth=3)
ax.errorbar(2, np.mean(grp1), fmt='_r', markersize=50,
markeredgewidth=3)
ax.set_xlim((0.5, 3.5))
ax.set_ylim((0, 2.7))
# create right axis
ax2 = fig.add_axes(ax.get_position(), sharex=ax, frameon=False)
ax2.spines['left'].set_color('none')
ax2.spines['top'].set_color('none')
ax2.spines['bottom'].set_color('none')
ax2.xaxis.set_ticks_position('none')
ax2.yaxis.set_ticks_position('right')
# postition of tick out
ax2.tick_params(axis='both', direction='out', width=3, length=7,
labelsize=24, pad=8)
ax2.spines['right'].set_linewidth(3)
ax2.set_xticks([1, 2, 3])
ax2.set_xticklabels(('gr2', 'gr1', 'D'))
ax2.hlines(0, 0.5, 3.5, linestyle='dotted')
#ax2.hlines((np.mean(adult)-np.mean(nrvm)), 0, 3.5, linestyle='dotted')
ax2.plot(3, (np.mean(grp1)-np.mean(grp2)), 'sk', markersize=12)
# manual adjustment so the origin is aligned width left group2
ax2.set_ylim((-2.3, 0.42))
ax2.set_xlim((0.5, 3.5))
plt.show()
A: You can make a little function that calculates the alignment of ax2:
def align_yaxis(ax1, v1, ax2, v2):
"""adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
_, y1 = ax1.transData.transform((0, v1))
_, y2 = ax2.transData.transform((0, v2))
inv = ax2.transData.inverted()
_, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
miny, maxy = ax2.get_ylim()
ax2.set_ylim(miny+dy, maxy+dy)
by using align_yaxis(), you can align the axes quickly:
#...... your code
# adjustment so the origin is aligned width left group2
ax2.set_ylim((0, 2.7))
align_yaxis(ax, np.mean(grp2), ax2, 0)
plt.show()
A: The above answer is Okay, but sometimes cuts out data, it is more thoroughly answered in the second answer here,
Matplotlib axis with two scales shared origin
or with a quick hack
def align_yaxis(ax1, v1, ax2, v2, y2min, y2max):
"""adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1."""
"""where y2max is the maximum value in your secondary plot. I haven't
had a problem with minimum values being cut, so haven't set this. This
approach doesn't necessarily make for axis limits at nice near units,
but does optimist plot space"""
_, y1 = ax1.transData.transform((0, v1))
_, y2 = ax2.transData.transform((0, v2))
inv = ax2.transData.inverted()
_, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
miny, maxy = ax2.get_ylim()
scale = 1
while scale*(maxy+dy) < y2max:
scale += 0.05
ax2.set_ylim(scale*(miny+dy), scale*(maxy+dy))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: jQuery DataTables - Slow initiation, "Normal" html table shown in the beginning I'm using jQuery DataTable plugin, but I got a concern where the scripts loading seems to take some time, so my web page is always displaying the ordinary html table first, and after all script done, the table will then become DataTable.
I don't think this kind of appearance is acceptable, so I hope can get some advices here. whether I can make the scripts faster, or don't display the plain table ahead?
Btw, I am calling my script from a _Scripts partial view at my _Layout.cshtml head tag
@Html.Partial("_Scripts")
(UPDATE)
I tried to hide the table, and show it after the datatable initialize, however, I get a datatable without the table header. Any idea why this is happening?
$('#stocktable').hide();
// Initialize data table
var myTable = $('#stocktable').dataTable({
// Try styling
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true,
// To use themeroller theme
"bJQueryUI": true,
// To use TableTool plugin
"sDom": 'T<"clear">lfrtip',
// Allow single row to be selected
"oTableTools": {
"sRowSelect": "single"
},
"fnInitComplete": function () {
$('#stocktable').show();
}
A: [edit to add: This older answer refers to the previous DataTables API. The jQueryUI options are deprecated and recommendations for replacement are found here: https://datatables.net/manual/styling/jqueryui Also, fnInitCallback (as with all other options) dropped Hungarian notation and is now initCallback]
Original answer follows:
My caveat is that I am not familiar with _Scripts partial views, so the advice below is what I would give someone just including and calling JavaScript in the 'normal' ways:
*
*Style the plain HTML table so that it shares the same appearance as the final. If you have jQuery UI enabled (bJQueryUI: true), this means having the jQuery UI classes in the 'plain' table rather than waiting for DT to add them.
*Use various FOUC (flash of unstyled content) techniques to hide the table until it is ready to render. DataTables API has useful callbacks that you can use for the "show it now" part of things, such as fnInitCallback. The most basic (but accessibility-damaging) technique is to style the table with display:none, and in the callback, use $('#myTable').show() or some variation. Searching on the internet should provide some great solutions that preserve accessibility.
Other than that, it's really just a question of (as you say!) tolerance for "acceptable". We use server-side processing (returning far fewer records), a script loader for faster script loading time (we're experimenting with head.js but there are others!), and the minimized versions of the scripts. Even with this, we sometimes see the plain table for a moment before it becomes a DT, but since internet users are accustomed to seeing pages being 'built' before their eyes as elements are loaded, it was an acceptable tradeoff. For you, it might not be.
Good luck!
A: Based on @hanzolo suggestion - here's my comment as an answer (and what my dataTable looks like):
var stockableTable = $('#stockable').dataTable({
"bLengthChange": false,
"iDisplayLength": -1,
"bSort": false,
"bFilter": false,
"bServerSide": false,
"bProcessing": false,
"sScrollY": "500px",
"sScrollX": "95%",
"bScrollCollapse": true,
// The following reduces the page load time by reducing the reflows the browser is invoking
"fnPreDrawCallback":function(){
$("#loading").show();
},
"fnDrawCallback":function(){
},
"fnInitComplete":function(){
$("#details").show();
this.fnAdjustColumnSizing();
$("#loading").hide();
}
});
A: I did a very simple solution that works fine.
In the DataTable initialization I used the method show():
$(document).ready(function() {
$('#example').dataTable({
"order": [[ 0, 'asc' ]]
});
$('#example').show();
} );
... and in the HTML table I put the style display:none:
<table id="example" class="display" cellspacing="0" width="100%" style="display:none">
Good luck!
A: My working solution is a "dirty" trick to hide the table without using "display:none". The ordinary "display:none" style causes initialization problem for jQuery Data Tables.
First of all, place your data table in a wrapper div:
<div id="dataTableWrapper" style="width:100%" class="dataTableParentHidden">
...data table html as described in jQuery Data Table documentation...
</div>
In CSS:
.dataTableParentHidden {overflow:hidden;height:0px;width:100%;}
This solution hides the data table without using "display:none".
After the data table initialization you have to remove class from wrapper to reveal the table:
$('#yourDataTable').DataTable(...);
$('#dataTableWrapper').removeClass('dataTableParentHidden');
A: I had the same problem. Try this:
var dTable=$("#detailtable").dataTable({
"bProcessing":true,
"bPaginate":false,
"sScrollY":"400px",
"bRetrieve":true,
"bFilter":true,
"bJQueryUI":true,
"bAutoWidth":false,
"bInfo":true,
"fnPreDrawCallback":function(){
$("#details").hide();
$("#loading").show();
//alert("Pre Draw");
},
"fnDrawCallback":function(){
$("#details").show();
$("#loading").hide();
//alert("Draw");
},
"fnInitComplete":function(){
//alert("Complete");
}
A: I think you should probably just load scripts in the _Layout.cshtml, after all that's what it's for. Partial views are really meant for segments that can be re-used in other areas or at the very least, rendered HTML content.
That being said, one easy thing to do would be to either hide the table until it's done loading or even hide it and show a progress indicator.
You could do something like:
// .loadTable() is some function that loads your table and returns a bool indicating it's finished
// just remember to check this bool within the function itself as it will be called over and over until it returns true
while (!loadTable()) {
// maybe show a progress bar
if ($('#myTable').css('display') != 'none')) {
$('#myTable').hide(); // if it isn't already hidden, hide it
}
}
// hide progress bar
$('#myTable').show();
UDPATE:
If the jQuery table plugin has a "success" or "finished" callback, just hide the table on page load and show it when it's done loading.
$(document).ready(function () {
$('#myTable').hide();
// run plugin and .show() on success or finished
});
A: I know it's very old question, but maybe I can help someone in future, how know ...
So after many hours I find the only solution that work's for me (table it will be loaded after it is rendered complete):
<html>
<head>
<style>
.dn {
display: none;
}
</style>
</head>
<body>
<div id="loadDiv" class="firstDivClass secondDivClass">Loading...<div>
<table id="myTable" class="dn firstTableClass secondTableClass">
<tr><td>Something Here</td></tr>
</table>
</body>
<script>
$(document).ready(function(){
showMeTheTabel();
});
function shoMeTheTable() {
var dTable = $('#myTable').dataTable({
"aoColumnDefs": [
{bla, bla}
],
"oLanguage": {
"bla" : "bla"
},
"fnPreDrawCallback":function(){
},
"fnDrawCallback":function(){
$("#loading").addClass('dn');
$('#tabel').removeClass('dn');
},
"fnInitComplete":function(){
console.log("Complete") // optional and Done !!!
}
});
}
</script>
</html>
A: This is due to the ColVis plugin. remove the "W" from the sDOM and your table rendering will fly (albiet withou dropdowns)
A: *
*The following is a node.js handlebars example. However, you can render the data using whatever web front-end framework you are using.
*If you're using bootstrap you can hide the table initially using the hidden class or alternatively hide the elements manually.
*Then in the initComplete callback you can then use jQuery to remove the hidden class to display the table only once it has loaded completely.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<table id="stocktable" class="table hidden">
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Street Address</th>
<th>State</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{{#each devices}}
<tr id="{{id}}">
<td>{{first_name}}</td>
<td>{{last_name}}</td>
<td>{{age}}</td>
<td>{{street_address}}</td>
<td>{{state}}</td>
<td>{{country}}</td>
</tr>
{{/each}}
</tbody>
</table>
<script>
$(document).ready(function() {
$('#stocktable').DataTable({
columns: [{
person: 'first_name'
}, {
person: 'last_name'
},
{
person: 'age'
},
{
person: 'street_address'
},
{
person: 'state'
},
{
person: 'country'
}
],
initComplete: function() {
// Unhide the table when it is fully populated.
$("#stocktable").removeClass("hidden");
}
});
});
</script>
For example:
A: My datatable was jumping between posts because of the filter on top.
Simple solution:
Hide the table with display:none, then use jquery .fadeIn() before DataTable() is called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Delphi 2007 and XE2: Using NativeInt Since Delphi XE2, NativeInt has new meaning. At 32 bits runtime, NativeInt is 32 bits integer. At 64 bits runtime, NativeInt is 64 bits integer.
I have some source files that use third party DLL (both 32 and 64 bits). These DLL use 32 and 64 bits integer in both 32 and 64 platform respectively.
These source files works in Delphi 2007 - Delphi XE2 32 bits platform without problem:
e.g.:
function Test: Integer;
When I attempt to migrate those source files to Delphi XE2 64 bits platform, the above function no longer works as it require 64 bits integer. In order to make the source works for both 32/64 platforms, I change to
function Test: NativeInt;
And it works.
However, the declaration doesn't work in Delphi 2007 as Delphi 2007 treat NativeInt as 64 bits integer: SizeOf(NativeInt) = 8
I may solve the problem by using conditional directive RtlVersion or CompilerVersion to
function Test: {$if CompilerVersion<=18.5}Integer{$else}NativeInt{$ifend};
But that would be tedious as there are many declaration in source files.
Is there a better ways to make the source files work in Delphi 2007-XE2 win32 and XE2 win64 platform?
A: A better alternative is to redeclare NativeInt type itself:
{$if CompilerVersion<=18.5}
type
NativeInt = Integer;
{$ifend}
It should be done once per unit and can be implemented as a part of common *.inc file.
A: Gee: why not just use LongInt (where you require 32-bits) and Int64 (otherwise)?
And just use "integer" where it doesn't matter?
It just seems counter-intuitive to use "NativeInt" where you KNOW it's going to mean different things at different times...
PS:
You can always define your OWN, custom type, and $ifdef it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: why it shows "App Requests 1", but no requests listed in the app pages on facebook
just as the picture I attached, it shows 1 app requests, but there is no apps listed there.
the apprequests sent from the graph api using javascript sdk
A: Any App Reqeusts you set with you app will need to be deleted by your app. Sample from blog shows how to concatenate the request_id and user_id in order to delete the outstanding requests.
Refer to http://developers.facebook.com/blog/post/569/
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>Deleting Requests Example</title>
</head>
<body>
<?php
$user_id = $facebook->getUser();
if ($user_id) {
//Get the Request Ids
$request_ids = explode(',', $_REQUEST['request_ids']);
//Construct full Request_Id
function build_full_request_id($request_id, $user_id) {
return $request_id . '_' . $user_id;
}
//For each Request construct full Request_id and Delete
foreach ($request_ids as $request_id) {
echo ("reqeust_id=".$request_id."<br>");
$full_request_id =
build_full_request_id($request_id,$user_id);
echo ("full_reqeust_id=".$full_request_id."<br>");
try {
$delete_success =
$facebook->api("/$full_request_id",'DELETE');
if ($delete_success) {
echo "Successfully deleted " . $full_request_id;
}
else {
echo "Delete failed".$full_request_id;
}
}
catch (FacebookApiException $e) {
echo "error";
}
}
}
//User TOS if user has not authenticated your App
else if (!isset($_REQUEST['error'])){
$params = array(
'redirect_uri' => 'http://localhost/~namitag/requests.php'
);
$loginUrl = $facebook->getLoginUrl($params);
echo
'<script>window.top.location.href="'.$loginUrl.'";</script>';
}
else {
echo ("user denied permission"); }
?>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: iPhone UDP broadcast and response I need to send out a UDP broadcast from an iPhone, and then listen for a UDP response with a timeout period. I have found Apple's UDPEcho example but I am not sure if it's what I need. Also found this example to send but not receive. Basically, I need to do something simple like this:
//send the broadcast
SendUDP("255.255.255.255", targetPort, myData);
//A blocking call to get the data. Timeout value will be short, 2 seconds at most
//An asynchronous option is ok, if it's necessary.
Response = GetFirstUDPResponse(receptionPort, timeoutValue);
//process the response
if(Response == null)
//we timed out
else
//process response
I'm hoping for a simple solution where I don't have to reinvent the wheel. I appreciate any advice on the best strategy to implement this!
A: You can use cocoaAsyncSocket which is easier to use than apple native classes.
It support UDP with AsyncUdpSocket class.
AsyncUdpSocket is a UDP/IP socket networking library that wraps
CFSocket. It works almost exactly like the TCP version, but is
designed specifically for UDP. This includes queued non-blocking
send/receive operations, full delegate support, run-loop based,
self-contained class, and support for IPv4 and IPv6
A: I'd put 'recvfrom' on another thread using grand central dispatch, like this:
// Use grand central dispatch so we don't block the interface
dispatch_async(dispatch_get_global_queue(0, 0), ^{
recvfrom(...) // Receive with a 2s timeout
dispatch_async(dispatch_get_main_queue(), ^{ // The main thread stuff goes here
if (received ok) {
[self receivedData:some data];
} else {
[self timedOut];
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Is there a UI framework to emulate the look of a Mac app? I've been looking around and havent been able to find any. I noticed that the wunderlist mac app was written in HTML/CSS/JS but I wasnt sure if they used an existing UI javascript framework.
Thanks!
A: Wunderlist was created using the Titanium framework (http://www.appcelerator.com/).
Titanium is used to create cross-platform applications for Windows, Mac, mobile platforms, and others.
If you're wondering how they got the Mac "look", that's because Titanium has built in Mac-like UI controls as part of the framework.
Edit
Here's the Titanium Desktop page: http://www.appcelerator.com/products/titanium-desktop-application-development/
Titanium makes Vista apps look like Vista apps, XP apps like XP apps and Mac OS X apps fully native as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HDFS replication factor When I'm uploading a file to HDFS, if I set the replication factor to 1 then the file splits gonna reside on one single machine or the splits would be distributed to multiple machines across the network ?
hadoop fs -D dfs.replication=1 -copyFromLocal file.txt /user/ablimit
A: According to the Hadoop : Definitive Guide
Hadoop’s default strategy is to place the first replica on the same node as the client (for
clients running outside the cluster, a node is chosen at random, although the system
tries not to pick nodes that are too full or too busy). The second replica is placed on a
different rack from the first (off-rack), chosen at random. The third replica is placed on
the same rack as the second, but on a different node chosen at random. Further replicas
are placed on random nodes on the cluster, although the system tries to avoid placing
too many replicas on the same rack.
This logic makes sense as it decreases the network chatter between the different nodes. But, the book was published in 2009 and there had been a lot of changes in the Hadoop framework.
I think it depends on, whether the client is same as a Hadoop node or not. If the client is a Hadoop node then all the splits will be on the same node. This doesn't provide any better read/write throughput in-spite of having multiple nodes in the cluster. If the client is not same as the Hadoop node, then the node is chosen at random for each split, so the splits are spread across the nodes in a cluster. Now, this provides a better read/write throughput.
One advantage of writing to multiple nodes is that even if one of the node goes down, a couple of splits might be down, but at least some data can be recovered somehow from the remaining splits.
A: If you set replication to be 1, then the file will be present only on the client node, that is the node from where you are uploading the file.
A: *
*If your cluster is single node then when you upload a file it will be spilled according to the blocksize and it remains in single machine.
*If your cluster is Multi node then when you upload a file it will be spilled according to the blocksize and it will be distributed to different datanode in your cluster via pipeline and NameNode will decide where the data should be moved in the cluster.
HDFS replication factor is used to make a copy of the data (i.e) if your replicator factor is 2 then all the data which you upload to HDFS will have a copy.
A: If you set replication factor is 1 it means that the single node cluster. It has only one client node http://commandstech.com/replication-factor-in-hadoop/. Where you can upload files then use in a single node or client node.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: CSS HTML Strange White Space I am creating a website and there's a strange white space at the bottom of the page (only at IE). safari is fine. i am using ie8.
I want the white background ended after that black navigation links.
http://www.applezone.com.hk/newrx/
I can't figure out which part of the css causing that white space.
Thanks.
A: try adding those:
.navlink{
display: inline-block;
margin-left: 51px;
}
i don't have IE8 to test on but i do use "IE tester" program which showed me the problem.
A: Try display:block and/or margin:0 and/or padding:0 for the element in question. One of them is going to be the culprit.
A: If you use Firebug (Firefox add-on) you can select that white space and it will show you where it is in the DOM, i.e. what the HTML is that is actually generating it - which element it's part of.
You can also switch on and off the individual styles on the fly.
The equivalent in IE is to hit F12 and get the 'Developer Tools' console. Find -> Select Element by Click.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How To Detect Email Size Issues In .NET We have an application which sends out automatic email notifications to our users.
Those emails come from a no reply address for instance '[email protected]'.
The problem comes when the attachments added to the automatic emails go above the limit of the receiver email server, e.g. 8 MB, or 10 MB.
Is there a way in .NET to detect that this is going to happen? If a reply comes to no-reply saying that there is a failure because the limit was exceeded that is not ideal because that address is never checked.
Is there a way of detecting whether this will be a problem before sending the email?
I guess the main problem is that the email size limit can be configured, so we don't know what it is going to be for a particular organisation.
A: Just a thought, why don't you insert links to the attachments/files instead? I've been though this several times, and yes if the file to attach is personal, attach it, otherwise just put the attachment on a webserver and link to it.
That would certainly speed up mail delivery, and reduce bouncing messages.
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: minGW and cpan modules I am trying to use the Finance::TickerSymbols module from perl(ActiveState perl) and since PPM didn't have it, I ran cpan on my minGW console to install it.
the installation went fine, however, minGW seems to install the modules in
C:\MinGW\msys\1.0\home\ar\.cpan\build\Finance-TickerSymbols-1.03\lib\Finance\
so, when I run my perl code, I get the following error:
Can't locate Finance/TickerSymbols.pm in @INC(@INC contains C:/Perl64/site/lib C:/Perl64/lib .)
and of course the compilation fails.
I can copy and paste the .pm from the mingw path, but that's not going to work for everything. Can anyone suggest how this can be fixed. thx!
EDIT: ran install for other module to provide the output of install in minGW
Running install for module Finance::Curency::Convert
Running make for J/JA/JANW/Finance-Currency-Convert-1.08.tgz
CPAN: LWP::UserAgent loaded ok
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/authors/id/J/JA/JANW/CHECKSUMS
CPAN: Compress::Zlib loaded ok
Checksum for /home/ar/.cpan/sources/authors/id/J/JA/JANW/Finance-Currency-Convert-1.08.tgz ok
Scanning cache /home/ar/.cpan/build for sizes
Deleting from cache: /home/ar/.cpan/build/GD-2.46 <24.0>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/Finance-TickerSymbols-1.03 <23.5>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/GDTextUtil-0.86 <23.4>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/GDGraph-1.44 <23.2>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/Date-Simple-3.03 <22.6>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/HTML-TableExtract-2.11 <22.4>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/Text-CSV-1.21 <22.2>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/ExtUtils-MakeMaker-6.59 <21.9>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/YAML-Syck-1.17 <19.1>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/Test-Inter-1.03 <18.2>10.0 MB>
Deleting from cache: /home/ar/.cpan/build/Date-Manip-6.25 <18.0>10.0 MB>
Finance-Currency-Convert-1.08/
Finance-Currency-Convert-1.08/MANIFEST
Finance-Currency-Convert-1.08/t/
Finance-Currency-Convert-1.08/t/convert.t
Finance-Currency-Convert-1.08/Makefile.PL
Finance-Currency-Convert-1.08/Changes
Finance-Currency-Convert-1.08/META.yml
Finance-Currency-Convert-1.08/Convert.pm
CPAN.pm: Going to build J/JA/JANW/Finance-Currency-Convert-1.08.tgz
Checking if your kit is complete...
Looks good
Writing Makefile for Finance::Currency::Convert
cp Convert.pm blib/lib/Finance/Currency/Convert.pm
Autosplitting blib/lib/Finance/Currency/Convert.pm (blib/lib/auto/Finance/Currency/Convert)
/bin/make -- OK
Running make test
/usr/bin/perl.exe "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib','blib/arch')"t/*.txt
t/convert....ok
All tests successful.
Files=1, Tests=8, 0 wallclock secs ( 0.03 cusr + 0.03 csys = 0.06 CPU)
/bin/make/test --OK
Running make install
Installing /usr/lib/perl5/site_perl/5.8/auto/Finance/Currency/Convert/autosplit.ix
Installing /usr/lib/perl5/site_perl/5.8/auto/Finance/Currency/Convert.pm
Writing /usr/lib/perl5/site_perl/5.8/auto/Finance/Currency/Convert/.packlist
Appending installation info to /usr/lib/perl5/5.8/msys/perllocal.pod
/bin/make/install -- OK
A: You need to go to the PPM and install the CPAN module.
Then, go to your command line, and run cpan. Then install Finance::TickerSymbols. ActiveState's cpan will check whether or not you need MinGW installed, and install it if necessary. After that, it will download and build the Finance::TickerSymbols module.
If that doesn't work, use the use lib pragma in your Perl script to specify the directory where these modules should be loaded from:
use lib qw(/usr/lib/perl5/5.8 /usr/lib/perl5/site_perl/5.8);
Yes, that's right, the module is actually in /usr/lib/perl5. If you look at your output, you'll see that the modules are built in C:\MinGW\msys\1.0\home\ar\.cpan\build\, but if you look at the end of the log, you'll see they're being installed in /usr/lib/perl5/site_perl/5.8
Running make install
Installing /usr/lib/perl5/site_perl/5.8/auto/Finance/Currency/Convert/autosplit.ix
Installing /usr/lib/perl5/site_perl/5.8/auto/Finance/Currency/Convert.pm
Writing /usr/lib/perl5/site_perl/5.8/auto/Finance/Currency/Convert/.packlist
Appending installation info to /usr/lib/perl5/5.8/msys/perllocal.pod
/bin/make/install -- OK
The final thing you can do (if nothing else works) is switch to Strawberry Perl. This comes with everything you need to use the CPAN modules. It's what Larry Wall uses. Strawberry Perl has no trouble installing that module from the CPAN archive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python: Clicking a button with urllib or urllib2 I want to click a button with python, the info for the form is automatically filled by the webpage. the HTML code for sending a request to the button is:
INPUT type="submit" value="Place a Bid">
How would I go about doing this?
Is it possible to click the button with just urllib or urllib2? Or will I need to use something like mechanize or twill?
A: You may want to take a look at IronWatin - https://github.com/rtyler/IronWatin to fill the form and "click" the button using code.
A: Use the form target and send any input as post data like this:
<form target="http://mysite.com/blah.php" method="GET">
......
......
......
<input type="text" name="in1" value="abc">
<INPUT type="submit" value="Place a Bid">
</form>
Python:
# parse the page HTML with the form to get the form target and any input names and values... (except for a submit and reset button)
# You can use XML.dom.minidom or htmlparser
# form_target gets parsed into "http://mysite.com/blah.php"
# input1_name gets parsed into "in1"
# input1_value gets parsed into "abc"
form_url = form_target + "?" + input1_name + "=" + input1_value
# form_url value is "http://mysite.com/blah.php?in1=abc"
# Then open the new URL which is the same as clicking the submit button
s = urllib2.urlopen(form_url)
You can parse the HTML with HTMLParser
And don't forget to urlencode any post data with:
urllib.urlencode(query)
A: Using urllib.urlopen, you could send the values of the form as the data parameter to the page specified in the form tag. But this won't automate your browser for you, so you'd have to get the form values some other way first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Better way of coding a RAM in Verilog Which code is better in writing a RAM?
*
*assigning data_out inside always block:
module memory(
output reg [7:0] data_out,
input [7:0] address,
input [7:0] data_in,
input write_enable,
input clk
);
reg [7:0] memory [0:255];
always @(posedge clk) begin
if (write_enable) begin
memory[address] <= data_in;
end
data_out <= memory[address];
end
endmodule
*assigning data_out using assign statement:
module memory(
output [7:0] data_out,
input [7:0] address,
input [7:0] data_in,
input write_enable,
input clk
);
reg [7:0] memory [0:255];
always @(posedge clk) begin
if (write_enable) begin
memory[address] <= data_in;
end
end
assign data_out = memory[address];
endmodule
Any recommendations?
A: to add to toolic's answer - if you use the asynchronous read method (case 2), it won't map to a RAM block in an FPGA, as the RAM blocks in all the major architectures I'm aware of have a synchronous read.
A: It depends on your requirements.
*
*This registers your memory output. If you are synthesizing this to gates, you will have 8 more flip-flops than in case 2. That means you use a little more area. It also means your output will have less propagation delay relative to the clock than case 2. Furthermore, the output data will not be available until the next clock cycle.
*Your output data will be available within the same clock cycle as it was written, albeit with longer propagation delay relative to the clock.
You need to decide which to use based on your requirements.
A third option is to use a generated RAM, which is a hard macro. This should have area, power and possibly timing advantages over both case 1 and 2.
A: Both forms are valid, depending on the type of pipelining you want. I always recommend following the Xilinx RAM coding guidelines -- it's a good way to ensure that the code synthesizes into proper FGPA constructs.
For example, your example 1 would synthesize into into Xilinx BRAM (i.e., dedicated Block Ram), since it is synchronous read, and your example 2 would synthesize into Xilinx Distributed Ram (since it is asynchronous read).
See the coding guidelines in Xilinx document UG901 (Vivado Design Suite User Guide), in the RAM HDL Coding Techniques section. It also has a good description of the difference between synchronous read and asynchronous read for RAMs.
A: In the second program, there would be compilation error as we can not 'Assign' a value to 'Reg'.
It will give an error saying: 'Register is illegal in left-hand side of continuous assignment'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: What's wrong with my (attempted) implementation of iterateM? I would like to implement a function, iterateM, whose type would look like this:
iterateM :: Monad m => (a -> m a) -> a -> [m a]
However, my first go at writing this function:
iterateM f x = f x >>= (\x' -> return x' : iterateM f x')
Gives me the error:
Could not deduce (m ~ [])
from the context (Monad m)
bound by the type signature for
iterateM :: Monad m => (a -> m a) -> a -> [m a]
at main.hs:3:1-57
`m' is a rigid type variable bound by
the type signature for
iterateM :: Monad m => (a -> m a) -> a -> [m a]
at main.hs:3:1
Expected type: [a]
Actual type: m a
In the return type of a call of `f'
In the first argument of `(>>=)', namely `f x'
In the expression: f x >>= (\ x' -> return x' : iterateM f x')
If I remove my type-signature, ghci tells me the type of my function is:
iterateM :: Monad m => (a -> [a]) -> a -> [m a]
What am I missing here?
A: What I gather from your signature:
iterateM :: (Monad m) => (a -> m a) -> a -> [m a]
Is that the nth element iterateM f x will be an action that runs f n times. This is very close to iterate, I suspect we can implement it in terms of that.
iterate :: (b -> b) -> b -> [b]
iterate gives us a list of bs, and we want a list of m as, so I suspect b = m a.
iterate :: (m a -> m a) -> m a -> [m a]
Now we need a way to transform f :: a -> m a into something of type m a -> m a. Fortunately, that is exactly the definition of bind:
(=<<) :: (Monad m) => (a -> m b) -> (m a -> m b)
So:
\f -> iterate (f =<<) :: (a -> m a) -> m a -> [m a]
And to get our initial x :: a into the desired m a, we can use return:
return :: (Monad m) => a -> m a
So:
iterateM f x = iterate (f =<<) (return x)
Pointfreeize to taste.
A: Your recursive use of iterateM is forcing it to be in the list monad. You need to run the iterateM action and return its result.
Try:
iterateM f x = do
x' <- f x
xs <- iterateM f x'
return $ x':xs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How can I make my EditText five lines high without using android:inputType="textMultiLine"? I want to have a EditText view that is five lines high. I want it five lines high for visual appeal reasons only (so that it does not appear cramped). The code below does not work, the EditText appears only one line high.
I have tried multilinetext and it works visually, however I want to abandon it as I want the virtual keyboard to say "Next" (rather than have the enter key that is automatically provided with multiline text)
How can I make my EditText box bigger? Alternatively, how can I use the imeOption "actionNext" with multiline text?
This code does not work...
<EditText
android:id="@+id/etEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:inputType="text"
android:lines="5" //this has no effect!
android:imeOptions="actionNext"
style="@style/dialogInput" />
A: Change:
android:inputType="text"
to:
android:inputType="textMultiLine"
Works for me!
A: <EditText
android:id="@+id/etEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:inputType="text"
android:lines="5" //this has no effect!
android:imeOptions="actionNext"
style="@style/dialogInput"
android:singleLine="false" />
android:singleLine="false" will make editText to support multiple lines
A: On the other hand, you can try to use a line-break on text string to display, this is the tip: http://xjaphx.wordpress.com/2011/07/15/set-line-break-in-textview/
and of course, you must set:
android:singleLine="false"
A: Change:
android:inputType="text"
To:
android:inputType="textImeMultiLine"
If that doesn't work then change:
android:inputType="text"
To:
android:inputType="textMultiLine"
and delete:
android:imeOptions="actionNext"
style="@style/dialogInput"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: The actual result of name resolution in the class template is different from the c++ 03 standard I test the code in the c++ standard ISO/IEC 14882-03 14.6.1/9 on Xcode 4.1 and Visual Studio 2008. The outputs of the two compiler are both different from the expected result of the standard.
The code is pasted below.
#include <stdio.h>
#include <iostream>
using namespace std;
void f(char);
template <class T > void g(T t)
{
f(1);
f(T(1));
f(t);
}
void f(int);
void h()
{
g(2);
g('a');
}
void f(int)
{
cout << "f int" << endl;
}
void f(char)
{
cout << "f char" << endl;
}
int main() {
h();
return 0;
}
As the description of the standard. The expected output should be
f char
f int
f int
f char
f char
f char
Build and run the code on Xcode 4.1. The output is as below. In the build settings, I tried to change the "Compiler for C/C++/Object-C" to be Apple LLVM Compiler 2.1, Gcc 4.2 and LLVM GCC 4.2. The outputs are the same.
f char
f char
f char
f char
f char
f char
Build and run the code on Microsoft Visual Studio 2008. The output is as below.
f int
f int
f int
f int
f char
f char
The description (14.6.1/9) of the standard is pasted below.
If a name does not depend on a template-parameter (as defined in 14.6.2), a declaration (or set of declara- tions) for that name shall be in scope at the point where the name appears in the template definition; the name is bound to the declaration (or declarations) found at that point and this binding is not affected by declarations that are visible at the point of instantiation. [Example:
void f(char);
template<class T> void g(T t)
{
f(1); // f(char)
f(T(1)); // dependent
f(t); // dependent
dd++; // not dependent
}
void f(int);
double dd;
void h()
{
// error: declaration for dd not found
g(2); // will cause one call of f(char) followed // by two calls of f(int)
g(’a’); // will cause three calls of f(char)
—end example]
The code is well-formed to the compilers, but the outputs are different. It would be very dangerous to port this code to different platforms.
Does somebody have the background why these compilers don't follow the standard?
Edit on 10/11/2011
Per http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#197, the example in the standard is wrong. I test the code below on Clang and Gcc.
#include <stdio.h>
#include <iostream>
using namespace std;
void f(char);
template <class T > void g(T t)
{
f(1);
f(T(1));
f(t);
}
enum E{ e };
void f(E );
void h()
{
g(e);
g('a');
}
void f(E )
{
cout << "f E" << endl;
}
void f(char)
{
cout << "f char" << endl;
}
int main() {
h();
return 0;
}
The output as expected.
f char
f E
f E
f char
f char
f char
Thanks,
Jeffrey
A: What you're running into is the fact that Visual Studio does not implement two-phase lookup. They only look up the actual name when you instantiate the template.
And Microsoft has pretty much decided at this point that they're not interested in supporting two-phase lookup.
A: As noted in the first example, this is an instance of two-phase name lookup, which both GCC and Clang implement but MSVC does not. And in this case, both GCC and Clang are correct: it's actually the standard that is wrong, as noted in C++ core defect report #197. The C++11 standard contains a different example.
This is one of the most common problems we see when porting code to Clang from either MSVC (which never implemented two-phase name lookup) or from GCC (which didn't implement two-phase name lookup uniformly until recently).
A: I don't know what to tell you except that I would agree with you that this is incorrect behavior.
I think what's probably happening is that in the case of MSVC, the compiler is optimizing away an extra pass at the cost of ending up with the knowledge of a later-defined function that should not be use in the case of non-template calls. I must confess, I don't get how GCC/LLVM would end up with the results that they do, as the results are what you would expect as the exception and not the rule.
I guess I'd file it as a bug on http://bugreport.apple.com/ and http://connect.microsoft.com/ and see what they say?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: specs failing in Rails 3.1 - NoMethodError: private method 'rand' called for Array I'm getting a weird error all of a sudden when I run my spec, which is then causing my specs to fail. These specs worked find before - but recently we upgraded from Rails 3.0 -> Rails 3.1. It seems like machinist is having some problems trying to create the data for my tests, but I don't quite get why 'rand' all of a sudden isn't available.
Anything thoughs/tips would be greatly appreciated.
Here is the line in my blueprint:
Invoice.blueprint do
invno { Faker::Base.bothify(["#######", "N######", "C######"].rand) }
order_no { Faker::Base.numerify("N######") }
Here is some information about my environment -
ruby -v:
ruby 1.9.2p290 (2011-07-09 revision 32553) [i686-linux]
rvm and rvm list (to show my gemset):
rvm 1.8.5 by Wayne E. Seguin ([email protected]) [https://rvm.beginrescueend.com/]
=> ruby-1.9.2-p290 [ i386 ]
And here is the error that is happening:
NoMethodError: private method `rand' called for ["#######", "N######", "C######"]:Array
/home/tom/work/ruby/litdistco-sales/spec/blueprints.rb:93:in `block (2 levels) in <top (required)>'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/machinist-1.0.6/lib/machinist.rb:77:in `generate_attribute_value'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/machinist-1.0.6/lib/machinist.rb:46:in `method_missing'
/home/tom/work/ruby/litdistco-sales/spec/blueprints.rb:93:in `block in <top (required)>'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/machinist-1.0.6/lib/machinist.rb:20:in `instance_eval'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/machinist-1.0.6/lib/machinist.rb:20:in `run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/machinist-1.0.6/lib/machinist/active_record.rb:53:in `make'
/home/tom/work/ruby/litdistco-sales/spec/models/invoice_sales_tax_assignment_mixin_spec.rb:7:in `block (3 levels) in <top (required)>'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/hooks.rb:35:in `instance_eval'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/hooks.rb:35:in `run_in'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/hooks.rb:70:in `block in run_all'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/hooks.rb:70:in `each'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/hooks.rb:70:in `run_all'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/hooks.rb:116:in `run_hook'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:221:in `block in eval_before_eachs'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:221:in `each'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:221:in `eval_before_eachs'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example.rb:145:in `run_before_each'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example.rb:47:in `block in run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example.rb:107:in `with_around_hooks'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example.rb:45:in `run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:294:in `block in run_examples'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:290:in `map'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:290:in `run_examples'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:262:in `run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:263:in `block in run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:263:in `map'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/example_group.rb:263:in `run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/command_line.rb:24:in `block (2 levels) in run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/command_line.rb:24:in `map'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/command_line.rb:24:in `block in run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/reporter.rb:12:in `report'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/command_line.rb:21:in `run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:80:in `run_in_process'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:69:in `run'
/home/tom/work/ruby/litdistco-sales/foreman/ruby/1.9.1/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:11:in `block in autorun'
A: Use "sample" instead of "rand".
Refer to:
http://www.ruby-forum.com/topic/383479
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: UIViewController shouldAutorotateToInterfaceOrientation - would like to add hysteresis I would like to defer auto rotating the user interface until the device has settled on an orientation for a number of seconds, rather than driving the user insane and flicking willy nilly whenever they tilt the device a few degrees off axis by mistake.
the closest i can get to this (which is by no means what I want, as it locks the UI) is:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
[NSThread sleepForTimeInterval:2.0];
return YES;
}
what i would like to do is use something like this - which works in principle, by checking the console log, but i need the appropriate line of code that has been commented out.
-(void) deferredAutorotateToInterfaceOrientation:(NSTimer *) timer {
autoRotationTimer = nil;
UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)[timer.userInfo integerValue];
NSLog(@"switching to new orientation %d now",interfaceOrientation);
// replace this with code to induce manual orientation switch here.
//[self forceAutoRotateToInterfaceOrientation:interfaceOrientation];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
[autoRotationTimer invalidate];
autoRotationTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self
selector:@selector(deferredAutorotateToInterfaceOrientation:) userInfo:[NSNumber numberWithInt:(int)interfaceOrientation ] repeats:NO];
NSLog(@"denying autorotate, deffering switch to orientation %d by 2 seconds",interfaceOrientation);
return NO;
}
I realize there are sometimes many ways to do things, so if this approach is not the most efficient, and someone can suggest another way to do this, I am all ears. My main criteria is I want to delay the onset of autorotation, whilst keeping a responsive user interface if indeed they have only leaned to the left slightly because they are in a bus that just went around a corner etc.
EDIT: I found a solution which may not be app store friendly, however i am a few weeks away from completion, and someone may answer this in the meantime. this works calls an undocumented method. the (UIPrintInfoOrientation) typecast is just to suppress the compiler warning, and does not affect the value being passed.
-(void ) forceUIOrientationInterfaceOrientation:(UIDeviceOrientation) interfaceMode {
[(id)[UIDevice currentDevice] setOrientation:(UIPrintInfoOrientation) interfaceMode];
}
full implementation which includes re-entrance negation is as follows:
- (void)viewDidLoad {
[super viewDidLoad];
acceptNewAutoRotation = YES;
}
-(void ) forceUIOrientationInterfaceOrientation:(UIDeviceOrientation) interfaceMode {
[(id)[UIDevice currentDevice] setOrientation:(UIPrintInfoOrientation) interfaceMode];
}
-(void) deferredAutorotateToInterfaceOrientation:(NSTimer *) timer {
autoRotationTimer = nil;
acceptNewAutoRotation = YES;
[self forceUIOrientationInterfaceOrientation:[[UIDevice currentDevice] orientation]];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
[autoRotationTimer invalidate];
if (acceptNewAutoRotation) {
autoRotationTimer = nil;
acceptNewAutoRotation = NO;
return YES;
} else {
autoRotationTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self
selector:@selector(deferredAutorotateToInterfaceOrientation:) userInfo:[NSNumber numberWithInt:(int)interfaceOrientation ] repeats:NO];
return NO;
}
}
A: To do this with public APIs, you probably would have to forget about autorotation, and do all your own view transforms manually based on filtered (not just delayed!) accelerometer input.
A: I have not tested this and it may not work at all but you can try this out:
start out self.rotate = NO; then:
- (void)shouldRotateTo:(UIInteraceOrientation *)interfaceOrientation {
self.rotate = YES;
// or test interfaceOrientation and assign accordingly.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
bool rot = self.rotate;
self.rotate = NO
[self performSelector:selector(shouldRotateTo:) withObject:[NSNumber numberWithInt:interfaceOrientation] afterDelay:2.0];
return rot;
}
Parameter interfaceOrientation is an enum (UIInteraceOrientation) so wrap it in an NSNumber when passing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to block global JQuery Effect which causes UI Slider to disappear I'm using the following JQuery UI slider script to input values:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery( "#slider-range-min" ).slider({
range: "min",
value: 5,
min: 1,
step: 5,
max: 60,
slide: function( event, ui ) {
jQuery( "#amount" ).val( ui.value );
}
});
jQuery( "#amount" ).val( jQuery( "#slider-range-min" ).slider( "value" ) );
</script>
<div style="width:100%;clear:both;margin-top:10px;"></div>
<div id="slider-range-min"></div>
Whenever the knob on the slid is clicked or slid, it is hidden or slides up out of site. I have not been able to determine which effect exactly is causing the slider to disappear. This is a problem, because if a user happens to initially set the wrong value, the cannot correct it because the slider has disappeared. Is there a way to block the slider from other globale effects. Again I am not sure which exact effect is causing this (hide,slideUP,etc)
A: If you are using a ranged slider in JQueryUI, you need to use .slider('values') instead of .slider('value').
Per the docs:
value
.slider( "value" , [value] )
Gets or sets the value of the slider. For single handle sliders.
values
.slider( "values" , index , [value] )
Gets or sets the values of the slider. For multiple handle or range sliders.
A: Could you possibly have a MooTools and jQuery library collision (1, 2)?
One workaround is to remove each MooTools slide method before applying the jQuery UI slider as such:
jQuery('div.slider')
.each(function(){
//removing the MooTools slide method
this.slide=null;
})
.slider({
...
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't export Play! app as war I'm trying to package a Play! app built against Java 7. I'm getting this error. Also, I cannot launch the app from the command line, but from Eclipse it works.
D:\Dropbox\eclipseProjectsClassic>play war MyApp -o MyApp.war --zip
~ _ _
~ _ __ | | __ _ _ _| |
~ | '_ \| |/ _' | || |_|
~ | __/|_|\____|\__ (_)
~ |_| |__/
~
~ play! 1.2.3, http://www.playframework.org
~
Listening for transport dt_socket at address: 8000
04:17:03,694 INFO ~ Starting D:\Dropbox\eclipseProjectsClassic\MyApp
Exception in thread "main" java.lang.UnsupportedClassVersionError: DocViewerPlugin : Unsupported maj
or.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at play.classloading.ApplicationClassloader.loadApplicationClass(ApplicationClassloader.java
:158)
at play.classloading.ApplicationClassloader.loadClass(ApplicationClassloader.java:84)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at play.plugins.PluginCollection.loadPlugins(PluginCollection.java:100)
at play.Play.init(Play.java:286)
at play.server.Server.main(Server.java:158)
~ Packaging current version of the framework and the application to D:\Dropbox\eclipseProjectsClassi
c\MyApp.war ...
Traceback (most recent call last):
File "C:\play\play", line 153, in
status = cmdloader.commands[play_command].execute(command=play_command, app=play_app, args=remai
ning_args, env=play_env, cmdloader=cmdloader)
File "C:\play\framework\pym\play\commands\war.py", line 65, in execute
package_as_war(app, env, war_path, war_zip_path, war_exclusion_list)
File "C:\play\framework\pym\play\utils.py", line 117, in package_as_war
copy_directory(app.path, os.path.join(war_path, 'WEB-INF/application'), war_exclusion_list)
File "C:\play\framework\pym\play\utils.py", line 230, in copy_directory
shutil.copyfile(from_, to_)
File "C:\play\python\lib\shutil.py", line 53, in copyfile
fdst = open(dst, 'wb')
IOError: [Errno 2] No such file or directory: 'D:\\Dropbox\\eclipseProjectsClassic\\MyApp.war\\WEB-
INF/application\\MyApp.war\\WEB-INF\\application\\MyApp.war\\WEB-INF\\application\\MyApp.war\\WEB
-INF\\application\\MyApp.war\\WEB-INF\\application\\MyApp.war\\WEB-INF\\application\\test\\data
\\DataCollectorTest.java'
UPDATE I've solved the UnsupportedClassVersionError by changing the JAVA_HOME system variable to jdk7 directory. The IOError is still coming up though.
UPDATE2 Solved IOError by changing te output directory to "C:\MyApp.war"
A: If I understood right from the release notes of Play 1.2.4RC1, Play 1.2.3 did not have full Java 7 support. Try it with the new Play 1.2.4 release candidate from the Play framework download page? It's release notes tell that "Java 7 is now supported out of the box in play".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to avoid the blink image when save the image after rotate animation? I am confusing the translate animation and rotate animation. In my game I use this two animations, after completing the animation I am save my image. In translate animation it is fine, but after completing rotate animation my image is blink once. See my code in bellow, please solve my problem……..
Why anyone not respond my question, it is not understand or I am asking any wrong question ? Please tell me reason.................
Thanks.
Bitmap bmp=BitmapFactory.decodeResource(getResources(),R.drawable.train);
//1)
TranslateAnimation TAnimation=new TranslateAnimation(0, 0, 0,-100);//bottom to start
TAnimation.setInterpolator(new LinearInterpolator());
TAnimation.setDuration(2000);
TAnimation.setFillAfter(false);
TAnimation.setFillEnabled(true);
//TAnimation.setFillBefore(true);
Train.startAnimation(TAnimation);
TAnimation.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
RelativeLayout RL=(RelativeLayout)findViewById(R.id.rl);
param=new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
param.setMargins(x, y, 0, 0);
Train.setLayoutParams(param);
Train.setImageBitmap(bmp);
}
});
//x and y values are exact position of compliting translateanimation position
//2)
RotateAnimation RAnimation=new RotateAnimation(0,90,50,25);
RAnimation.setInterpolator(new LinearInterpolator());
RAnimation.setDuration(2000);
RAnimation.setFillAfter(false);
TAnimation.setFillEnabled(true);
//RAnimation.setFillBefore(true);
Train.startAnimation(RAnimation);
RAnimation.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
RelativeLayout RL=(RelativeLayout)findViewById(R.id.rl);
param=new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
param.setMargins(x, y, 0, 0);//x and y values are exact position of compliting translateanimation position
Train.setLayoutParams(param);
Train.setImageBitmap(bmp);
}
});
A: i had that problem but it's reaaaaally simple to fix. You don't need to implement the animation listener, simple don't do it (i had your problem because I use that way).
Do your animation and before call the animation method:
setFillAfter(true); //this save view at the end of the animation
Like so:
//my animation
final Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_up);
//hide login content
content.setVisibility(View.GONE);
//animContent = AnimationUtils.loadAnimation(getActivity(), R.anim.show_up);
rotation.setFillAfter(true);
//animate the arrow
arrow.startAnimation(rotation);
So, delete the listeners and change your setFillAfter(false) to TRUE. Will works ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Greenfoot actor gets removed after compile I create a new scenario, add new world subclass, add a new actor subclass, then compile. I drag that new actor to the scenario and press the compile button and that actor disappears. Am I missing something here? I hope I am. I'm running this from the usb using the standalone version.
A: The actors you drag to the scenario are temporary - if you add them that way you have to drag them there each time you compile.
You've two options, either drag the actors where you want then right click the world and hit the "save the world" button, or edit the world's constructor to add your actors in where you want them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: RowVersion and Performance I was wondering if there was an performance implications of adding a rowversion column on a table in a Sql-Server database?
A: There are few performance implications, rowversion is just a new name for the old timestamp datatype. So your database will need to store the additional binary field. Your performance will suffer much more when you try to do queries on this data such as:
SELECT *
FROM MyTable
WHERE rowVersion > @rowVersion
Which is the common way that can be used to get the list of updated items since last @rowVersion.
This looks fine and will work perfect for a table with say 10,000 rows. But when you get to 1M rows you will quickly discover that it has always been doing a tablescan and your performance hit is because your table now no longer fits entirely within the RAM of the server.
This is the common problem that is encountered with the rowVersion column, it is not magically indexed on it's own. Also, when you index a rowVersion column you have to accept that the index will often get very fragmented over time, because the new updated values are always going to be at the bottom of the index, leaving gaps throughout the index as you update existing items.
Edit: If you're not going use the rowVersion field for checking for updated items and instead you're going to use it for consistency to ensure that the record isn't updated since you last read, then this is going to be a perfectly acceptable use and will not impact.
UPDATE MyTable SET MyField = ' @myField
WHERE Key = @key AND rowVersion = @rowVersion
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Make background position variable I'm using this code...
document.getElementById('a1').style.backgroundPosition = '0px 0px';
and it works fine but is there anyway to make the positioning variable with javascript?
like so...
document.getElementById('a1').style.backgroundPosition = '0px VariableHere';
A: Since the background position is a string, you can just concatenate your value in.
For example:
var yValue = 20;
document.getElementById('a1').style.backgroundPosition = '0px ' + yValue + 'px';
A: var bgPos = '20px';
document.getElementById('a1').style.backgroundPosition = '0px ' + bgPos;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cucumber "--format progress" doesn't work In my cucumber.yml I've tried to add this option (default: --drb --format progress), but it return an error :
Exception encountered: #<ArgumentError: wrong number of arguments (3 for 2)
Error creating formatter: progress>
When I take it in brackets default: --drb --"format progress" it doesn't helps:
invalid option: --format progress (OptionParser::InvalidOption)
So maybe there is no option, but it should be
And "format pretty" works correctly without any brackets.
I want see not all scenarios in console, but just which has an errors, perhaps there is another way to do this.
Full trace:
wrong number of arguments (3 for 2)
Error creating formatter: progress (ArgumentError)
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/activerecord-3.1.0/lib/active_record/base.rb:1543:in `initialize'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:168:in `new'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:168:in `block in formatters'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:163:in `map'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:163:in `formatters'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:68:in `build_tree_walker'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/runtime.rb:42:in `run!'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/main.rb:43:in `execute!'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/main.rb:20:in `execute'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/bin/cucumber:14:in `<top (required)>'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/bin/cucumber:19:in `load'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/bin/cucumber:19:in `<main>'
And If I write option in cucumer.yml the error slightly different:
Exception encountered: #<ArgumentError: wrong number of arguments (3 for 2)
Error creating formatter: progress>
backtrace:
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/activerecord-3.1.0/lib/active_record/base.rb:1543:in `initialize'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:168:in `new'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:168:in `block in formatters'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:163:in `map'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:163:in `formatters'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/configuration.rb:68:in `build_tree_walker'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/runtime.rb:42:in `run!'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/cucumber-1.1.0/lib/cucumber/cli/main.rb:43:in `execute!'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/test_framework/cucumber.rb:24:in `run_tests'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/run_strategy/forking.rb:13:in `block in run'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/forker.rb:21:in `block in initialize'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/forker.rb:18:in `fork'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/forker.rb:18:in `initialize'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/run_strategy/forking.rb:9:in `new'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/run_strategy/forking.rb:9:in `run'
/home/alder/.rvm/gems/ruby-1.9.2-p290@global/gems/spork-0.9.0.rc9/lib/spork/server.rb:48:in `run'
/home/alder/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/drb/drb.rb:1558:in `perform_without_block'
/home/alder/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/drb/drb.rb:1518:in `perform'
/home/alder/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/drb/drb.rb:1592:in `block (2 levels) in main_loop'
/home/alder/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/drb/drb.rb:1588:in `loop'
/home/alder/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/drb/drb.rb:1588:in `block in main_loop'
I have a Spork by the way maybe it's a problem.
A: Based on the updated information in your question, I think I see the problem (hence I'm posting another answer as it's completely different to my other one). It looks like Cucumber is trying to instantiate an ActiveRecord class, so I suspect you have a model named 'Progress' in your project somewhere, which Cucumber is trying to create instead of of the actual formatter.
I was able to reproduce your problem (close enough, anyway) by adding this class in the 'support' folder:
class Progress
def initialize
raise "I don't exist!"
end
end
According to the docs, you should be able to specify a fully qualified class name here i.e. --format Cucumber::Formatter::Progress, to force Cucumber to use it's own formatter. However, I tried this and it still doesn't work, there seems to be a bug in how Cucumber resolves the fully-qualified name.
I was able to get around this by adding this line to my env.rb file:
require 'cucumber/formatter/progress'
Which then allowed me to run cucumber --format progress successfully.
I think that, as env.rb gets executed before any other code, then Cucumber's Progress class will be the first one that gets found when creating the formatter.
A: It looks from the output you've pasted in, that you have an extra angle ('>') bracket floating around in your cucumber.yml file:
Error creating formatter: progress>
Unless that's a typo in your question, for some reason Cucumber is trying to create a formatter named 'progress>', so you probably just need to find and remove the extra angle bracket.
Edit: This wasn't the problem at all, see my other answer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: confused on how my code work and want to understand the logic in it Please dont discourage this question..I am very new to c++ and really want to understand the code I work on.
// bintodec.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main(){
string inp;
int dec = 0;
char base;
cout << "Input a number: ";
cin >> inp;
cout << "Input the base your number is in: ";
cin >> base;
for(int i = inp.length()-1, j = 0; i >= 0; i--, ++j) dec += (inp[i]-48) * pow((float)base-48, j);
cout << "Your number in base 10 is: " << dec <<endl;
system("pause");
return 0;
}
I really want to understand how this FOR LOOP runs the INPUT NUMBER and BASE, to then get an answer.
so lets say I INPUT 110 BASE 2 PRINT: 6
*How the for loop is doing it
thanks all!
A: for(int i = inp.length()-1, j = 0; i >= 0; i--, ++j)
dec += (inp[i]-48) * pow((float)base-48, j);
48 is the value of '0', and they are supposed to be consecutive up to '9' which would be 57. You should be able to work out how the job is done with that in mind.
A: They are taking the ASCII input values plugged into inp, and doing a conversion to the actual decimal equivalents by subtracting off the ASCII offset for that character. At that point, they are merely adding each position of the input decimal raised to the power of the base for that decimal's positon. For instance, for a number input as BASE-2, each numeral in a binary number is equivalent to the following:
2^2 2^1 2^0
| | |
1 1 0
Therefore, to convert this to BASE-10, you would add up (1*2^2) + (1*2^1) which equals 4 + 2 = 6.
If you had input a hexadecimal number (i.e, BASE-16), say 0xA5, it would look like the following:
16^1 16^0
| |
A 5
That would then be equivalent to 10*16^1 + 5*16^0 which equals 160 + 5 = 165
A: '0'=48, so this loop is picking up the digits starting from the end, converting the character to a number, multiplying by base raised to the correct power and summing the result.
A: The 48 just converts ASCII input to its numeric representation, '0' = 48, '1' = 49, etc. What the for loop is doing is iterating over each character entered, raising it to the base power entered, and adding it to make a decimal (base 10) answer.
If you're wondering why mathematically it works, check http://en.wikipedia.org/wiki/Radix
3657 in base 6 for example = 3x6^4 + 6x6^3 + 5x6^2 + 7x6 in decimal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Facebook Social Graph API: "Annoying or Abusive" Error Message I got the following exception from the Social Graph API:
(OAuthException) Block! You are engaging in behavior that may be
considered annoying or abusive by other users.: You have been blocked
from Body of an error/warning message. Title is: Block! You are
engaging in behavior that may be considered annoying or abusive by
other users. because you repeatedly misused this feature. This block
will last anywhere from a few hours to a few days. When you are
allowed to reuse this feature, please proceed with caution. Further
misuse may result in your account being permanently disabled. For
further information, please visit our {= FAQ page}.
My program makes thousands of calls, but the call that threw the exception was like this:
graph.facebook.com/search?q=6511+club&access_token=...
I'm not writing anything back to the API, so I don't see how I could be violating any abuse/annoyance rules. At first I thought I might have gone over the rate limit but this thread says the exception message for that would look like this:
Facebook.GraphAPIError: (#613) Calls to stream have exceeded the rate of 600 calls per 600 seconds.
My program is calling the above Event search endpoint with a new value for the q parameter repeatedly. For each event returned, my program:
*
*(calls /eventId) Gets the Event detail
*(calls /pageId) Get place Page of the Event's location if the Event's location references a Facebook place Page
*(calls /eventId/attending) Get the ids of the User profiles who are attending or maybe attending
*(calls /?ids=...) Get the User profiles of the Users who are attending or maybe attending.
I'm using the Facebook C# SDK. All my calls include an access token (from my personal User profile).
A: It's not your app which is blocked, it's your user which is blocked. Your user was identified by Facebook's automated system as a bot (which it really is actually). Next step - your user will be banned from Facebook. You're making too many calls harvesting data from Facebook by a single user. You need to rethink your app purpose and whther you need to call this data to store or your users can get it on demand from the API. Most offensive calls here are /eventId/attending and ids per each event. Call it thousand times on thousand events and the user will be blocked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: GUI for single interface approach I've made a small application using MDI but I want to make another one where there is only one main window and the main container changes or updates. I'm sure this can be done without creating multiple panels but I've been doing a bit of reading and I can't seem to find how can I do this.
A: For my scrum information radiator (full screen application for a big TV in portrait) I decided to use a set of controls from Actipro. I have multiple windows, but only one visible at a time. The user can use the arrow keys to "swipe" windows in and out just like they're used to do in smartphones.
The control used was the ZapPanel, as seen in my xaml below:
<ListBox x:Name="listBox" Grid.RowSpan="2" BorderThickness="0" Focusable="False" SelectionMode="Single"
SnapsToDevicePixels="True" VerticalContentAlignment="Top" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.VerticalScrollBarVisibility="Hidden" Background="Black">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<views:ZapPanel AreChildrenWrapped="True" Orientation="Horizontal" AreLeavingElementsAnimated="True" Background="Black" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
<StackPanel Orientation="Horizontal" Height="30" Margin="10" VerticalAlignment="Top" Opacity="0.5" >
<Button Click="PrevButtonClick">Prev</Button>
<Button Click="NextButtonClick">Next</Button>
</StackPanel>
</Grid>
A: If I understand you correctly you want to keep only one form. You can use tab control and switch between different pages, or create a set of user controls and then manage yourself what user control to show
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why does only one (the last) XML file is saved? I use this below to save me the contents of the XML addresses I have in array. However only one XML is saved, specifically the last one. What am I missing here?
$filenames = array('xml url','xml url','xml url');
foreach( $filenames as $filename) {
$xml = simplexml_load_file( $filename );
$xml->asXML("test.xml");
}
A: You appear to be opening each XML file, then saving them in the same location. File 1 is written, then File 2 overwrites it, then File 3... In short, the last file will overwrite the previous ones, and therefore "only the last one is saved".
What exactly are you trying to do here?
A: You save them all as the same name, so of course the earlier ones will be lost.
A: Try this:
$filenames = array('xml url','xml url','xml url');
foreach( $filenames as $key => $filename) {
$xml = simplexml_load_file( $filename );
$xml->asXML('test' . $key. '.xml');
}
That should save the files sequentially as test0.xml, test1.xml, test2.xml and so on.
If you want all your loaded XML URL's to be appended to a single file, you can do something like this:
$filenames = array('xml url','xml url','xml url');
$fullXml = array();
foreach( $filenames as $key => $filename) {
$xml = simplexml_load_file( $filename );
// Convert the simplexml object into a string, and add it to an array
$fullXml[] = $xml->asXML();
}
// Implode the array of all our xml into one big xml string
$fullXml = implode("\n", $fullXml);
// Load the new big xml string into a simplexml object
$xml = simplexml_load_string($fullXml);
// Now we can save the entire xml as your file
$xml->asXml('test.xml');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jboss SLF4J Security exception when deploying I had to deploy applications at work and i tried to deploy a file called "ReportService.WAR", then i deploy it using Jboss 6.0.0 and got this error
Deployment "vfs:///apps/jboss/server/default/deploy/ReportServices.war" is in error due to the following reason(s): java.lang.SecurityException: class "org.apache.commons.logging.impl.SLF4JLog"'s signer information does not match signer information of other classes in the same package
at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:1370) [:2.2.0.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:1316) [:2.2.0.GA]
at org.jboss.deployers.plugins.main.MainDeployerImpl.checkComplete(MainDeployerImpl.java:968) [:2.2.0.GA]
at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.checkComplete(MainDeployerPlugin.java:82) [:6.0.0.Final]
at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.checkComplete(ProfileControllerContext.java:138) [:0.2.2]
at org.jboss.profileservice.deployment.hotdeploy.HDScanner$HDScanAction.deploy(HDScanner.java:246) [:0.2.2]
at org.jboss.profileservice.deployment.hotdeploy.HDScanner$HDScanAction.complete(HDScanner.java:192) [:0.2.2]
at org.jboss.profileservice.management.TwoPCActionWrapper.doComplete(TwoPCActionWrapper.java:57) [:0.2.2]
at org.jboss.profileservice.management.actions.AbstractTwoPhaseModificationAction.complete(AbstractTwoPhaseModificationAction.java:74) [:0.2.2]
at org.jboss.profileservice.management.actions.AbstractTwoPhaseModificationAction.prepare(AbstractTwoPhaseModificationAction.java:95) [:0.2.2]
at org.jboss.profileservice.management.ModificationSession.prepare(ModificationSession.java:87) [:0.2.2]
at org.jboss.profileservice.management.AbstractActionController.internalPerfom(AbstractActionController.java:234) [:0.2.2]
at org.jboss.profileservice.management.AbstractActionController.performWrite(AbstractActionController.java:213) [:0.2.2]
at org.jboss.profileservice.management.AbstractActionController.perform(AbstractActionController.java:150) [:0.2.2]
at org.jboss.profileservice.management.AbstractActionController.perform(AbstractActionController.java:135) [:0.2.2]
at org.jboss.profileservice.deployment.hotdeploy.HDScanner.scan(HDScanner.java:146) [:0.2.2]
at org.jboss.profileservice.deployment.hotdeploy.HDScanner.run(HDScanner.java:90) [:0.2.2]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) [:1.6.0_10]
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317) [:1.6.0_10]
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150) [:1.6.0_10]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98) [:1.6.0_10]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181) [:1.6.0_10]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205) [:1.6.0_10]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [:1.6.0_10]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [:1.6.0_10]
at java.lang.Thread.run(Thread.java:619) [:1.6.0_10]
Now, i didn't do any coding activity so i didn't know anything inside the code..but i do check the file and find if it used slf4j 1.6.0 while in jboss lib used sl4j 1.5.11, assuming this was the key problem i tried replace the jar in lib with 1.6.0 and ended unsuccess..anybody know what is the problem and how to fix it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Possible to send automated email? The iOS SDK class MFMailComposeViewController can be used to let the user compose an email message.
What I'd like to do, is for the iOS app to send an email in the background, with no user interaction. Is this at all possible/allowed in the iOS SDK?
A: Nope. There isn't any API available to do this. You'd need to roll your own SMTP client and have the user enter credentials into your application. On top of that Apple may not approve this.
A: Unfortunately, I don't think Apple would ever allow this because (for example) then you could just get everyone's email address by auto-sending mail to yourself. :(
A: I actually wanted to implement something like this for the express purpose of alerting me when a critical error happens on an app in the app market.
Best solution would be to create an API (just ping a php file or something), and have it send the relative alert message to your email).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Segmentation fault when adding a vector. (C++) So I've got a pretty basic class that has a few methods and some class variables. Everythings working great up until I add a vector to the member variables in the header file:
std::vector <std::string> vectorofstuff;
If all I do is add this line then my program run perfectly but at the end, after all the output is there, I get a message about a seg fault.
My first guess is that I need to call the destructor on the vector, but that didn't seem to work. Plus my understanding is I don't need to call the destructor unless I use the word 'new'.
Any pushes in the right direction? Thanks bunches!
A: I guess the following either happened to you, or it was something similar involving unrealised dependencies/headers. Either way, I hope this answer might show up on Google and help some later, extremely confused programmer figure out why they're suddenly observing arbitrary crashes.
So, from experience, this can happen if you compile a new version of SomeObject.o but accidentally have another object file #include an old version of SomeObject.hpp. This leads to corruption, which'll be caused by the compiler referring to outdated member offsets, etc. Sometimes this mostly works and only produces segfaults when destructing objects - either related or seemingly distant ones - and other times the program segfaults right away or somewhere in-between; I've seen several permutations (regrettably!).
For anyone wondering why this can happen, maybe this is just a reflection of how little sleep I get while programming, but I've encountered this pattern in the context of Git submodules, e.g.:
*
*MyRepo
*/ GuiSubmodule
*/ HelperSubmodule
*/ / GuiSubmodule
If (A) you have a new commit in GuiSubmodule, which has not yet been pulled into HelperSubmodule's copy, (B) your makefile compiles MyRepo/uiSubmodule/SomeObject.o, and (C) another translation unit - either in a submodule or in the main repo via the perils of #include - links against an older version of SomeObject.hpp that has a different class layout... You're in for a fun time, and a lot of chasing red herrings until you finally realise the simple mistake.
Since I had cobbled together my build process from scratch, I might've just not been using Git/make properly - or strictly enough (forgetting to push/pull all submodules). Probably the latter! I see fewer odd bugs nowadays at least :)
A: You are probably corrupting the memory of the vectorofstuff member somewhere within your class. When the class destructor is called the destructor of the vector is called as well, which would try to point and/or delete to invalid memory.
A: I was fooling around with it and decided to, just to be sure, do an rm on everything and recompile. And guess what? That fixed it. I have no idea why, in the makefile I do this anyway, but whatever, I'm just glad I can move on and continue working on it. Thanks so much for all the help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Still confused about Pthreads I am using an old exam as a study guide and one of the questions is to use pthreads to fill in the following code:
#include <pthread.h>
#include <stdio.h>
typedef struct {
int a;
int b;
} local_data;
void *foo(void *arg);
int main() {
int a = 12;
int b = 9;
pthread_t tid;
pthread_attr_t attr;
local_data local;
local.a = a;
local.b = b;
pthread_attr_init(&attr);
/* block of code we are supposed to fill in (my attempt at filling it in)
pthread_create(&tid, &attr, foo, &local);
pthread_join(tid, NULL);
*/
b = b - 5;
printf("program exit. a = %d, b = %d\n", a, b);
return 0;
}
void *foo(void *arg) {
int a, b;
local_data *local = (local_data*)arg;
/* block of code we are supposed to fill in (my attempt at filling it in)
a = local->a;
b = local->b;
a++;
*/
printf("program exit. a = %d, b = %d\n", a, b);
pthread_exit(0);
}
What we are supposed to do is make our pthreads mimic this code:
int main() {
int a = 12;
int b = 9;
int fid = fork();
if (fid == 0) {
a++;
}
else {
wait(NULL);
b = b - 5;
}
printf("program exit. a = %d, b = %d\n", a, b);
return 0;
}
I've been really lost on this section and I am sure I do not understand it as well as I should (or at all). Would appreciate any answers to help me grasp the concept.
A: This line is wrong:
pthread_create(&tid, &attr, foo(local), NULL);
pthread_create's signature is:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
The third argument is a function and the last argument is it's argument, so instead of calling the function (foo(local)), pass the function and the argument separately:
pthread_create(&tid, &attr, foo, &local);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Querying pages in WordPress by template name I have a template named "Foo" in "foo.php", I would like to be able to select all pages that are using that template. I have searched for awhile now but have not been able to find a successful way to do this... Can somebody enlighten me on the proper/only way to do this?
A: Robot's answer is good, but I thought I'd clarify a few things.
First, You should use the variable for the query you created, so it would be $query->have_posts() etc.
Second, you should specify post_type. I used any, so that it will pull any post types except for revisions.
Last, if this is in a page with any other WP loops, you may want to use wp_reset_query. I added one below and one above just in case, but you only really need this if you have another loop above or below. Remove it if you don't.
Here is the code:
wp_reset_query();
$query = new WP_Query( array(
'post_type' => 'any',
'meta_key' => '_wp_page_template',
'meta_value' => 'foo.php'
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post(); // WP loop
the_title();
endwhile; // end of the loop.
} else { // in case there are no pages with this template
echo 'No Pages with this template';
}
wp_reset_query();
Hope that helps someone!! Happy coding!
A: This also works
$pages = get_pages(
array(
'meta_key' => '_wp_page_template',
'meta_value' => 'template.php'
)
);
foreach($pages as $page){
echo $page->post_title.'<br />';
}
http://jorgepedret.com/old/web-development/get-pages-by-template-name-in-wordpress/
A: You can get this by using following code
$query = new WP_Query( array( 'meta_key' => '_wp_page_template', 'meta_value' => 'foo.php' ) );
if ( have_posts() ) while ( have_posts() ) : the_post();
<?php the_title(); ?>
<?php endwhile; // end of the loop. ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Android "best practice" for team collaboration and development? we would to pick the community brains on the best and efficient way to do team collaboration on Android mobile development.
*
*Does some members work on the modules and turn it into jars and other team members use it?
*How to split work between developers and UI designers.
*How to do automated testings.
*How to effectively do testings on various mobile devices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: program to store details of an employee in a structure This is a program to store details of an employee in a structure. Although the program runs it shows many errors, it does not give me a chance to enter address. Why is the program not running properly . Where am I going wrong ?
#include <stdio.h>
#include <conio.h>
struct details
{
char name[30];
int age;
char address[500];
float salary;
};
int main()
{
struct details detail;
clrscr();
printf("\nEnter name:\n");
gets(detail.name);
printf("\nEnter age:\n");
scanf("%d",&detail.age);
printf("\nEnter Address:\n");
gets(detail.address);
printf("\nEnter Salary:\n");
scanf("%f",&detail.salary);
printf("\n\n\n");
printf("Name of the Employee : %s \n",detail.name);
printf("Age of the Employee : %d \n",detail.age);
printf("Address of the Employee : %s \n",detail.address);
printf("Salary of the Employee : %f \n",detail.salary);
getch();
}
This is the output I get:
A: Statement scanf("%d",&detail.age); will read 222 but not the newline you've entered. This newline will remain in input buffer and pass it to next input gets().
You can use getchar() method to remove some chars from the input buffer to avoid such problems.
char ch;
....
printf("\nEnter age:\n");
scanf("%d",&detail.age);
while((ch = getchar()) != '\n' && ch != EOF) { }
printf("\nEnter Address:\n");
gets(detail.address);
Another problem is the incorrect use of format specifier with printf function.
A: // To Developed Employee Details using LogIn Screen
// And access to add employee,view details by id, update data, delete
// using structure
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<dos.h>
#include<windows.h>
/*structure declaration*/
struct employee
{
char fname[20],lname[20];
int emp_id;
float emp_salary;
};
void main()
{
FILE *outfile, *infile,*temp;
struct employee input;
int a,op,o,n;
char pass[20],uname[30];
char ch;
int j,k,i;
char pass1[5]="amit", un[5]="amit",fnam[20],lnam[20];
//Design Part
printf("\n\n\t");
for(i=0;i<11;i++) {
printf("*");
usleep(50000);
}
usleep(500000); printf(" Welcome");usleep(500000);printf(" To ");usleep(500000);
printf("A"); usleep(500000); printf("X"); usleep(500000); printf("I"); usleep(500000); printf("O"); usleep(500000); printf("M");
usleep(500000); printf(" SOFTECH");usleep(500000);printf(" PVT.");usleep(500000);printf(" LTD. ");usleep(50000);
for(i=0;i<11;i++)
{
printf("*");
usleep(50000);
}
login:
printf("\n\n\t\t\t ~~~~~~~~~~~~~~~~~~~~~");
printf("\n\t\t\t | AUTHORIZE LOGIN |");
printf("\n\t\t\t ~~~~~~~~~~~~~~~~~~~~~");
printf("\n\n\t\t*-----------------------------------------*");
printf("\n\t\t User Name :- ");
gets(uname);
printf("\n\t\t Password(Provided By programmer) :- ");
for(i=0;i<4;i++)
{
ch = getch();
pass[i] = ch;
ch = '*' ;
printf("%c",ch);
}
printf("\n\t\t*-----------------------------------------*");
pass[i] = '\0';
getch();
if((strcmp(uname,un)==0) && (strcmp(pass,pass1)==0))
{
printf("\n\n\n\t\t @-------- Login Successful --------@"); //login successful then data will
menu:
printf("\n\n \t+++++++++++++++++ AMIT BEHERE PVT. LTD. +++++++++++++++++");
printf("\n\n\t\t #```````````````````````````#");
printf("\n\t\t | AB Employee Management |");
printf("\n\t\t #'''''''''''''''''''''''''''#");
printf("\n\t\t *---------------------------*");
printf("\t\n\t\t |\t1. Add Employee \t|\n\t\t |\t2. Display Employee\t|\n\t\t |\t3. Search Employee\t|\n\t\t |\t4. Update Employee\t|\n\t\t |\t5. Delete Employe\t|");
printf("\n\t\t *---------------------------*");
printf("\n\t Enter Option :- ");
scanf("%d",&op);
switch(op)
{
case 1: //Add Employee
outfile = fopen ("accounts.dat","a+");
if (outfile == NULL)
{
fprintf(stderr, "\n\tError opening accounts.dat\n\n");
}
printf("\n\tEnter Count Of Employee To Add :- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\t Enter First Name :- ");
scanf ("%s", input.fname);
printf("\n\t Enter Last Name :- ");
scanf ("%s", input.lname);
printf("\n\t Enter Employee Id :- ");
scanf ("%d", &input.emp_id);
printf("\n\t Enter Salary :- ");
scanf ("%f", &input.emp_salary);
// write entire structure to Accounts file
fwrite (&input, sizeof(struct employee), 1, outfile);
}
fclose(outfile);
break;
case 2: //Display All Records
infile = fopen ("accounts.dat","r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
}
rewind(infile);
while (fread (&input, sizeof(struct employee), 1, infile)==1)
{
printf("\n\t#---------------------------------------#");
printf ("\n\t| Name Of Employee %d -> %5s %5s \t|\n\t| Employee Id -> %4d \t\t|\n\t| Salary -> %8.2f\t\t|\n",i,
input.fname, input.lname, input.emp_id, input.emp_salary);
printf("\t#---------------------------------------#");
printf("\n");
i++;
}
i=1;
fclose(infile);
break;
case 3: //Search Employee
infile = fopen ("accounts.dat","r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
}
printf("\n\t Enter First name of Employee :-");
scanf("%s",&fnam);
printf("\n\t Enter Last name of Employee :-");
scanf("%s",&lnam);
rewind(infile);
while(fread(&input,sizeof(input),1,infile)==1)
{
if((strcmp(input.fname,fnam)==0)&&(strcmp(input.lname,lnam)==0))
{
printf("\n\t#-----------------------------------------------#");
printf ("\n\t| Name Of Employee -> %5s %5s \t\t|\n\t| Employee Id -> %4d \t\t\t|\n\t| Salary -> %8.2f\t\t\t|\n",
input.fname, input.lname, input.emp_id, input.emp_salary);
printf("\t#-----------------------------------------------#");
}
}
fclose(infile);
break;
case 4: //Employee Update
infile = fopen ("accounts.dat","rb+");
if (infile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
}
printf("\n\tEnter the Employee Name to Modify: ");
scanf("%s",fnam);
printf("\n\tEnter Last Name of Employee :-");
scanf("%s",&lnam);
rewind(infile);
while(fread(&input,sizeof(input),1,infile)==1)/// fetch all record from file
{
if( (strcmp(input.fname,fnam)==0) && (strcmp(input.lname,lnam)==0)) ///if entered name matches with that in file
{
update:
printf("\n\t\t *````````````````````````````*");
printf("\n\t\t | Employee Details Parameter |");
printf("\n\t\t *''''''''''''''''''''''''''''*");
printf("\n\t\t +-------------------+");
printf("\t\n\t\t |\t1. First Name \t|\n\t\t |\t2. Last Name\t|\n\t\t |\t3. Employee Id\t|\n\t\t |\t4. Salary\t|\n\t\t ");
printf("+-------------------+");
printf("\n");
printf("\n\t Enter Field Option to Update :- ");
scanf("%d",&o);
switch(o)
{
case 1:
printf("\n\t Enter First Name :- ");
scanf ("%s", input.fname);
break;
case 2:
printf("\n\t Enter Last Name :- ");
scanf ("%s", input.lname);
break;
case 3:
printf("\n\t Enter Employee Id :- ");
scanf ("%d", &input.emp_id);
break;
case 4:
printf("\n\t Enter Salary :- ");
scanf ("%f", &input.emp_salary);
break;
}
printf("\n Do you Wish to Continue Updation for Given Employee[Y/N] ");
scanf("%s",&ch);
if(ch=='y'||ch=='Y')
{
goto update;
}
fseek(infile,-sizeof(struct employee),SEEK_CUR); /// move the cursor 1 step back from current position
fwrite(&input,sizeof(struct employee),1,infile); /// override the record
fclose(infile);
}
}
break;
case 5: //Delete Employee
outfile = fopen ("accounts.dat","rb+");
printf("\n\tEnter First Name of Employee :- ");
scanf("%s",fnam);
printf("\n\tEnter Last Name of Employee :-");
scanf("%s",&lnam);
temp = fopen("temp.dat","wb"); /// temporary file is created
rewind(outfile); /// move record to starting of file
while(fread(&input,sizeof(struct employee),1,outfile) == 1) /// read all records from file
{
if(strcmp(input.fname,fnam) != 0 &&(strcmp(input.lname,lnam)!=0) ) /// if the entered record match
{
fwrite(&input,sizeof(struct employee),1,temp); // move all records except the one that is to be deleted to temp file
}
}
fclose(outfile);
fclose(temp);
remove("accounts.dat"); // Delete orginal file
rename("temp.dat","accounts.dat"); // rename the temp file to original file name
outfile = fopen("accounts.dat", "rb+");
printf("\n\tRecord Deleted Successfully...\n");
break;
default: printf("\n\t\t Enter Valid Option");
goto menu;
}
printf("\n Do you Wish to Continue With Employee Management Service[Y/N] ");
scanf("%s",&ch);
if(ch=='y'||ch=='Y')
{
goto menu;
}
}
else
{
system("cls");
printf("\n\n \t++++++++++++ Welcome To AMIT BEHERE World. ++++++++++++");
printf("\n\n\t\tInvalid UserName or Password");
printf("\n\t\tTry Again");
goto login;
}
}
A: #include <stdio.h>
#include <conio.h>
#include<string.h>
struct details
{
char name[30];
int age;
char address[500];
float salary;
};
int main()
{
struct details detail;
printf("\nEnter name:\n");
gets(detail.name);
printf("\nEnter age:\n");
scanf("%d",&detail.age);
printf("\nEnter Address:\n");
scanf("%s",&detail.address);
printf("\nEnter Salary:\n");
scanf("%f",&detail.salary);
printf("\n\n\n");
printf("Name of the Employee : %s \n",detail.name);
printf("Age of the Employee : %d \n",detail.age);
printf("Address of the Employee : %s \n",detail.address);
printf("Salary of the Employee : %f \n",detail.salary);
getch();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Object Oriented Design for iPhone So I've run into this a few times, and am new to OOD so not sure if there is a good way to do this or not.
But basically, I have a MainViewController, and then I push a new DetailViewController. In my MainViewController, I have a Reset method that basically resets everything to their default values.
If I want to put the button to call Reset in the DetailViewController though, how do I call the method since it's in the MainViewController class?
What I've done before is have a reference to the ParentController (in this case, MainViewController), and then call it that way from the DetailViewController. I don't know if this is a good practice though and if there are better ways to do something like this.
Thanks.
A: You probably want to have the MainViewController be a delegate to DetailViewController. Apple's frameworks use this pattern all over the place so you can use that as an example. When you do references like this, be sure it doesn't form a retain cycle or you will probably leak memory; don't retain the delegate.
A: You are following the "delegate pattern" and its one of the very good designs. I would recommend using the same approach. You can check out the book "Cocoa Design Patterns", it should provide you a good understanding of design patterns.
In your case, Create a delegate of type "id" in DetailsViewController, write properties for it and set it when you are pushing the DetailsViewController object from your main view. Then call the method using "ResondsToSelector" on that delegate. Let me know if you want a code snippet.
A: First of all, consider if it makes sense to have a reset button in the detail view. It might not make sense from a UI organization standpoint for the same reason it's a little inconvenient from an OOD perspective.
Okay, suppose you have decided that it you do want to have the button. Then in some sense it seems that DetailViewController has to be aware of the larger context it's in. It has to know that there's something to reset. I think it's fine to assign a property on DetailViewController a pointer to MainViewController, and declare it as MainViewController *. Unless it's somehow useful for DetailViewController to know that it needs to reset something, but not really know what, then I don't think you need to abstract the fact that DetailViewController is talking to a MainViewController, and leave open the possibility that DetailViewController could be the child of a different kind of parent. So you don't need the protocol.
Option C, you can have some object representing your data model. I will say it is an instance of class Thing, and conforms to protocol ThingModel. You give both MainViewController and DetailViewController a pointer to a ThingModel, i.e. a property declared as id. When they want to reset, they call [self.thingModel reset].
Now, that would reset your data, but how do you reset your views? Many possible options. For one, when DetailViewController calls reset, the next lines can have DetailViewController do what it needs to do to reflect the data model, which is now empty. And maybe MainViewController doesn't do anything yet, but updates itself to match the data model next time it's shown.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Alter existing jQuery to make span placeholder I have some jQuery that provides a placeholder as long as my <label for=""> matches the input name and ID. However, that's not the case so I've decided to just use a <span> for the placeholder instead. Can someone help alter my jQuery to make the <span> class "holder" I'm using work? The goal is to have the placeholder stay on focus, disappear when input exists, then reappear if the input disappears.
Here's the HTML I'm using:
<div id="placeholder">
<span class="holder">This is the placeholder...</span>
<%= f.text_area :body, :id =>"Placeholder" %>
</div>
And my current jQuery:
$(document).ready(function() {
$('textarea').keyup(function() {
if ($(this).val().length) {
$('label[for="' + $(this).attr('name') + '"]').hide();
} else {
$('label[for="' + $(this).attr('name') + '"]').show();
}
});
});
Thanks!
A: You want to bind to the focus and blur events and absolutely position the <span> over the <textarea>. Start with some CSS:
#placeholder {
position: relative;
}
.holder {
position: absolute;
top: 2px;
left: 2px;
display: none;
}
And then the jQuery:
$('.holder').click(function() {
$(this).siblings('textarea').focus();
});
$('#Placeholder').focus(function() {
$(this).siblings('.holder').hide();
});
$('#Placeholder').blur(function() {
var $this = $(this);
if($this.val().length == 0)
$(this).siblings('.holder').show();
});
$('#Placeholder').blur();
The final $('#Placeholder').blur() call is there to initialize the state of the <span> so that it will be in the right state if the <textarea> starts out with content.
And a quick demo: http://jsfiddle.net/ambiguous/PLrf3/1/
BTW, having id="placeholder" and id="Placeholder" in the same page might lead to some confusion. You would be better off choosing a standard scheme (camelCase, words-and-hyphens, or whatever) for your id attributes and sticking to it. Just a case difference might be confusing and might look like a typo.
A: Something like this should work:
$(function() {
$("span.holder + textarea").keyup(function() {
if($(this).val().length) {
$(this).prev('span.holder').hide();
} else {
$(this).prev('span.holder').show();
}
});
});
This should work for all textareas on page if they have span.holder preceding them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to grab the last line of wget? $ wget --output-document=/dev/null http://website.com/file.jpg
Resolving speedtest.sea01.softlayer.com... 67.228.112.250
Connecting to speedtest.sea01.softlayer.com|67.228.112.250|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1986284 (1.9M) [image/jpeg]
Saving to: `/dev/null'
2011-10-02 22:38:04 (337 KB/s) - `/dev/null' saved [1986284/1986284]
Everything works above, but I would like to know how to store the last line in a variable OR pass it through GREP -> /((.+))/
(I'm trying to parse for the average KB/s)
A: You can redirect the output of the command. For example:
$ wget --output-document=/dev/null http://website.com/file.jpg 2>&1 | tee /tmp/somefile
$ tail -n 1 /tmp/somefile
A: If you have apache installed, you can use Apache HTTP server benchmarking tool:
ab -n1 http://website.com/file.jpg | grep -F 'Transfer rate:'
you get output like:
Transfer rate: 1722.38 [Kbytes/sec] received
A: wget -O /dev/null http://website.com/file.jpg 2>&1 |
sed -n '\%/dev/null%!d;s/.*(//;s/).*//p'
On my system, the final output line is empty, otherwise the sed addressing would be simpler. This is on Ubuntu out of the box; if your sed is different, you may need to adapt the script slightly.
(I tried with grep -o '(.*)' at first, but there is other text in parentheses earlier in the output from wget.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using FB.api("/me/apprequests") only returns one request. It used to return all. How do you get all with the Javascript API? Using
FB.api("/me/apprequests", function(response){
});
I am only getting one request no matter what. Also, the left sidebar is only ever showing a 1 next to my application.
Example: I have 4 requests currently pending but it only shows a 1 next to the icon in my favorites list and it only loads one request in my "Message Center" within my app.
Anyone else seeing this?
EDIT: I've also confirmed the same happens with the php api.
EDIT#2: I've created a bug if you want to mark repro or subscribe: http://developers.facebook.com/bugs/141622979268860?browse=search_4e8a33c8136a20101558833
A: I can confirm that indeed this issue seems to be a bug and a very critical one at that. Both the Graph API and FQL return a single apprequest which happens to be the latest one for me as well. And, as jestro describes, Facebook is also displaying a "1" next to the name of the app when there are clearly more than one apprequest for my app.
I stumbled across this problem because I was in the middle of implementing apprequest functions for my game and now it looks like I'll have to set aside implementing the apprequest system for my game while this issue is resolved. Hopefully someone from Facebook reads this and the problem will get resolved soon. To that end, I'd like to encourage everyone to confirm this issue for themselves and to subscribe to the bug report jestro submitted so Facebook will pay attention to it.
Thanks all!
btw, if there is a critical bug like this in both Graph API and FQL, does this mean that apprequests for all games are now broken? If not, what are they doing differently that makes it so they are not affected by this issue?
A: This sounds like a bug that you should log with Facebook. As a workaround, you should still be able to use an FQL query to get all results:
SELECT recipient_uid, request_id, app_id
FROM apprequest
WHERE recipient_uid = me() AND app_id = 182197005148613
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What does -n in if [ -n "${TEMP_FILE_LIST}" ] do? What does -n in if [ -n "${TEMP_FILE_LIST}" ] do for this shell script?
A: -n tests for a non-zero-length string
A: if [ -n "${TEMP_FILE_LIST}" ]
tests if the argument "${TEMP_FILE_LIST}" does not have zero length.
You can also check
if [ ! -z "${TEMP_FILE_LIST}" ]
A: From help test:
-n STRING
STRING True if string is not empty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Why is NSArray empty at the time when UITableView Cell is selected? I have list of file with some name of friends. I am trying to understand UITableViewNavigation . I load the list from a file but when I select a cell the Data Array at that point seems empty and I can not work out why.
At this method I get this error
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FriendsNameViewController *newView =[[FriendsNameViewController alloc] initWithNibName:@"FriendsNameViewController" bundle:nil];
[self.navigationController pushViewController:newView animated:YES];
//Crashes here
NSString *temp = [dataArray objectAtIndex:indexPath.row];
NSLog(@"%@",temp);
[[newView labelx] setText:[NSString stringWithFormat: @"%@" ,temp]];
}
2011-10-03 14:43:08.411 navman2[69691:b303] * Terminating app due to
uncaught exception 'NSRangeException', reason: '* -[NSMutableArray
objectAtIndex:]: index 2 beyond bounds for empty array'
Interface
#import <UIKit/UIKit.h>
@interface TableViewController : UITableViewController
{
NSArray *dataArray;
}
@property(retain,nonatomic) NSArray *dataArray;
@end
and then implementaion here
#import "TableViewController.h"
#import "FriendsNameViewController.h"
@implementation TableViewController
@synthesize dataArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"myfriendsList" ofType:@"txt"];
NSStringEncoding encoding;
NSError* error;
NSString* fh = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
dataArray = [NSArray alloc];
dataArray = [fh componentsSeparatedByString:@"\n"];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FriendsNameViewController *newView =[[FriendsNameViewController alloc] initWithNibName:@"FriendsNameViewController" bundle:nil];
[self.navigationController pushViewController:newView animated:YES];
//Crashes here
NSString *temp = [dataArray objectAtIndex:indexPath.row];
NSLog(@"%@",temp);
[[newView labelx] setText:[NSString stringWithFormat: @"%@" ,temp]];
}
@end
A: If you have verified that the array is correct prior to selecting, then the first thing I would try is to rearrange your code a little bit:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FriendsNameViewController *newView =[[FriendsNameViewController alloc] initWithNibName:@"FriendsNameViewController" bundle:nil];
NSString *temp = [dataArray objectAtIndex:indexPath.row];
NSLog(@"%@",temp);
[[newView labelx] setText:[NSString stringWithFormat: @"%@" ,temp]];
[self.navigationController pushViewController:newView animated:YES];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Framework 4.1 doesn't put data into database on SaveChanges() I have a problem when using the new Entity Framework 4.1. I started testing it a few days ago, and I am still new to the whole POCO concept and this new API.
Anyway, while doing some coding I created something like this:
public Tag GetTagWithName(string name)
{
if (db.Tags.SingleOrDefault(q => q.Name == name) == null)
{
return new Tag { Name = name };
}
else
{
return db.Tags.SingleOrDefault(q => q.Name == name);
}
}
Which is supposed to check in the database if the Tag this such a name already exists, and I am using this function in this piece of code:
if (tags != null)
{
foreach (HtmlNode tagNode in tags)
{
string tagString = tagNode.InnerText.Remove(0, 1);
Tag tag = TagRep.GetTagWithName(tagString);
pic.Tags.Add(tag);
}
}
if (context.Pictures.Any(q => q.Link == pic.Link))
{
continue;
}
else
{
context.Pictures.Add(pic);
}
context.SaveChanges();
Which is basically adding Tags to newly created photos, check if the photo is in database already and than if not add it to database, and invoke SaveChanges() after every picture.
Well my problem it, that during execution function GetTagWithName causes an error "Sequence contains more than one element" on getting "SingleOrDefault", which shouldn't happen, because I check the whole database before adding any new tag, using this function to check if the tag is already in DB.
From what I saw in my code, the situation happens because of the fact, that even if I add to the Picture a Tag object which I took from database, it still later on adds it as a new object to the Tags table.
Is there any explaination for that?
A: Several things things. One, you are doing it wrong:
which shouldn't happen, because I check the whole database before
adding any new tag, using this function to check if the tag is already
in DB.
Databases are capable of checking such constraints, so use the database, not the code.
Second thing -- your code is not only inefficent (you hit db twice) but buggy too. You check the name against the database, let's say it does not exist, so you add a tag, then you check the same name, it still does not exists, so you add it again!
You save it, and then you cannot get single record, because you just saved 2 records of the same name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Any way to get the frame of a UIObject from a different orientation? I have a piano UIView, made of Key subviews. The keys are assigned their frames relative to the frame of the piano. This works fine if I stay in portrait mode.
But if I start in landscape mode, the frame of the piano is landscape, but the keys set themselves up relative to the portrait mode frame of the piano. (There is a gray area, so I know the frame of the piano is different than the sum of the keys)
Is there any way to get the frame of the landscape mode piano while I'm in portrait mode? That way, I can check to see if I'm in landscape mode, and assign the appropriate frame.
The code below is in the piano class
- (void) setWhiteKeys {
CGRect baseFrame = CGRectMake(0, 0, self.frame.size.width / 7, self.frame.size.height)
for (Keys *key in whiteKeys) {
// sets the key's x origin to where the previous key ended
key.frame = baseFrame;
baseFrame.origin.x = key.frame.origin.x + key.frame.size.width;
}
A: You need to use the method layoutSubviews. It will be called automatically at the start, and after when the device orientation changes.
In that method, have your view check it's bounds and layout any subviews accordingly, e.g.
- (void)layoutSubviews {
CGRect bounds = self.bounds;
// Layout your subviews here according to the bounds
The key thing to think about in this is, how do you wish your views to behave in the two different orientations? Do you want them to be bigger, or in a different place, or remain the same?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A couple of questions regarding jQuery's $(document).ready and its use I have been writing some basic Javascripts, and I am finally giving in to try to learn jquery (less than 24hrs). I am having a problem with understanding syntax with simple lessons/codes that I am tweaking for my purpose.
Does everything has to be wrapped inside a separate $(document).ready(function())?
Or just have 1 $(document).ready(function()) statement and stuff everything inside of it? Including custom functions.
What happens when you put one inside another?
Sorry for simple question, but the examples online or in my book has the declaration wrapped around the executing code.
A: Generally, you just have one ready function that will kick off your entire page's event listeners, and initialize any objects that need setting up or what have you.
Here is a very simple page I put together a while ago that has some photo galleries and other 'complex' behaviors, but you can see that it's all stored in one big Page object that only gets inited during the document ready event:
http://threeaprons.com/ta.js
So what I've done is made a large "singleton" that is very page specific, and not reusable anywhere else (IE another site or what have you). This encapsulates the entire site's behavior, and only needs to be inited when the DOM is ready for event listeners, etc.
A: $(document).ready(function()) has one purpose.
That purpose is to delay execution of the code inside of it until the page is fully loaded and then run it as soon as the page reaches that state. Only initialization code that expects to examine/modify the initial state of the page (and thus has to wait for it to be loaded before examining it) needs to be inside that function.
Other pieces of code that run or get called at a later time do not have to be inside a document.ready block.
You may have one or multiple document.ready blocks - that's really up to how you want to organize your code. If all my code is in support of one app and is in very few set of files, I may just have one document.ready block and put any initialization code in that block. If I have independent modules that I want to be able to stand alone and easily be used in other projects, then I may use a separate document.ready block for each module just to make the organization of the code more independent.
There is no right or wrong way to do it - it just depends upon how you want/need to organize your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Single quotation and double issue In a PHP file i am assigning a XML file to an input variable
Example:
$xmlfile = '<?xml version="1.0" encoding="UTF-8"?>
<creators>
<creator>
<creatorName>Ganesh</creatorName>
</creator>
</creators>
<identifier identifierType="id">Dynamic input($input)</identifier>';
In the part of Dynamic input i want to declare a variable like $input which would based on the previous value.
How can i declare a variable ($input) in ''(single quotes) because declaring disturbs the structure.
A: You can concatenate it in:
$xmlfile = '<?xml version="1.0" encoding="UTF-8"?>
<creators>
<creator>
<creatorName>Toru, Nozawa</creatorName>
</creator>
</creators>
<identifier identifierType="id">Dynamic input(' . $input. ')</identifier>';
Fair warning, XML cannot hold all values, so you might need to escape the data depending on where it comes from -- for instance, you might not want any angle brackets, and you certainly need to cleanse any control characters.
A: You have to use double quotes or choose HEREDOC string.
$xmlfile = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<creators>
<creator>
<creatorName>Toru, Nozawa</creatorName>
</creator>
</creators>
<identifier identifierType=\"id\">Dynamic input($input)</identifier>";
HEREDOC string : (<<<ABC is opening identifier and the closing identifier must begin in the first column of the line - ABC.
$xmlfile = <<<ABC
<?xml version="1.0" encoding="UTF-8"?>
<creators>
<creator>
<creatorName>Toru, Nozawa</creatorName>
</creator>
</creators>
<identifier identifierType="id">Dynamic input($input)</identifier>
ABC;
A: Try:
$xmlfile = '<?xml version="1.0" encoding="UTF-8"?>
<creators>
<creator>
<creatorName>Toru, Nozawa</creatorName>
</creator>
</creators>
<identifier identifierType="id">Dynamic input('.$input.')</identifier>';
A: I prefer to use concationation instead of including variables in double quotes or HEREDOC (but HEREDOC goes next in my preferences list if text is long enough) because of three reasons:
1) no need to escape all double quotes (not applicable to HEREDOC, ofcourse);
2) PHP interpreter doesn't need to parse long text over and over again within every request to find any variable inside and replace it with its value.
3) there is less chance to make typo in variable name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Migrating PHP/MySQL based website to cloud server I have a web site developed in PHP/MySQL and hosted in normal webserver, so far there is no issue except in rare cases hosting server getting down for few hours.
Now client wants to host the same site in cloud server. (My site is something similar to churpchurp.com)
My Question is,
*
*What are the changes I need to do in the code when I move to cloud server.
*My MySQL database will be same or needs to change (including my existing data).
*Is it good idea to move to cloud at this point of time for this kind of website.
Please help me to decide.
A:
I am new to cloud technologies, Just like many I know the cloud is hsoted by Amazon and other providers and is more reliable and scalable
It's is not more reliable and scalable if you don't know how to use it. If all you do is host at amazon you get the exact same result as hosting anywhere else. Those scalable and reliable (i.e. distributed) technologies require you to know how to use them. Explaining how to do that is far beyond the scope of this site.
I do not recommend hosting on "cloud" server until you learn a LOT more about the technology they use to spread out your app on multiple machines.
A: You shouldn't have to do much except change the MySQL username and password in your config file(s).
But before moving over make sure everything you need is there and working, such as
*
*SEO friendly URLs if your site uses them
*PHP and MySQL versions are equal or greater than the ones you are currently using
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Twig macros VS includes? I can't really understand the difference between macros and includes in Twig: both seems to do the same stuff, that is take some variables and output something.
What's the difference and why you use macro or include?
A: Even though this question has an accepted answer, I think it is important to point out a few key differences between include and macro in twig.
*
*(The obvious): You can define multiple macros in a single file, resulting in multiple reusable blocks of code per file. An include is always included entirely, so one reusable block of code per file.
*There is a significant performance difference between the two options if you are planning to use it inside a loop. From my tests with 10k iterations, here are the times to render the template:
*
*raw HTML: 0.0015s
*macro: 0.040s (27x slower)
*include: 0.1584s (105x slower)
The macro import was called outside of this iteration.
*If you use include '...' with {...}, then you are passing entire context to the included template, and all the context variables (parameters) are optional. With macros, you may define required parameters, which is sometimes handy.
*You can define a macro within the same template that calls the macro. Not possible with include.
*To use a macro, you will need at least 2 statements in your template: one to import the macro, the other one to use it. Using include is just one statement, which is cleaner.
A: With includes, you would include an entire template, verbatim. That template would have access to any template variables currently in scope.
With macros, you are defining a kind of function within Twig (not to be confused with a Twig function, which can access other application logic, not just data passed into templates) that can render a particular component given appropriate objects. So you could have a macro for rendering, say, a shopping list which takes a shopping list as a parameter - and you could then reuse this macro without worrying whether you'd passed the data into the template in the same way elsewhere. Variables not explicitly passed into the macro would not be within scope within that macro.
A macro should really do one specific task to take some data and render a reusable component. An include can comprise any chunk of things - it's a lot more up to you. The extensible nature of the way Twig templates work, as opposed to something like Smarty, means that you are likely to use includes less, by design - but there can still be use cases where it will be the easiest way of avoiding duplication in your templates.
A: I am new to Symfony2, but I think the difference between twig macro and include is as following.
include: Used to define common parts in the page, such as header, sidebar or slot.
macro: Used to define functions related to the view, such as pagination.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Cannot reset NSArray and NSMutableArray in Objective-C I create an NSMutableArray as follows (note that winner is an instance variable):
winner = [NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil];
When I set winner to nil or remove its objects like
[self.winner removeAllObjects];
my program will automatically shut down. How should I solve this?
Updated !!!
In case I code like this
self.winner = [NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil];
it will call setter method which is
- (void)setWinner:(NSMutableArray *)newWinner
{
[winner release];
winner = [newWinner retain];
}
Do I still need to retain the array like
self.winner = [[NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil] retain];
A: Are you calling -removeAllObjects in a different method? If so, then the problem is likely that you've failed to retain the array, and it has been destroyed between the assignment and your later reference. +arrayWithObjects returns an instance that has had autorelease called on it.
Either use a synthesized property to set the instance variable, use a method that returns ownership of the object (like +alloc), or add a retain call:
winner = [[NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil] retain];
A: You didnt allocated the array
SO do like,
winner = [[NSMutableArray alloc] initWithArray:@"11", @"12", @"13", nil];
A: You assigned an autoreleased reference to an instance variable, so it gets dealloced after the event loop. Just retain it after creating it:
winner = [[NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil] retain];
A: Your program is not shutting down for what you're showing there, there's nothing wrong with it. Show us what error code you get and whether an exception is being thrown and post a bit more code around where the crash is happening.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CSS broken on Django admin on developer server I'm getting some really weird issues with the Django admin application. I'm running everything on the manage.py runserver development server, so I can't imagine what the issue would be, but I'm seeing something like this:
Obviously, this isn't ideal, so I'd like to return it to actually looking good. I'm using the staticfiles app, which I think might be a part of the problem, but I don't know for sure. What am I doing wrong here?
The admin site seems to link to the following CSS sheets, which aren't being found:
<link rel="stylesheet" type="text/css" href="/media/css/base.css" />
<link rel="stylesheet" type="text/css" href="/media/css/dashboard.css" />
A: I'm assuming you mean you're using the staticfiles contrib package in Django 1.3. If that's correct, you only need:
ADMIN_MEDIA_PREFIX = STATIC_URL+'admin/'
A: In settings.py uncomment(if commented) or add 'django.contrib.staticfiles', and restart the server.
This should fix it.
A: You've probably got your ADMIN_MEDIA_PREFIX set incorrectly.
Try setting it to:
ADMIN_MEDIA_PREFIX = "/admin-media/"
And see if that fixes everything.
Ok, three more things to check:
*
*Just a sanity check: are the admin stylesheets which are 404ing actually prefixed with /admin-media/?
*Is there any chance that your custom URL handlers are matching? (ex, do you have something like url(r'^admin-media/', …) in your root urls.py?
*It's unlikely, but is there any chance your Django install could be broken? do the .css files actually exist in …/site-packages/django/contrib/admin/static/admin?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I make the report always close at end of page in JasperReport? For what I know, JasperReport will always attach bands like Column Footer, Summary... right after the end of Detial band. So, when only few lines left in Detail band at last page, after all other band appended, report will remain lots of empty space.
How do I make the Detail band stretch, so the bands like Column Footer and Summary will always stay at the bottom of the page ?
I came up a way to move all data in Summary into Last Page Footer, and fake the border line in Background so it looks like Detail band stretch, it works great. But when there are no enough space for Last Page Footer and move to the next page. The fake border line fail to match, so I don't think this is a correct way to achieve this.
Any help would be appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you get an Idle Message in a UserControl class in C# / Silverlight? How do you get an Idle Message in a UserControl class in C# / Silverlight?
Back when I was programming in C++ and MFC there was an idle message for user intervace classes that one could overwrite and make use of. Is there something like that in C# and/or Silverlight?
A: In WPF (which uses mostly the same Dispatcher API as Silverlight), you can use the Dispatcher to dispatch a task with the Idle or ApplicationIdle priority:
How do we do idle time processing in WPF application?
...But in Silverlight, this functionality doesn't exist (intentionally so) (see http://forums.silverlight.net/t/149518.aspx).
If you want to ensure your task doesn't hang the UI, use BeginInvoke as opposed to Invoke.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How is Azure Data out computed? I'm on a free trial of Windows Azure at the moment.
All I've done is deploy a standard MVC start up template, "My MVC Application", to the service.
However when reading the data out charges (zerod costed out while I'm on a trial account) I see
01/10/2011 Windows Azure Platform - All Services Zone 2 Data
Transfer Out (GB) 11.414393 Southeast Asia Compute
That's 11GB!
The page is all of 3Kb and I'm the only one who knows it exists so how on earth does the useage get that high. I tried calling MS Support but they offered no explaination and if I were not on the intro package I would be billed for this amount.
Has anyone any ideas on where 11GB went for a 3Kb MVC template?
Note: I have no corresponding usage from my ISP bandwidth so it's "cant" have been me.
UPDATE:
The usage was never explained. Microsoft talked to itself but ultimately was unable to offer any explaination for the useage spike. I have not since experienced a similar problem. I dont believe Microsoft would intentionally rip us off as that would be a short term gain that would ultimately backfire but in terms of an error they apparently have no means to drill into the figures they bill you for in any meaningful way.
So i think the lesson is that you must implement your own metrics on this service to cross check the figures for which you will be billed.
A: Did you enable Content Delivery Network (CDN) ? The mechanism will transfer your data to other service zone. But still, 11GB is extremely large compared with your actual content size.
See more details at: http://www.microsoft.com/windowsazure/faq/
A: I don't suppose you've hit the page 4000 times?
Data transfer is computed by counting how many bytes leave our data center (from your app, storage account, service bus, caching, etc.). If you're not using anything other than compute (just hosting this app), it would mean that 11GB of data were served up by IIS in your web role.
A: Were you launching background threads that connected to web systems outside of Azure? I just saw something on my own Azure Website that made me think that some abandoned HttpClient requests launched with await were running all night long. (I must go on a bug hunt.) Even though my browser wasn't waiting for the requests, it looks like Azure counts data that was intended for delivery. This suggests the metering isn't done at the network level, but somewhere in IIS. Data needn't make it to the wire, just some output buffer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to convert returns to prices? I am curious how I revert from log-returns to prices. Here's an example:
> a1 <- c(88.23, 88.44, 88.55, 88.77, 88.99)
> a1
[1] 88.23 88.44 88.55 88.77 88.99
> a2 <- diff(log(a1))
> a2
[1] 0.002377315 0.001243008 0.002481391 0.002475249
a1 is prices, a2 is returns. How would I go from a2 back to a1? Any suggestions would be great.
A: You want to use something like
a3 <- exp(cumsum(a2))
Alternatively, you could use
a3 <- cumprod(exp(a2))
But these will be off because you need to add back the initial price to each value.
A: That should do:
> Reduce(function(x,y) {x * exp(y)}, a2, init=a1[1], accumulate=T)
[1] 88.23 88.44 88.55 88.77 88.99
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I add datepicker into jQuery modal dialog box in Rails? I add a datepicker into my modal dialog box. but when I click on the date picker, it always display behind the modal dialog box. How can I load it inside the jQuery modal dialog box? Following is my code to load date picker...
<%= calendar_date_select_tag "event[start_at]", "", :valid_date_check => "date.getDay() != 0 && date.getDay() != 6 && date.stripTime() > (new Date()).stripTime()" %>
I am using date picker plug-in in my application..
A: Sounds like the z-index of the modal box is higher than the datepicker
make the css z-index for the datepicker higher than the modal box.
example css:
.modal {
z-index: 9990;
}
.datepicker {
z-index: 9999;
}
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Refactoring techniques for Clojure I'm familiar with refactoring fairly large code bases in C# and Java but Clojure is something of a different beast, especially since it:
*
*Has a mix of macros and functions in typical code (i.e. you might want to refactor from a macro to a function or vice-versa?)
*Uses dynamic typing in most circumstances (so you don't get compile time checks on the correctness of your refactored code)
*Is functional rather than object-oriented in style
*Has less support for refactoring in current IDEs
*Is less tolerant of cyclic dependencies in code bases (making it harder to move blocks of code / definitions around!)
Given the above, what is the best way to approach code refactoring in Clojure?
A: In "Working effectively with legacy code" Michael Feathers suggests adding unit tests to create artificial "inflection points" in the code that you can re-factor around.
a super brief and wholly incomplete overview on his approach to adding order to unstructured code:
*
*devide the code into "Legacy" (without tests) and the rest.
*create a test
*recur on both halves.
The recursive approach seemed to fit well with the mental processes I use in thinking about Clojure so I have come to associate them. even new languages can have legacy code right?
This is what I got from my reading of that one book while thinking about clojure. So I hope it is useful as a general guideline. perhaps your codebase already has good tests, in which case you're already beyond this phase.
A: I'm not an expert. But anyway:
*
*Stay away from God functions. If you have a big function, break it down to smaller functions and each of these functions is doing one thing, and it is doing it well.
*If you find usage of Java arrays (and it is not necessary to use them), convert them to Clojure sequences.
*Embrace defrecord and defprotocol.
*Stay away from macros unless you really can't proceed without writing a macro.
*When it is possible, favor lazy sequences over recursion.
*When creating a service, put the contract in its own namespace and the implementation in its own namespace.
*Achieve dependency injection as passing functions as parameters to another functions.
*Use desctructuring for a function's arglist when it is possible. It will lead to an easier to understand a function's implementation.
*Consider using Prismatic Schema project.
Also, have a look at CursiveClojure. I think it is really promising.
I'm not the creator of CursiveClojure.
A: I'm not familiar with refactoring fairly large code bases in C# or Java, but here goes.
Clojure:
*
*Has a mix of macros and functions: I could be wrong, but I think you'll find that refactoring seldom moves the interface between macros and functions.
*Uses dynamic typing (so you don't get compile time checks on refactored code): ... nor on any other code: you need more tests in either case.
*Is functional rather than object-oriented in style Refactorings are stated in OO terms, but often survive simple transcription: method to function, class to function or closure or map.
*Has less support for refactoring in current IDEs True: more busywork.
*Is less tolerant of cyclic dependencies in code bases Two cases: mutual recursion in a namespace/file should be easier to cope with than it is; but cyclic dependencies between namespaces/packages cause confusion and ambiguity. I think Java only allowed them because C++ did, and C# followed suit.
I have found it useful to look through Martin Fowler's catalogue of refactorings. Most survive translation from OO to functional lingo. Some (such as Change Value to Reference) disappear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: JQuery function, wrapping and live binding I've written a nice function to wrap an input with increment/decrement buttons:
$.fn.qDecInc = function(){
return this.wrap('<span id="qButtons" />').after($('<span/>', { class: 'qIncButton' }).bind('click', function() {
var ov = 0;
if (isNaN($(this).val())){
ov = 0;
} else {
ov = $(this).val();
}
if (ov < 99){
var nv = parseFloat(ov) + 1;
$(this).val(nv);
$(this).keyup();
$(this).change();
}
}), $('<span/>', { class: 'qDecButton', style: 'top: 11px;' }).bind('click', function() {
var ov = 0;
if (isNaN($(this).val())){
ov = 0;
} else {
ov = $(this).val();
}
if (ov > 0){
var nv = parseFloat(ov) - 1;
$(this).val(nv);
$(this).keyup();
$(this).change();
}
}));
}
Values get updated, but the inputs not.
I've tried
$(this).live("change");
and even
$("body").delegate($(this), "change");
to no avail.
What did I miss?
http://jsfiddle.net/MVxsA/1/ - here's a jsfiddle for your convenience.
A: Two issues
*
*in this context, you should use .bind('click', function() {...}) instead of live(). Or you can use the convenient shortcut method .click(function() {...}). The function live() is used when elements will be added to the dom later, and you want jQuery to automatically attach listeners to the new elements at that time. For this reason, live() also requires a selector (which your example omits).
*When inside an event handler, this refers to the element on which the listener was fired. So in this case, this is the qIncButton or qDecButton, not the element to which the plugin is applied.
Here's how these issues can be corrected:
$.fn.qDecInc = function(){
var self = this;
return self.wrap('<span id="qButtons" />').after($('<span/>', { class: 'qIncButton' }).click(function() {
console.log("up");
var ov = 0;
if (isNaN($(self).val())){
ov = 0;
} else {
ov = $(self).val();
}
if (ov < 99){
var nv = parseFloat(ov) + 1;
$(self).val(nv);
$(self).keyup();
$('body').change();
}
}), $('<span/>', { class: 'qDecButton', style: 'top: 11px;' }).click(function() {
console.log("down");
var ov = 0;
if (isNaN($(self).val())){
ov = 0;
} else {
ov = $(self).val();
}
if (ov > 0){
var nv = parseFloat(ov) - 1;
$(self).val(nv);
$(self).keyup();
$(self).change();
}
}));
}
Your updated jsFiddle is here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jquery URL driven content management So I am very new to jquery and need some help on a little project. Perhaps there is a script already in existence that I could use, if not I am hoping to find some direction.
I have found a few URL parsing scripts that allow me to dig through the query string and capture the value. Now what I want to do is take that variable and have it define what content is rendered on the page.
Here is an example, www.site.com renders normal site. But www.site.com/m/default.aspx?img=img1 would hide a parent div that contains all the sites content and .show a hidden div containing a supplemental image. But, www.site.com/m/default.aspx?img=img2 would show an alternative div with yet another image.
Seen something like this done before? Any resources that might help me out?
Thanks a million to all and any that help.
-Travis
A: I have written some code, I hope this solves your problem: http://jsfiddle.net/fNjCk/
And yes,i do like nyan nyan cat :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you default to show or hide using JQuery based on the value of a checkbox? I have the following JQuery:
$('#promotion_profile_offer').live('click', function(e) {
$('.nooffer').toggle();
});
which toggles the form, if it detects a click it will hide the form. This works great in the case that the user unchecks the box, but it doesn't make sense when the checkbox defaults to unchecked and moves to checked.In that case my code would Hidee an offer form, when the user clicks the Offer checkbox.
Therefore How do I do the following:
*
*Read the value of the checkbox #promotion_profile_offer
*Default the .nooffer class to hide() if the #promotion_profile_offer
box is false
Thank you.
A: $('#promotion_profile_offer').live('click', function(e) {
var checked = $(this).is(':checked');
$('.nooffer')[checked ? 'show' : 'hide']();
});
Or a easier to read version:
$('#promotion_profile_offer').live('click', function(e) {
var checked = $(this).is(':checked');
if (checked === false) $('.nooffer').hide()
else $('.nooffer').show()
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Spoofing" a 404 not found error with .htaccess I have .htaccess currently set up to rewrite anything without a period or slash to the equivalent with a .php extension (so "foo" internally pulls up "foo.php") via the following:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !(.*)\.php
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/.]+)$ $1.php [L,NS]
However, I'd like direct requests for "foo.php" come back with a 404 as though the file didn't exist (just as if someone tried "foo.asp" or "foo.blargh"). I know there's the [F] and [G] flags, but I don't want "forbidden" (403) or "gone" (410), as those are different results from what a nonexistent file returns (404).
Is there a way to do this?
UPDATE 1
I've tried
RewriteCond %{REQUEST_FILENAME} \.php$
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.php\ HTTP/
RewriteRule ^(.*)$ /error.php?e=404 [R=404,L,NS]
Which works... until I try to use an ErrorDocument handler. Assuming "error.php" at my document root, anything along the lines of ErrorDocument 404 /error?e=404 (i've also tried with error.php, etc) regurgitates the error
Not Found
The requested URL /foo.php was not found on this server.
Additionally, a 500 Internal Server Error error was encountered while
trying to use an ErrorDocument to handle the request.
... but only when attempting to access a .php page that actually exists (such as foo.php); any attempt to access a page that actually doesn't exist (and thus doesn't trigger my second rewrite rule) goes to the page specified by the ErrorDocument handler.
A: Found a solution:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ (/.*)\.php
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_URI} !^/error\.php
RewriteRule . - [R=404,L,NS]
ErrorDocument 404 /error.php?e=404
Specifically, the third RewriteCond keeps requests for the error page from triggering the RewriteRule (since the THE_REQUEST still contains the original request (matching the first RewriteCond), and the error page does indeed exist (matching the second RewriteCond).
Note that the third RewriteCond matches the URI format specified for the ErrorDocument. Within error.php, I use $_SERVER["REDIRECT_SCRIPT_URL"] to find out what file the user originally requested (thus making it look like the 404 was served as a direct response to their request).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to Update the Date without changing its Time Using SQL Server? I have One Column in the Mytable called StockDate and its DataType is DateTime.
So My Table contains record as follows
SID StockDate
----- ------------
1 2011-10-02 09:44:41.170
2 2011-10-02 09:48:23.234
Here I want to update Only the Date of the StockDate as "2011-09-30". But the time should be same as it is. How to do this? Please I need all your suggestions.
A: Work out the different in whole days and subtract that...
UPDATE
MyTable
SET
StockDate = DATEADD(day, DATEDIFF(day, StockDate, '20110930'), StockDate)
WHERE
...
Note the use of the yyyymmdd for SQL Server.
A: http://msdn.microsoft.com/en-us/library/ms186724(v=SQL.90).aspx
You could probably use DATEDIFF and DATEADD to get yourself to 9/30/2011 without changing the time.
A: You can use dateadd, datediff functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How to tell BufferedReader to stop reading from System.in? I am using bufferedReader to read System.in from the user, The user will enter a domain address and source address separated by a space.
eg
auckland.ac.nz. 198.19.20.44
www.esc.auckland.ac. 173.27.28.93
stat.auckland.ac.nz. 52.159.152.105
student.auckland.ac.nz. 64.247.240.232
Now the problem is that once the user finishes entering the data, the input stream does not terminate and hence the program does not get executed. I have written some code for the BufferedReader if anyone is willing to check it and tell me where I went wrong I would greatly appreciate it. Notice the two variables "count" and "n", is there anyway I can use those to help with that?
try {
String fqdn, src, key, temp;
Integer count;
int n = 0;
while ((temp = br.readLine()) != null){
int divide = temp.indexOf(" ");
fqdn = temp.substring(0, divide); // divide the input
src = temp.substring(divide+1);
key = fqdn + " " + src;
//System.out.printf("%d: %s\n", n, key);
dht.lookup(key);
n += 1;
}
br.close();
} catch (NoSuchElementException e) {
//System.out.printf("end-of-file\n");
}
A: The loop will terminate when readLine() returns null. The only way that this will happen is if standard input it closed. The user can do this by typing Ctrl+D, but that's perhaps too much to ask from a typical user. One easy alternative is to ask them to type "done" when they're done; then your loop should check for that value, rather than null.
A: What I would look at is Observer Pattern http://en.wikipedia.org/wiki/Observer_pattern and multitreading releated things such as wait() - use this link: How can I set a timeout against a BufferedReader based upon a URLConnection in Java?
and take a look here: http://www.javaspecialists.eu/archive/Issue153.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to implement an Drop Down List for iphone I searched about UIPickerView and NSComboBox , I really don't understand the difference between these two !!! can anyone tell me what is the best way to show an Drop down list in xcode .
I saw the picker view but I think it is too much coding for a dropdown list !!!!
thank you
A: For Drop Down List you can implement picker View.It takes very less coding effort.
If you want to implement it like a drop down then you might take think to create a view which will have a label and a button (like in drop down) and on that button click show a table view.
This will take a good coding effort.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to have ListView inside a dialog? Basically, I have this LazyList which originally created by [Fedor][1] , I am just wondering if there is anyway to put it inside a dialog. Please help me, I've been struggling for days trying to figure this out, I really need your help. Thanks in advance!
Here his code when you need it:
p
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
if(position == 0){
final Dialog dialog = new Dialog(MainPictures.this, R.style.CustomDialogTheme);
dialog.setContentView(R.layout.customlayout);
dialog.setTitle(null);
dialog.setCancelable(true);
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.dimAmount=0.5f;
dialog.getWindow().setAttributes(lp);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
}
else {
System.out.println("Error");
}
}
});
}
private String[] mStrings={
"http://www.urlurl/hi.png",
"http://www.urlurl/hi.png",
};
}
A: have a lokk at this.
http://developer.android.com/guide/topics/ui/dialogs.html
Update:
Another solution could be Create an ACtivity and Put listView in it and make its Theme as Dialog.
read this to know how to set theme http://developer.android.com/guide/topics/ui/themes.html
A: You have to create a dialog with a custom layout. So for example, use this layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="400dip"
android:padding="10dp">
<ListView android:id="@+id/MyAwesomeList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
And use it for a dialog like this when you're creating the dialog in the onCreateDialog() callback of your Activity:
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
ListView myList = (ListView) dialog.findViewById(R.id.MyAwesomeList);
// set the list adapter and stuff
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Relational Algebra Query I'm stuck at the query below where i'll need to list out two attributes from different tables. Is there a simpler way to write the above query?
Tables:
Patient (PatientID, FamilyName, GivenName,Address)
Item (ItemNo, Info, Fee)
Account (AccountNo, PatientID, Date)
AccountLine (AccountNo, ItemNo)
List the Item Info and the date of all treatments for any patient named John Wayne:
Select FamilyName =” Wayne” and GivenName=”John” (Patient)> Temp1
Temp1*Temp1.PatientID = Account.PatientID (Account) > Temp2
- Updated
Temp2*Temp2.AccountNo = AccountLine.AccountNo (Temp2 X Account) >Temp3
Temp3*Temp3.ItemNo = Item.ItemNo (Temp3x Item) > Temp4
Select Description, Date(Temp4)
Join Answer
Select Description, Date (Restrict FamilyName =” Wayne” and GivenName=”John” (Patient) Join Account Join Item Join AccountLine)
A: Looks very much like [homework] so I'll just provide hints...
Rather than selecting from a table, you can select from a join
specifically, the natural join of Patient and Account table would, for one, allow finding all AccountNo and Date values that are associated with John Wayne.
Similarly another join would locate the Item Info given the AccountNo.
And since a join can be joined with another one (assuming there are no conflicts), seems like I almost solved it...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Native way to add SimilarResults to model via SOLRNET I am using SOLRNET and am using SOLR's MoreLikeThis functionality to get similar documents to those that are being returned. My code looks a little something like this (in this case I am doing a lookup on ID as I already know the specific document I would like to load):
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<MyDocument>>();
var queryOptions = new QueryOptions()
{
MoreLikeThis = new MoreLikeThisParameters(new[] { "text" })
{
MinDocFreq = 1, // minimum document frequency
MinTermFreq = 1, // minimum term frequency
},
};
var document = solr.Query(new SolrQuery(string.Concat("id:", id)),queryOptions);
When I execute my query everything works exactly as it should and my document is retrieved as type MyDocument. I can iterate through SOLRNET's SimilarResults dictionary and see that similar documents are indeed returned. What I am wondering is if there is a native way to map a field in my MyDocument class so that it is populated with an collection of type MyDocument, representing the similar documents that are returned.
If I have to loop through the SimilarDocuments one by one that is fine, but I'm guessing there is a straightforward way to do this. I've tried the obvious tricks, like mapping using an attribute in my MyDocument class
[SolrField("moreLikeThis")]
public IDictionary<string,IList<MyDocument>> SimilarResults { get; set; }
Any help would be greatly appreciated,
Thanks in advance
JP
A: Similar results are not part of a document, and the can actually change whenever you update the index.
Anyway, solr.Query returns a ISolrQueryResults object, not just a document, so you will have a list of similar documents in document.SimilarResults that you can assign to any property you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What will be the default speed to play the mp3 file through NAudio What will be the default Speed set to play the MP3 files through NAudio waveout.
Is there any way to set the speed according to the User setting in NAudio waveout.
Thank's in Advance.
A: The default will be normal playback speed. There is a Windows API call called waveOutSetPlaybackRate, but this is not necessarily supported on all soundcards. You would be better off finding alternative ways to speed up the audio.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make the image bounce horizontally? I have an image("ball.gif") that moves horizontally, the problem is how could I make the ball bounce when it reach the end of the size of the panel? I know this is not really difficult but I'm just a little bit confuse on how to do it.
Could someone help me about this matter?
This what I've tried so far :
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(ball, x, y, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void cycle()
{
x += 1;
y += 0;
if (x >240)
{
x = 10;
y = 10;
}
}
public void run()
{
long beforeTime, elapsedTimeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true)
{
cycle();
repaint();
elapsedTimeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - elapsedTimeDiff;
System.out.println(sleep);
if (sleep < 0)
{
sleep = 2;
}
try
{
Thread.sleep(sleep);
}
catch (InterruptedException e)
{
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
A: First, you need to hold your velocity in a field instead of hardcoding it:
private static final int RIGHT_WALL = 240;
private int x, y;
private int xVelocity = 1;
//...
x += xVelocity;
y += 0; //change this later!
Then when you do your bounds checking, flip your xVelocity:
//...
if ( x > RIGHT_WALL ) {
x = RIGHT_WALL;
xVelocity *= -1;
}
A: private int dx = 1;
public void cycle() {
x += dx;
y += 0;
if (x+star.getWidth() >= getWidth()) {
dx = -1;
}
if (x <= 0) {
dx = 1;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I read data from an HID USB device in a Cocoa Application? I am trying to implement an HID USB application in Mac OS X. The application needs to read data from the HID USB device. I found some information about reading from an HID USB device, which mentioned the creation of a HID manager kext. My question is, how can I create the HID manager kext and how do I implement this kext in my Cocoa application?
This is my device's information from USB Prober:
Low Speed device @ 2 (0x5D200000): ............................................. Composite device: "SportBrain USB\000\000\000\000\000\000\000\000\000\000\000\000"
Device Descriptor
Descriptor Version Number: 0x0110
Device Class: 0 (Composite)
Device Subclass: 0
Device Protocol: 0
Device MaxPacketSize: 8
Device VendorID/ProductID: 0x1125/0x2000 (unknown vendor)
Device Version Number: 0x0106
Number of Configurations: 1
Manufacturer String: 1 "SportBrain In"
Product String: 2 "SportBrain USB\000\000\000\000\000\000\000\000\000\000\000\000"
Serial Number String: 0 (none)
Configuration Descriptor: ....................................... "SportBrain USB\000\000\000\000\000\000\000\000\000\000\000\000"
Length (and contents): 34
Raw Descriptor (hex) 0000: 09 02 22 00 01 01 02 80 0D 09 04 00 00 01 03 00
Raw Descriptor (hex) 0010: 00 02 09 21 00 01 00 01 22 1C 00 07 05 81 03 08
Raw Descriptor (hex) 0020: 00 0A
Number of Interfaces: 1
Configuration Value: 1
Attributes: 0x80 (bus-powered)
MaxPower: 26 ma
Interface #0 - HID
Alternate Setting 0
Number of Endpoints 1
Interface Class: 3 (HID)
Interface Subclass; 0
Interface Protocol: 0
HID Descriptor
Descriptor Version Number: 0x0100
Country Code: 0
Descriptor Count: 1
Descriptor 1
Type: 0x22 (Report Descriptor)
Length (and contents): 28
Raw Descriptor (hex) 0000: 06 A0 FF 09 01 A1 01 09 01 15 00 25 FF 75 08 95
Raw Descriptor (hex) 0010: 08 81 02 09 03 75 08 95 08 B1 02 C0
Parsed Report Descriptor:
Usage Page (65440)
Usage 1 (0x1)
Collection (Application)
Usage 1 (0x1)
Logical Minimum......... (0)
Logical Maximum......... (-1)
Report Size............. (8)
Report Count............ (8)
Input................... (Data, Variable, Absolute, No Wrap, Linear, Preferred State, No Null Position, Bitfield)
Usage 3 (0x3)
Report Size............. (8)
Report Count............ (8)
Feature................. (Data, Variable, Absolute, No Wrap, Linear, Preferred State, No Null Position, Nonvolatile, Bitfield)
End Collection
Endpoint 0x81 - Interrupt Input
Address: 0x81 (IN)
Attributes: 0x03 (Interrupt no synchronization data endpoint)
Max Packet Size: 8
Polling Interval: 10 ms
If anybody know this please help me.
A: You do not need to implement a kext. You would simply use IOKit, specially the IOHid interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: securing a REST API accessible from Android We're building a game for Android, which needs access to web services - so we wrote a RESTful API in PHP that runs on our own server. What the API offers is: creating user, logging in, downloading games, retrieving game list, submitting score... etc. Now I'm thinking, if some experienced user gets the URL format of the API - s/he will be able to trash the system in many ways:
*
*Create a script & run it to create automatic users - I think I can prevent it by CAPTCHA or someting like that. But again, captcha will annoy game players.
*Malicious user logs in using his browser, downloads game & then submits score as he wish - all via calling the API by simply typing it from his browser. I assume malicious user somehow knows API urls to call - by sniffing when the application was making HTTP requests.
*I need to ensure that requests are made only from Android device that installed the game. (The game will be free)
Now How do I prevent such abuses?
A: Solutions that others have presented here are called security through obscurity. Basically they are trying to obscure the protocol and hide the implementation. This might work until someone capable enough disassembles the app and reverse-engineers the protocol. Hackers are very capable at that.
The question is if your app is worth cracking? Schemes like iTunes, DVD or Sony PS3 network were obviously worth the effort. The obscurity approach might work if no one capable of cracking cares. Just don't fool yourself that it is not doeable.
Since you can not trust the device or your app, you must trust the user. In order to trust the user, you need user identification and authorization system. Basically a login to your app. Instead rolling you own indentification system (login with confirmation emails, etc..), use a 3rd party system: OpenID (google accounts) or OAuth (facebook, twitter). In case of facebook use the server-side auth scheme.
What I'd do:
*
*Allow users to freely play the game until they want to "save" the results on server.
*Before saving their results have them login via above mentioned method.
*Use HTTPS to send the data to your server. Buy a ssl certificate from trusted CA, so you don't have to deal with self-signed certs.
A: I think you will never be able to hide the urls being called by the application
(if I am running a root-ed android phone, I should be able to spy on all network traffic)
But your real problem is that you need to authenticate your api in some way.
One way would be to implement OAUTH, but maybe this'd be overkill.
If you want a simple mechanism, how about this;
*
*create a secret key
*build the api request (eg. https://my.example.com/users/23?fields=name,email)
*hash this request path + plus your secret key (eg. md5(url+secret_key) == "a3c2fe167")
*add this hash to your request (now it is https://.....?fields=name,email&hash=a3c2fe167)
*on the api end, do the same conversion (remove the hash param)
*check the md5 of the url and the secret key
As long as the secret remains secret, no one can forge your requests.
Example (in pseudo-code):
Android side:
SECRET_KEY = "abc123"
def call_api_with_secret(url, params)
# create the hash to sign the request
hash = MD5.hash(SECRET_KEY, url, params)
# call the api with the added hash
call_api(url+"&hash=#{hash}", params)
end
Server side:
SECRET_KEY = "abc123"
def receive_from_api(url, params)
# retrieve the hash
url_without_hash, received_hash = retrieve_and_remove_hash(url)
# check the hash
expected_hash = MD5.hash(SECRET_KEY, url_without_hash, params)
if (expected_hash != received_hash)
raise our exception!
end
# now do the usual stuff
end
A: You mentioned users faking the high scores. This could still happen if your users are authenticated. When the game is uploading the high scores you may want to have it also upload a proof of the score. For example Score 20100 from 103 bugs squished, 1200 miles flown, level 3 reached, and 2 cherries were eaten. This is by no means perfect but would cover the low hanging fruit.
The first you should do is have authenticated users. Userid/password/session token etc., see if you can find some already existing frameworks. Once you have user authentication make sure you can do it securely with TLS or similar.
As far as I know there is no way your server can be certain that the request is coming from your application (it's all just bits in packets) but you can at least make it hard for someone to be malicious.
*
*Build a secret into your application (as suggested by other responses, key, hash salt etc.)
*Generate a unique ID on the first execution of the application after installation and track that along with the logged in user. Details on this and the device's unique ID (why not to use it) can be found on the android blog
*Some ideas discussed in this post How to ensure/determine that a post is coming from an specific application running on an iPhone/iTouch?
*Check User Agent
A: If you really want to secure the connection then you'll have to use public key cryptography, e.g. RSA. The device will encrypt the log in information using the public key and in the server end you will have to decrypt using the private key. After login the server will send a token/encryption key (the response will be an encrypted JSON or something) and the device will store that. From then as long as the session is not expired the device will send all the information encrypted using that token. For this requests you should not use RSA cause that will take more time. You can use AES256 (which is a popular private key encryption) with that encryption key received from server to encrypt your requests.
For sake of simplicity you can drop RSA altogether (If you are not sending payment information) and do everything using AES256 with a private key. The steps should be -
*
*Encrypt every outgoing request with a private key.
*Convert the encrypted string to a base 64 string.
*URL encode the base 64 encoded string.
*Send it over.
On the server end
*
*Do base 64 decode
*Decrypt using the private key.
Your request should carry a signature (e.g. the encryption key appended as a salt) so that it becomes possible to identify it after decrypting. If the signature is not present simply discard the request.
For sending responses do the same.
Android SDK should have methods for Encrypting with AES256 and Base 64 encoding.
A: Follow these guidelines from the Android team to secure your backend, by using Oauth tokens provided through Google's APIs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: nested content_tags only showing the last of the chilldren rails view helper I am trying to do a little reusable helper to insert into a page of some descriptions with the content tag
def spec_description(name, overview, detail)
content_tag :dl do
content_tag :dt do
content_tag(:strong, name)
end
content_tag :dd, overview, :class => "spec-overview"
content_tag :dd, detail, :class => "spec-detail" #only this dd tag gets output
end
end
But as it is, only the dd tag with what is to be 'detail' gets output to the html
UPDATED
output html is like this now:
<dl>
<dd>some detail from detail variable</dd>
</dl>
See how the "overview" and "name" dd tags are completely missing? Let alone their content...
Does anyone have an idea why this is and how I may fix it?
A: Your helper is returning some HTML and its return value is whatever content_tag :dl returns. The content of the <dl> will be whatever its block returns and the block returns the last value (i.e. the last <dd>). So you just have a return value problem:
def spec_description(name, overview, detail)
content_tag :dl do
html = content_tag :dt { content_tag(:strong, name) }
html += content_tag :dd, overview, :class => "spec-overview"
html += content_tag :dd, detail, :class => "spec-detail"
html
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Retaining parent slugs in CakePHP I'm experimenting with SEO friendly URL's in CakePHP as efficiently as I can, I've managed to use the current format, each example uses function view($slug) except for the first example which uses function index().
/categories/
/categories/books/
/categories/books/it-and-computing/
But what if IT & Computing has a sub-category "Web Development"? I'd like the URL to become:
/categories/books/it-and-computing/web-development/
I'm not sure how to do this without creating too many routes. Here is my route code so far:
Router::connect('/categories/', array('controller' => 'categories', 'action' => 'index'));
Router::connect('/categories/:slug',
array('controller' => 'categories', 'action' => 'view'),
array('pass' => array('slug'))
);
Router::connect('/categories/:parent/:slug',
array('controller' => 'categories', 'action' => 'view'),
array('pass' => array('parent', 'slug'))
);
Any help would be greatly appreciated
Kind Regards
Stephen
A: // in routes.php
Router::connect('/categories/:row:lastslash',array('controller' => 'settings', 'action' => 'show',),array(
'pass'=>array('row'),
'row'=>'.*?',
'lastslash'=>'\/?'
));
//in controller
function show($row = ""){
if($row){
$categories = split('/',$row);
?><pre><? print_r($categories);?></pre><?die();
}else{
die('do something else');
}
}
/categories/books/computing/web-development/cakephp/
result:
Array
(
[0] => books
[1] => computing
[2] => web-development
[3] => cakephp
)
/categories/
result:
do something else
/categories/books
result:
Array
(
[0] => books
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using <% asp tags in javascript not working? I can't get the following to work:
var percent = <% Model.Percent; %>
I am sending a Model to the view from the controller...I'm getting the error:
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Am I being extremely stupid?
A: Replace:
var percent = <% Model.Percent; %>
With:
var percent = <%= Model.Percent %>
The <% nugget simply means, "run this code as a C# statement". It doesn't actually render any value. <%= on the other hand evaluates the C# expression, and converts it to a string and renders it. This way, it'll print out the percent in your javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: asp.net - Multiple select box selection + Quantity Design advice I have a listbox that allows a user to have multiple selection and a button to transfer these selected items to another listbox, now theres a new requirement which I also need to indicate the quantity for each respective items. I can't think of a good way to handle this.
I currently have a Source items select box and a Selected items select box. Any advice on how to go about designing this feature? Thanks!
Multiple select box selected Quantity
e.g. Eggs ---> Eggs ---> X 4
Vegetables Potato X 5
Potato
A: This was about the best idea I could come up with for your scenario:
HTML would look like this:
<table>
<tr>
<td>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
</td>
<td>
<input type="button" value="-->" onclick="moveOptions(<%=ListBox1.ClientID %>, <%=ListBox2.ClientID %>);" /><br />
<input type="button" value="<--" onclick="moveOptions(<%=ListBox2.ClientID %>, <%=ListBox1.ClientID %>);" />
</td>
<td>
<asp:ListBox ID="ListBox2" runat="server"></asp:ListBox>
<br />
</td>
</tr>
</table>
Then the code behind (to add a couple of imaginary items):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Me.ListBox1.Items.Add(New ListItem("Eggs", 1))
Me.ListBox1.Items.Add(New ListItem("Vegetable", 2))
Me.ListBox1.Items.Add(New ListItem("Potatoes", 3))
End If
End Sub
Then the javascript:
<script language="JavaScript" type="text/javascript">
<!--
var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);
function addOption(theSel, theText, theValue) {
var newOpt = new Option(theText, theValue);
var selLength = theSel.length;
theSel.options[selLength] = newOpt;
}
function deleteOption(theSel, theIndex) {
var selLength = theSel.length;
if (selLength > 0) {
theSel.options[theIndex] = null;
}
}
function moveOptions(theSelFrom, theSelTo) {
var selLength = theSelFrom.length;
var selectedText = new Array();
var selectedValues = new Array();
var selectedCount = 0;
var i;
for (i = selLength - 1; i >= 0; i--) {
if (theSelFrom.options[i].selected) {
if (theSelTo.id.indexOf("ListBox2") > -1) {
var quantity = prompt("Please indicate the quantity of " + theSelFrom.options[i].text + " that you would like to add", 1);
if (quantity > 0) {
selectedText[selectedCount] = theSelFrom.options[i].text + "(" + quantity + ")";
}
else if (quantity == null || quantity == nan) {
return;
}
}
else {
selectedText[selectedCount] = theSelFrom.options[i].text.substring(0, theSelFrom.options[i].text.indexOf("("));
}
selectedValues[selectedCount] = theSelFrom.options[i].value;
deleteOption(theSelFrom, i);
selectedCount++;
}
}
for (i = selectedCount - 1; i >= 0; i--) {
addOption(theSelTo, selectedText[i], selectedValues[i]);
}
if (NS4) history.go(0);
}
//-->
</script>
So basically what this does is that for each selected item in the first ListBox asks the amount with a fancy Prompt dialog, and then adds the item into the other ListBox. The effect will be the same if more than one item is selected. If the item is being moved from ListBox2 to ListBox1 it won't ask, and it will just move the item without the amount. You might want to add extra security in the server side, also you might want to check for numerical values and stuff.
Hopefully this helps man, as I said it was the best idea I could come up with real quick, but probably not the best solution.
Good luck!
Hanlet
Couple of Screenshots
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesn't progressbar update when exceeds maximum or minimum value? <ProgressBar Value="{Binding Player1PointsLife}" Minimum="0" Maximum="8000"/>
Why when value exceeds maximum or minimun, it doens't update the UI anymore? How can I fix it?
Thanks in advance.
UPDATE:
Maybe I was not very clear. I mean, I set in progress bar value = 2000 (all right, updates de UI), then I set -1000 (it's correct, it mustn't show anything in the progress bar), and finally I set 6000 (here must updates the UI, but it isn't updating anymore).
A: What should it do? It can't show the progress bar any more empty than fully empty or any more full than completely full. You can fix it by telling the progress bar what you want it to do. If you want it to appear, say, 85% full, set the value to 85% of the way from the minimum to the maximum.
The usual way to do this for a stat in a game is to raise the maximum to the player's current maximum for that stat. If you allow the stat to go over the normal maximum for some reason (say a special power up), you have to decide how you want to display that. Maybe you can change the bar color and raise the maximum to the temporary maximum. Maybe you can add an additional bar to show the "overflow" power. Whatever works for your concept.
A: Write a WPF converter so that if the value is >8000 or <0 it sets the value according to your requirement. Set the converter as follows in XAML:
<ProgressBar Value="{Binding Player1PointsLife, Converter={StaticResource **YourConverter**}}" Minimum="0" Maximum="8000"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sources, APIs and techniques for academic data-mining So I'm gonna do a historical trends analysis for one of my education literature review class. I'm considering use the abstracts and keywords from the peer-reviewed journals since 1970s, I know Springer has an API which might be useful, what other sources/APIs are there? I never did any data-mining and analysis before, I know a bit about ruby and less about python. Any other advices are also welcomed.
A: I think you can get abstracts of medical publications (not the fulltext though) using the PubMed API. That'll give you something on the order of a million documents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Debugging App Engine with --backends I can debug my application in Eclipse without running any backends just fine. Now I want to debug my application with the backends enabled.
I start the dev_appserver via Eclipse with the --backends. But the execution doesn't stop at the breakpoints I set. I tried setting the application ports to the same as without backends by passing --multiprocess_min_port=8080, but that didn't help either.
What am I missing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP / Google Maps API - Easiest method to verify a street address and standardize / prevent duplicates? What is the easiest way to do this? I've read Google Map API can't legally be used as an address verification service. What are some practical alternatives and/or respected premium/pay-per-request services?
Address Validation API from '09 - Address validation using Google Maps API
A: I'm glad you asked this question.
UPS and USPS both offer free APIs for address verification.
However, USPS requires that you can only use their APIs if you intend on using their shipping service. UPS doesn't appear to have this restriction. The TOS looks fairly boilerplate and you aren't required to use them for shipping (although I'm not a lawyer so idk).
USPS Developer Kit - https://www.usps.com/business/webtools.htm?
UPS eCommerce APIs - https://www.ups.com/upsdeveloperkit?loc=en_US
List of 7 Address Verification Services - http://www.programmableweb.com/news/7-package-tracking-apis-rock/review/2014/08/26
A: It sounds like you are looking for a "live" address verification solution as opposed to a batch processing or "scrubbing" solution.
As for the "live" address verification services, you are correct that USPS (US Postal Service) requires you to use their delivery services if you use their API. UPS (United Parcel Service) is the same way. Here is a quote from their TOS (Terms Of Service)
"The UPS Systems and Information are to be used solely by Access User in connection with shipments tendered by, to or for Access User to UPS for delivery and for no other purpose."
There are quite a few different service providers available that license the USPS data and then allow you to use it WITHOUT the stated requirements. The USPS API is very complex and unless you are going to be using it A LOT, it might not be worth the investment to get it figured out.
In the interest of full disclosure, I'm the founder of SmartyStreets, we have an address verification API called LiveAddress.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Connect By Prior Equivalent for MySQL All,
I have three fields in a table that define a parent child relationship present in a MySQL database version 5.0 . The table name is tb_Tree and it has the following data:
Table Name: tb_Tree
Id | ParentId | Name
--------------------
1 | 0 | Fruits
2 | 0 | Vegetables
3 | 1 | Apple
4 | 1 | Orange
5 | 2 | Cabbage
6 | 2 | Eggplant
How do I write a Query to get all the children if a ParentId is specified. Note that the table entries given are just sample data and they can have many more rows. Oracle has a "CONNECT BY PRIOR" clause, but I didn't find anything similar for MySQL. Can anyone please advise?
Thanks
A: Might be late post.
With MySQL8 you can achieve it with recursive clause. Here is the example.
with recursive cte (id, name, parent_id) as (
select id,
name,
parent_id
from products
where parent_id = 19
union all
select p.id,
p.name,
p.parent_id
from products p
inner join cte
on p.parent_id = cte.id
)
select * from cte;
For more help find another thread, Hope It will help someone.
A: You Can also look into this interesting blog, which demonstrate how can we get similar results in mysql
http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/
A: This is an old thread, but since I got the question in another forum I thought I'd add it here. For this case, I created a stored procedure that is hard-coded to handle the specific case. This do, of course have some drawbacks since not all users can create stored procedures at will, but nevertheless.
Consider the following table with nodes and children:
CREATE TABLE nodes (
parent INT,
child INT
);
INSERT INTO nodes VALUES
( 5, 2), ( 5, 3),
(18, 11), (18, 7),
(17, 9), (17, 8),
(26, 13), (26, 1), (26,12),
(15, 10), (15, 5),
(38, 15), (38, 17), (38, 6),
(NULL, 38), (NULL, 26), (NULL, 18);
With this table, the following stored procedure will compute a result set consisting of all the decedents of the node provided:
delimiter $$
CREATE PROCEDURE find_parts(seed INT)
BEGIN
-- Temporary storage
DROP TABLE IF EXISTS _result;
CREATE TEMPORARY TABLE _result (node INT PRIMARY KEY);
-- Seeding
INSERT INTO _result VALUES (seed);
-- Iteration
DROP TABLE IF EXISTS _tmp;
CREATE TEMPORARY TABLE _tmp LIKE _result;
REPEAT
TRUNCATE TABLE _tmp;
INSERT INTO _tmp SELECT child AS node
FROM _result JOIN nodes ON node = parent;
INSERT IGNORE INTO _result SELECT node FROM _tmp;
UNTIL ROW_COUNT() = 0
END REPEAT;
DROP TABLE _tmp;
SELECT * FROM _result;
END $$
delimiter ;
A: The below select lists all plants and their parentid up to 4-level (and of course you can extend the level):
select id, name, parentid
,(select parentid from tb_tree where id=t.parentid) parentid2
,(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid)) parentid3
,(select parentid from tb_tree where id=(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid))) parentid4
from tb_tree t
and then you can use this query to get the final result. for example, you can get all children of "Fruits" by the below sql:
select id ,name from (
select id, name, parentid
,(select parentid from tb_tree where id=t.parentid) parentid2
,(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid)) parentid3
,(select parentid from tb_tree where id=(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid))) parentid4
from tb_tree t) tt
where ifnull(parentid4,0)=1 or ifnull(parentid3,0)=1 or ifnull(parentid2,0)=1 or ifnull(parentid,0)=1
A: MySQL doesn't support recursive queries so you have to do it the hard way:
*
*Select the rows where ParentID = X where X is your root.
*Collect the Id values from (1).
*Repeat (1) for each Id from (2).
*Keep recursing by hand until you find all the leaf nodes.
If you know a maximum depth then you can join your table to itself (using LEFT OUTER JOINs) out to the maximum possible depth and then clean up the NULLs.
You could also change your tree representation to nested sets.
A: The below stored procedure order a table that has rows with back reference to the previous one. Notice on the first step I copy rows into temp table - those rows match some condition. In my case those are rows that belong to the same linear (road that is used in GPS navigation). Business domain is not important. Just in my case I am sorting segments that belong to the same road
DROP PROCEDURE IF EXISTS orderLocations;
DELIMITER //
CREATE PROCEDURE orderLocations(_full_linear_code VARCHAR(11))
BEGIN
DECLARE _code VARCHAR(11);
DECLARE _id INT(4);
DECLARE _count INT(4);
DECLARE _pos INT(4);
DROP TEMPORARY TABLE IF EXISTS temp_sort;
CREATE TEMPORARY TABLE temp_sort (
id INT(4) PRIMARY KEY,
pos INT(4),
code VARCHAR(11),
prev_code VARCHAR(11)
);
-- copy all records to sort into temp table - this way sorting would go all in memory
INSERT INTO temp_sort SELECT
id, -- this is primary key of original table
NULL, -- this is position that still to be calculated
full_tmc_code, -- this is a column that references sorted by
negative_offset -- this is a reference to the previous record (will be blank for the first)
FROM tmc_file_location
WHERE linear_full_tmc_code = _full_linear_code;
-- this is how many records we have to sort / update position
SELECT count(*)
FROM temp_sort
INTO _count;
-- first position index
SET _pos = 1;
-- pick first record that has no prior record
SELECT
code,
id
FROM temp_sort l
WHERE prev_code IS NULL
INTO _code, _id;
-- update position of the first record
UPDATE temp_sort
SET pos = _pos
WHERE id = _id;
-- all other go by chain link
WHILE (_pos < _count) DO
SET _pos = _pos +1;
SELECT
code,
id
FROM temp_sort
WHERE prev_code = _code
INTO _code, _id;
UPDATE temp_sort
SET pos = _pos
WHERE id = _id;
END WHILE;
-- join two tables and return position along with all other fields
SELECT
t.pos,
l.*
FROM tmc_file_location l, temp_sort t
WHERE t.id = l.id
ORDER BY t.pos;
END;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Any possibility to use Graphics.DrawString on a 1bpp Bitmap? The question is quite self explicative, I would like to use a 1bpp Bitmap because will help me (a lot) talking with a device that accept 1bbp bitmaps (well, 160x43 byte array that is a 160x43 bitmap image with 1bpp format).
While C# allows me to create 1bpp bitmaps, I would like to work on it with a Graphics object. But the program seems to behave strangely when I do any operation on this.
Is possible to do some graphic operations on those type of bitmaps?
my code snippet is quite short:
Bitmap bwImage = new Bitmap(160, 43, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
using (Graphics g = Graphics.FromImage(bwImage))
{
g.FillRectangle(Brushes.White, new Rectangle(0, 0, 160, 43));
g.DrawString("ciao sono francesco", Font, Brushes.Black, new RectangleF(0f, 0f, 159f, 42f));
}
When I do anything related to bitmaps after those calls. My bitmaps doesn't change (obviusly I'm talking about other bitmaps). Like if GDI is totally dead
Any ideas?
A: The Graphics class and the Graphics.FromImage method do not support indexed bitmaps. Please refere to the documentation for the Graphics.FromImage method on MSDN. A workaround for your problem would be to do all graphic operations on a supported bitmap format such as PixelFormat.Format32bppRgb and then convert the bitmap to a indexed bitmap. The conversion is straightforward. You will find a example of such a conversion here.
Hope, this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sub-packaging my static meta-model classes on Eclipse Indigo I'm currently using Eclipse Indigo and I'd like to have my meta-model classes to be automatically generated in a sub-package instead of having them in the same package of my entities.
I've followed the instructions in the JPA User Guide for Canonical Model Generator on Eclipse Galileo, but it's not working at all with Indigo. :(
Does anybody use the static meta-model classes in a sub-package? Is there any way to configure it on Eclipse Indigo?
A: Maybe you should not change package
I would suggest against it, because having those in sub package (or any other) violates current JPA 2 specification:
• For each managed class X in package p, a metamodel class X_ in
package p is created.[67]
...
[67] We expect that the option of
different packages will be provided in a future release of this
specification.
...
Implementations of this specification are not
required to support the use of non-canonical metamodel classes.
Applications that use non-canonical metamodel classes will not be
portable.
Other way to organize is common JUnit practice: same package in different source directory.
But if you have to, this is how it is done
Following works at least with Eclipse version: Indigo Service Release 1 20110916-0149 and EclipseLink: eclipselink-2.3.0.v20110604-r9504. Names of the JARs can slightly vary from version to another.
If enabled, disable generating to the same package where entities are:
*
*Go to Project Properties - JPA and check that value of Source Folder
is <None>
Adjusting generating to the other package:
*
*Properties - Annotation Processing
[x] Enable project specific settings
[x] Enable annotation processing
[x] Enable processing in editor
Generated source directory: src (or wherever sources live)
*New processor option:
key=eclipselink.canonicalmodel.subpackage
value=sub | (desired package name)
*Go one level deeper to the Annotation Processing | Factory Path and select Add External JARs and add following jars:
eclipselink/jlib/jpajavax.persistence_2.0.3.v201010191057.jar
eclipselink/jlib/jpaeclipselink-jpa-modelgen_2.3.0.v20110604-r9504.jar
eclipselink/jlib/eclipselink.jar
*Let Eclipse rebuild project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Return an Array of Strings in C? For example, I have in the main file
1) char ** array[NUMBER];
2) array = build_array();
and in an imported file
char ** build_array()
{
char ** array[NUMBER];
strings[0] = "A";
strings[1] = "B";
return (char *) strings;
}
However, at line 2 in the main file, I get the error: "incompatible types when assigning to type 'char **[(unsighed int)NUMBER]' from type 'char **'
What am I doing wrong? Any suggestions or advice would be appreciated. Thank you in advance.
A: As littleadv pointed out, there are several problems with your code:
*
*Mismatch between char ** and char **[ ]
*Returning a pointer to a local variable
*Etc.
This example might help:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define NUMBER 2
#define MAX_STRING 80
char **
build_array ()
{
int i = 0;
char **array = malloc (sizeof (char *) * NUMBER);
if (!array)
return NULL;
for (i = 0; i < NUMBER; i++) {
array[i] = malloc (MAX_STRING + 1);
if (!array[i]) {
free (array);
return NULL;
}
}
strncpy (array[0], "ABC", MAX_STRING);
strncpy (array[1], "123", MAX_STRING);
return array;
}
int
main (int argc, char *argv[])
{
char **my_array = build_array ();
if (!my_array) {
printf ("ERROR: Unable to allocate my_array!\n");
return 1;
}
else {
printf ("my_array[0]=%s, my_array[1]=%s.\n",
my_array[0], my_array[1]);
}
return 0;
}
A: There seem to be some confusion about what a string is in C. In C, a null terminated sequence of chars is considered a string. It is usually represented by char*.
I just want to call the build_array() function and return the array of strings
You pretty much can't return an array, neither a pointer to a local array. You could however pass the array to build_array as an argument, as well as its size, and fill that instead.
void build_array( char* strings[], size_t size )
{
// make sure size >= 2 here, based on your actual logic
strings[0] = "A";
strings[1] = "B";
}
...later called as:...
char *array[NUMBER];
build_array(array, NUMBER);
The alternatives are to return a pointer to a global or static allocated array, which would make your function non-reentrant. You probably don't care about this now, but is bad practice so I would recommend you avoid going that route.
A: Your return type is char**, while you're assigning it to char**[], that's incompatible.
Other than that you should post the actual code that you have problem with, the code you posted doesn't compile and doesn't make much sense.
In order to fix your code, the function should be returning char **[NUMBER]. Note also, that you're casting the return value to char* instead of char** that you declared (or char **[NUMBER] that it should be, and in fact - is).
Oh, and returning a pointer to a local variable, as you do in your case, is a perfect recipe for crashes and undefined behavior.
What you probably meant was:
char *array[NUMBER];
int ret = build_array(array, NUMBER);
// do something with return value or ignore it
and in an imported file
int build_array(char **arr, int size)
{
// check that the size is large enough, and that the
// arr pointer is not null, use the return value to
// signal errors
arr[0] = "A";
arr[1] = "B";
return 0; // asume 0 is OK, use enums or defines for that
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to remove the subdirectory name from the url in asp.net mvc? I have hosted my website in a subdomain, say test.mystie.com and points to a folder called test. when i access my website test is getting added to the url.
expected url: http://test.mystie.com/gallery/image
actual url: http://test.mystie.com/test/gallery/image
How to get rid of the test(http://test.mystie.com/test/gallery/image) in the url? I am using asp.net mvc2,IIS7
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: converting rails db from postgres -> mysql I converted a DB using this:
https://github.com/maxlapshin/mysql2postgres
At a glance it looks like it worked. Tables/columns/indices are in place inside of postgres... Great.
However, db:migrate wants to run all of my migrations. It's as if the schema_migrations table didn't get converted correctly - or had no records. But it does have all of the records, and looks the same as it does in mysql.
That or the postgres adapter tracks migrations in some other way.
A: Are you sure your schema_migrations table has the right schema? Go into psql and do:
> \d schema_migrations
You should see this:
Table "public.schema_migrations"
Column | Type | Modifiers
---------+------------------------+-----------
version | character varying(255) | not null
Indexes:
"unique_schema_migrations" UNIQUE, btree (version)
or nearly that.
If it looks like that and db:migrate still wants to run all your migrations then you probably have some stray spaces in the column values or something similar. You can waste more time trying to fix it or you can just rebuild it by hand and move on to more interesting activities. From psql:
> drop table schema_migrations;
> create table schema_migrations (
version varchar(255) not null,
constraint unique_schema_migrations unique (version)
);
and then from your migrations directory (assuming you're on something Unixy):
$ for m in *.rb; do printf "insert into schema_migrations (version) values ('%s');\n" $(echo $m | sed 's/_.*//');done | psql -h your_host -U your_user -d your_db
You'll have to supply the correct values for the -h, -U, and -d switches of course.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extract partial duplicates from a list of lists; return single match with record of origin of each duplicate; Python I have a list in the following format:
L = ['apples oranges x',
'bananas apples y',
'apples oranges z']
For every item in L, if item.split()[0:2] matches another item.split()[0:2] (i.e., 'apples oranges' matches 'apples oranges') then I need to output a single item.split()[0:2] followed by the tags recording the origin of the partially duplicated line. The tags come from index 3 of each item (i.e, x, y or z).
So, the output of L would be L2:
L2 = ['apples oranges x z',
'bananas apples y']
Any ideas?
A: d = collections.defaultdict(list)
for line in L:
name, value = line.rsplit(' ',1)
d[name].append(value)
then you'll have a dict like that:
{'bananas apples ': ['y'], 'apples oranges ': ['x', 'z']}
So you only need to format the keys and values:
[key + ' '.join(values) for key, values in d.items()]
And the result will be:
['bananas apples y', 'apples oranges x z']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reading an array in unmanaged c++ I have a managed C++ class, with a method whose constructor signature is:
tools_package_net::PackageInfo::PackageInfo(array<Byte>^ bytes)
Within the constructor I wish to call a method on an unmanaged class with the signature:
bool PackageInformation::ReadProject(const unsigned char *data, size_t size)
So I want to call "ReadProject", passing in the data from my "bytes" array. The "size" I can pass using "bytes.Length". But how can I get the data itself? Can I simply typecast the first element &bytes[0] (ala std::vector)?
Any help would be greatly appreciated.
A: cli::pin_ptr<unsigned char> pb = &(bytes[0]);
unsigned char* p = static_cast<unsigned char*>(pb);
According this book.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why declare an array this way I'm looking at code written by someone else and it declares an array this way (which I think is still a string, can someone confirm).
$array = "Label 1" . "~/" . "Label 2" . "~/" . "Label 3" . "~/" . "Label4";
Then later in the code, it does this
split('~/', $array);
Is there a valid reason why anyone would do it this way? I would normally declare it as an array from the start.
A: There is absolutely no defendable reason to do things this way instead of just
$array = Array("Label 1", ... , "Label 4");
In fact it's a very bad way of doing it, unless you can guarantee that the string "~/" will never appear in the array's elements.
A: The only reason I could think of someone doing this is if they want to later save $array to a text file, for example save some application settings to a php file. But they would still have been better to define an array the usual way and then use implode, as others have already mentioned this is still not the best idea and has problems.
A: In variable $array, it's still a string, just like this:
$array = "Label 1~/Label 2~/Label 3~/Label4";
But after it do something like
$realArray = split("~/",$array);
It will become an array.
If someone who know how to create an array doing this, I would guess that he/she wants to save this string for use later. But a better way to do this is
$array = array("Label 1","Label 2","Label 3","Label 4");
$string = implode("~/",$array);
So, just forget it and use the normal way.
A: Without knowing the context I can't be definitive, but doing it like this as you've posted there is no obvious benefit.
It's inefficient, as it uses multiple extra steps (variable assignment, string iteration and array population).
The most efficient way to do this would be:
$array = array( "Label 1", "Label 2", "Label 3", "Label 4" );
This would have the same result.
A: It's a horrible way to do it.
*
*It's not immediately obvious what the code does, over an array() definition which would be recognised immediately.
*split() is deprecated.
*You need to remember that "~/" is magic.
*String concatenation for readability in a code style that hinders readability.
Really, you should drop that and use array('Label 1', ...).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET MVC3 Postback brings up new TAB net MVC View. At the end of the view I have the following Buttons
<div style="clear: both; padding-top: 40px; width: 720px;">
<button name="buttonHelp" value="Help" onclick="window.open('Help.htm',target='_blank');return false;">
Help</button>
<span style="float: right;">
<button name="button" value="Reset">
Reset</button>
<button name="button" value="Save">
Save</button>
</span>
</div>
The Save and Reset causes a postback and the screen gets refreshed properly.
If I click the help button it opens the Help screen in s new TAB which is what I require.
Now after using the help screen I press Save/Reset it always open a new window which I dont want and I find puzzling.
Any idea how to solve this ?
A: The following change solved the problem. the help still opens in a new tab as I wanted
> <button name="buttonHelp" value="Help"
> onclick="window.open('Help.htm');return false;">
> Help</button>
A: Check to ensure that the target isn't staying "_blank" after you click Help and that the target of the form is _self.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: struts tag questions I have two related struts jsp files.
I am new to this and a little confused.
*
*in #1, for td, where are those value from, i mean firstname, lastname, department.name? are those from fields of the java action or hibernate class?
*in #2, on line 10, what is employee? is employee.employee.id the same as the one at the bottom of #2 code? also, in the s:select, are departmentID and name from some class?
Thank you very much for your help...
1.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<link href="<s:url value="/resources/main.css"/>" rel="stylesheet" type="text/css"/>
<title><s:text name="label.employees"/></title>
</head>
<body>
<div class="titleDiv"><s:text name="application.title"/></div>
<h1><s:text name="label.employees"/></h1>
<table width=600 align=center>
<tr> <s:url id="insert" action="setUpForInsertOrUpdate"/>
<td><s:a href="%{insert}">Click Here to Add New Employee</s:a></td>
</tr>
</table><br/>
<table align=center class="borderAll">
<tr>
<th><s:text name="label.firstName"/></th>
<th><s:text name="label.lastName"/></th>
<th><s:text name="label.age"/></th>
<th><s:text name="label.department"/></th>
<th> </th>
</tr>
<s:iterator value="employees" status="status">
<tr class="<s:if test="#status.even">even</s:if><s:else>odd</s:else>">
<td class="nowrap"><s:property value="firstName"/></td>
<td class="nowrap"><s:property value="lastName"/></td>
<td class="nowrap"><s:property value="age"/></td>
<td class="nowrap"><s:property value="department.name"/></td>
<td class="nowrap"><s:url id="update" action="setUpForInsertOrUpdate">
<s:param name="employee.employeeId" value="employeeId"/>
</s:url> <s:a href="%{update}">Edit</s:a>
<s:url id="delete" action="delete">
<s:param name="employee.employeeId" value="employeeId"/>
</s:url> <s:a href="%{delete}">Delete</s:a>
</td>
</tr>
</s:iterator>
</table>
</body>
</html>
2.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<link href="<s:url value="/resources/main.css"/>" rel="stylesheet" type="text/css"/>
</head>
<body>
<center>
<div class="titleDiv"><s:text name="application.title"/></div>
<h1><s:if test="employee==null || employee.employeeId == null">
<s:text name="label.employee.add"/>
</s:if>
<s:else>
<s:text name="label.employee.edit"/>
</s:else></h1>
<table width=600 align=center>
<tr><td><a href="getAllEmployees.action">Click Here to View Employees</a></td>
</tr>
</table>
<table>
<tr><td align="left" style="font:bold;color:red">
<s:fielderror/>
<s:actionerror/>
<s:actionmessage/></td></tr>
</table>
<s:form>
<table align="center" class="borderAll">
<tr><td class="tdLabel"><s:text name="label.firstName"/></td>
<td><s:textfield name="employee.firstName" size="30"/></td>
</tr>
<tr>
<td class="tdLabel"><s:text name="label.lastName"/></td>
<td><s:textfield name="employee.lastName" size="30"/></td>
</tr>
<tr><td class="tdLabel"><s:text name="label.age"/></td>
<td><s:textfield name="employee.age" size="20"/></td>
</tr>
<tr>
<td class="tdLabel"><s:text name="label.department"/></td>
<td><s:select name="employee.department.departmentId"
list="#session.departments"
listKey="departmentId"
listValue="name"
/>
</td>
<s:hidden name="employee.employeeId"/>
</tr>
</table>
<table>
<tr>
<td><s:submit action="insertOrUpdate" key="button.label.submit" cssClass="butStnd"/></td>
<td><s:reset key="button.label.cancel" cssClass="butStnd"/></td>
<tr>
</table>
</s:form>
</center>
</body>
</html>
A: for #1
There is a key-value pair stored in the applicationresource.properties file.This file available in the WEB-Inf folder or its path specify in the WEB.xml file under tag.
<context-param>
<param-name></param-name>
<param-value>(specify the application resource file path)</param-value>
</context-param>
this file contains key-value pair which keys used in your jsp pages.search these label.firstname,label.lastname in that file and you will got the whole situation.
A: To answer your questions:
No. 1. label.firstName could be retrieved from any of the value stack which is maintained by Struts. This can be from the message resource or from the property of the action class which forwards to the jsp. Please refer the document below for more information:
http://struts.apache.org/2.2.3/docs/tag-syntax.html
No. 2. employee.employeeId could be reference to the the employee variable set in the Action which forwards this jsp. If you see the Action class which forwards this jsp, you will something like private Employee employee; along with the setEmployee(Employee employee) and getEmployee() methods which shares this variable outside the object. And if you see the Employee class declaration you will see employeeId as a variable in it. This variable will be accessed by the struts tags using the getter method. Here it would be getEmployeeId(). I recommend that you refer the link below and see the complete tags which could be used in Struts2 along with their usage:
http://struts.apache.org/2.2.3/docs/tag-reference.html
In the s:select of the second jsp, an iteration over #session.departments happen. Here departments could be a list of Department bean over which the iteration occurs. This list is in session scope too. name="employee.department.departmentId" defines the name of the html select element to be generated. You can see this if you view the html source once the page is loaded in the browser. <s:select/> tag generates html select along with html option elements inside it. In this case, when iteration happens on the departments list, each department object is accessed and its departmentId is set as the option element's value attribute and name of department object is set as the content, which you see in the select element. You can refer the s:select tag reference in the above link for more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Error installing psycopg2 in cygwin I'm trying to install psycopg2 in cygwin but have not succeeded yet.
The error is:-
Gaurav@gauravpc ~/FieldAgentWeb/FieldAgentWeb
$ easy_install psycopg2
Searching for psycopg2
Reading http://pypi.python.org/simple/psycopg2/
Reading http://initd.org/psycopg/
Reading http://initd.org/projects/psycopg2
Best match: psycopg2 2.4.2
Downloading http://initd.org/psycopg/tarballs/PSYCOPG-2-4/psycopg2-2.4.2.tar.gz
Processing psycopg2-2.4.2.tar.gz
Running psycopg2-2.4.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-QBYpxH
/psycopg2-2.4.2/egg-dist-tmp-gcLa5F
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
or with the pg_config option in 'setup.cfg'.
error: Directory not empty <built-in function rmdir> /tmp/easy_install-QBYpxH/ps
ycopg2-2.4.2/tests
After that i was trying to get d pg_config file, but couldn't find it on the net.
A: pg_config is part of your PostgreSQL installation. It's in the bin directory of your local installation (e.g. C:\Program Files (x86)\PostgreSQL\9.0\bin). Add that directory to your search path and try to build again.
A: I just managed to install psycopg2 today without installing the windows PostgreSQL (in my case the db is already set up in another server, I just need to connect to it with a python package which depends on psycopg2, so having the complete installation it was not necessary for me).
Following pg_config executable not found , from the cygwin setup I installed postgresql-devel AND libpq-dev ( those should be the necessary ones, for the record I installed also a lot of other packages relative to postgresql like postgresql-client, postgresql-plpython and libpq5).
After that I could run succesfully pip install psycopg2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to disable JButton without hiding its label? I'm developing a project in Java using netbeans IDE and I need to disable a particular JButton. I use the following code for that.
IssuBtn.setEnabled(false);
But after it is disabled it doesn't show the text on the JButton. How can I keep that text on the JButton?
A: This experiment suggests one answer is 'Use a PLAF that is not Metal'.
import java.awt.*;
import javax.swing.*;
class LookOfDisabledButton {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
JPanel pEnabled = new JPanel(new GridLayout(1,0,2,2));
pEnabled.setBackground(Color.green);
gui.add(pEnabled, BorderLayout.NORTH);
JPanel pDisabled = new JPanel(new GridLayout(1,0,2,2));
pDisabled.setBackground(Color.red);
gui.add(pDisabled, BorderLayout.SOUTH);
UIManager.LookAndFeelInfo[] plafs =
UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo plafInfo : plafs) {
try {
UIManager.setLookAndFeel(plafInfo.getClassName());
JButton bEnabled = new JButton(plafInfo.getName());
pEnabled.add(bEnabled);
JButton bDisabled = new JButton(plafInfo.getName());
bDisabled.setEnabled(false);
pDisabled.add(bDisabled);
} catch(Exception e) {
e.printStackTrace();
}
}
JOptionPane.showMessageDialog(null, gui);
}
});
}
}
Alternately, adjust the values in the UIManager.
import java.awt.*;
import javax.swing.*;
class LookOfDisabledButton {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
JPanel pEnabled = new JPanel(new GridLayout(1,0,2,2));
pEnabled.setBackground(Color.green);
gui.add(pEnabled, BorderLayout.NORTH);
JPanel pDisabled = new JPanel(new GridLayout(1,0,2,2));
pDisabled.setBackground(Color.red);
gui.add(pDisabled, BorderLayout.SOUTH);
// tweak the Color of the Metal disabled button
UIManager.put("Button.disabledText", new Color(40,40,255));
UIManager.LookAndFeelInfo[] plafs =
UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo plafInfo : plafs) {
try {
UIManager.setLookAndFeel(plafInfo.getClassName());
JButton bEnabled = new JButton(plafInfo.getName());
pEnabled.add(bEnabled);
JButton bDisabled = new JButton(plafInfo.getName());
bDisabled.setEnabled(false);
pDisabled.add(bDisabled);
} catch(Exception e) {
e.printStackTrace();
}
}
JOptionPane.showMessageDialog(null, gui);
}
});
}
}
As pointed out by kleopatra..
it's not a solution but might be a pointer to the direction to search for a solution
Where 'it' is my answer. In fact, I suspect she hit upon the real cause with the comment:
guessing only: here it's due to violating the one-plaf-only rule.
I second that guess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: how to move 20dip margin left from center? i want to move a seekbar 20dip margin left from center.
android:progressDrawable="@drawable/progress_vertical"
android:thumb="@drawable/seek_thumb" android:layout_height="80dip"
android:layout_width="20dip" android:layout_marginBottom="50dip"
android:layout_alignParentBottom="true" android:visibility="gone"
android:layout_centerHorizontal="true" android:layout_marginLeft="20dip" />
but the above xml code shows it center only.
A: I made a workaround with a TextView in the middle that has no content (and is not visible).
<TextView
android:id="@+id/viewMiddleInvisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnAtTheTop"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp" />
<TextView
android:id="@+id/tvAtLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/viewMiddleInvisible"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@id/viewMiddleInvisible"
android:text="Some text" />
You would obviously have to replace tvAtLeft with whatever you want. Same principle if you want to have something to the right of the center.
A: android:layout_centerHorizontal and android:layout_marginLeft don't work together.
A workaround is to use an invisible view, such as Space:
Space is a lightweight View subclass that may be used to create gaps
between components in general purpose layouts.
So, for your case, inside your RelativeLayout, this should do:
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/blankspace" />
<ProgressBar
android:progressDrawable="@drawable/progress_vertical"
android:thumb="@drawable/seek_thumb"
android:layout_height="80dip"
android:layout_width="20dip"
android:layout_marginBottom="50dip"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@id/blankspace"
android:visibility="gone" />
A: The cleanest answer, which doesn't require to pollute your XML with additional views is simply:
Add a 40dp padding on the right.
Rationale:
Padding belongs to your View, so it counts towards its final size. If you add a 40dp padding, your View will be 40dp wider without padding.
And because you are centering, For every 2dp of padding, your View will move just 1dp to the left, so your View will move only 20dp, as needed.
A: Remove centerHorizontal = true.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: A view controller is in landscape mode, but I'm getting the frame from portrait mode? I have a settings view controller with a table view. The table view is supposed to set its frame to be the frame of the view controller. My app only supports landscape mode, so that's the orientation I'm always in.
However, when the settings view controller loads, the table view has the portrait mode frame of the view controller, even though it's in landscape (360 by 480 when it should be 480 by 360).
Additionally, when I checked to see if the device thought it was in portrait mode, it returned true.
What is causing the problem and how can I fix it?
A: when you call [UIView init] it will default to the screen size of your device in portrait mode (same goes for iPad but with larger size).
Inside [UIViewController viewDidLoad] the self.view will also default to this size.
Screen rotation is only done to the top view (controller) in your hierarchy and rotation messages are forwarded through container-VCs that support this behavior (e.g. UINavigationController, UITabBarController).
If you want your view to be sized correctly, use [UIView initWithFrame:self.view.bounds] for creating a view. Insinde UIViewController you only have the chance to override the loadView Method to set the frame before viewDidLoad gets called (or you could use a different XIB for landscape). You could also hardcode the view's size by setting its frame first thing in viewDidLoad
A: You can use viewWillAppear to size your views before they display
A: You have to implement this in your settings view controller:-
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is it safe to have a lock() inside of a BeginInvoke call? I have a form with a control on it to display some custom objects. In the form I subscribe to an event AddObject that adds objects to a ToAdd List as they come in from the server. I setup a timer to run every 10 seconds to copy the objects from the ToAdd List to the Display List (it was more efficient adding the items in bulk to the control than 1 at a time as they came in), which is bound to a control on my form, then I clear the ToAdd List. Is it safe to have the lock inside of the BeginInvoke? Is there a better way of doing this?
private System.Threading.Timer aTimer;
private readonly Object sync = new Object();
List<object> ToAdd = new List<object();
List<object> Display = new List<object();
private void Init()
{
TimerCallback tcb = IntermittentProcessMessages;
aTimer = new System.Threading.Timer(tcb, null, 1000, 100);
Server.MessageReceived += AddObject;
}
private void AddObject(object t)
{
lock (sync)
{
try
{
ToAdd.Add(t);
}
finally() {}
}
}
private void IntermittentProcessMessages(object source)
{
try
{
if (this.IsHandleCreated == false)
{
return;
}
this.BeginInvoke((Action)delegate()
{
lock (sync)
{
if (ToAdd.Count > 0)
{
ToAdd.ForEach(f => Display.Add(f));
ToAdd.Clear();
}
}
}
}
finally(){}
}
A: Yes it is safe. Technically the lock is not in the BeginInvoke, but in the anonymous function that is is created from the delegate.
Some notes:
*
*List<T> has an AddRange method that is more efficient than multiple Add.
Use it like Display.AddRange(ToAdd);
*The delegate in IntermittentProcessMessages is not covered by the try-catch since the BeginInvoke returns immediately.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I parse XML of having multiple Nodes with same name and show in different controller? See the XML below
http://sosmoths.com/.xml/moths.xml
This XML having multiple images name, I have to show the different title(There are four title) in their respective Controller.
I have 4 controller, and have to show each moth value in different Controller, along with their multiple images values, how can I do it?
I can make single object of should I make four objects?
I am a bit confused in it, please help me.
A:
This XML having multiple images name, I have to show the different
title(There are four title) in their respective Controller. I have 4
controller, and have to show each moth value in different Controller,
along with their multiple images values, how can I do it?
This sounds less like an XML parsing problem and more like an app architecture problem.
That XML basically describes some data and said data would typically be represented by objects in your application. You could go with a CoreData based solution whereby you parse the XML into a local CoreData store (in memory or on disk, matters not) and then display the managed objects as per usual.
Or, assuming that is representative of a typical set of data, you could parse it into your own hand rolled objects (or, even, dictionaries and arrays), then display from there.
There are dozens of questions about parsing XML on SO (and via Google).
The second part of your question hasn't been addressed. Basically, you need to properly layer your app into the model-view-controller pattern. Your model layer would parse the XML and create an object graph that represents the data. Each controller would have a reference to that single model.
This will work fine as long as your app is read only. If the various controllers are expected to also edit the object graph, then it'll need to be a bit more complex in that you'll have to deal with change propagation (this is where CoreData shines; it makes change management, propagation, validation, and undo relatively straightforward).
A: With TBXML you can easily parse the xml and it will convert it into objects to use:
http://www.tbxml.co.uk/TBXML/TBXML_Free.html
and libxml2 is also that you can use easily to parse.
A: try this it worked properly
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
NSLog(@"%@",elementName);
if([elementName isEqualToString:@"moths"]){
mytblarray=[[NSMutableArray alloc] init];
} else if([elementName isEqualToString:@"moth"]){
tmpdic=[[NSMutableDictionary alloc] init];
}
else if([elementName isEqualToString:@"images"]){
imgArray=[[NSMutableArray alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(tmpstr!=nil && [tmpstr retainCount]>0){ [tmpstr release]; tmpstr=nil; }
tmpstr=[[NSString alloc] initWithString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:@"moth"]){
[mytblarray addObject:tmpdic];
[tmpdic release];
}if([elementName isEqualToString:@"images"]){
[tmpdic setValue:imgArray forKey:elementName];
}
else if([elementName isEqualToString:@"image"]){
[imgArray addObject:tmpstr];
}
else if([elementName isEqualToString:@"id"] || [elementName isEqualToString:@"title"]||[elementName isEqualToString:@"description"]){
[tmpdic setValue:tmpstr forKey:elementName];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@"%@",[imgArray description]);
NSLog(@"%@",[mytblarray description]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//get value like it
NSString *cellValue = [[mytblarray objectAtIndex:indexPath.row] valueForKey:@"id"];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//get value like it
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithDictionary:
[mytblarray objectAtIndex:indexPath.row]];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access denied error on window.moveTo() I have a window that is composed of a frameset. When I launch it, I have to
resize it, thus:
<script language="javascript"> window.onload = function(){window.moveTo(0,0); window.resizeTo(400,500); }</script>
but then when I ran it in IE 8, it gives me the "Access denied" error in the
window.moveTo() code.
I also tried using it as:
<body onLoad="moveWindow(this);"><script language="javascript"> function move(obj){ obj.moveTo(0,0);obj.resizeTo(400,500); }
but still gives me the error.
Can somebody help?
A: A workaround for this problem which works for me is to add a simple html file with only "Loading.." text in it. Load it first, move the window, and then load the intended URL:
var win = window.open('blank.html');
win.moveTo(50, 50);
win.location = 'http://www.google.com';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Do you have to use Urban Airship to build push notifications using PhoneGap? Do you have to use Urban Airship to build push notifications into a PhoneGap app?
Everything I've found so far mentions Urban Airship....
A: No you don't have to use Urban Airship for this. Urban Airship is actually a third party 'framework' which communicates with C2DM (Androids Cloud To Device Messaging) for you.
But, it can be quite difficult to build this by yourself. That's why alot use Urban Airship at the moment. It provides an easy way to add notfications to your Android app, aswell as for your iPhone or Black Berry app.
So basically Urban Airship provides you one framework and you're able to build Push Notifications for three platforms.
It also comes with an online backend which allows you to easily send the Push Notifications to all users.
So my advice is, check it out. I do recommend it.
For an indept tutorial on how to implement this for Android, then check the following site which helped me alot:
http://phpmyweb.net/2011/10/04/use-urban-airship-for-your-android-app/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I parse a query string with "&" in the value using C#? I have a C# custom webpart on a sharepoint 2007 page. When clicking on a link in an SSRS report on another page, it sends the user to my custom webpart page with a query string like the following:
?tax4Elem=Docks%20&%20Chargers&ss=EU%20MOVEX&Phase=1&tax3Elem=Play%20IT&tax5Elem=Charger
Take note of the value for "tax4Elem", which is basically "Docks & Chargers". (The ampersand can actually come up in "tax4Elem", "tax3Elem", and "tax5Elem").
I cannot have the ampersand in that value encoded so I will have to work with this.
How do I parse this query string so that it doesn't recognize the "&" in "Docks & Chargers" as the beginning of a key/value pair?
Thanks in Advance!
kate
A: I think you can't parse that string correctly - it has been incorrectly encoded. The ampersand in "Docks & Chargers" should have been encoded as %26 instead of &:
?tax4Elem=Docks%20%26%20Chargers&ss=EU%20MOVEX&Phase=1&tax3Elem=Play%20IT&tax5Elem=Charger
Is it possible to change the code that generated the URL?
A: Obviously the request is incorrect. However, to work-around it, you can take the original URL, then find the IndexOf of &ss=. Then, find the = sign immediately before that. Decode (with UrlDecode) then reencode (with UrlEncode) the part between the = and &ss= (the value of tax4Elem). Then, reconstruct the query string like this:
correctQueryString = "?tax4Elem=" + reencodedTaxValue + remainderOfQueryString
and decode it normally (e.g. with ParseQueryString) into a NameValueCollection.
A: If you really cannot correct the URL, you can still try to parse it, but you have to make some decisions. For example:
*
*Keys can only contain alphanumeric characters.
*There are no empty values, or at least, there is always an equal sign = after the key
*Values may contain additional ampersands and question marks.
*Values may contain additional equal signs, as long as they don't appear to be part of a new key/value pair (they are not preceded with &\w+)
One possible way to capture these pairs is:
MatchCollection matches = Regex.Matches(s, @"\G[?&](?<Key>\w+)=(?<Value>.*?(?=$|&\w+=))");
var values = matches.Cast<Match>()
.ToDictionary(m => m.Groups["Key"].Value,
m => HttpUtility.UrlDecode(m.Groups["Value"].Value),
StringComparer.OrdinalIgnoreCase);
You can then get the values:
string tax4 = values["tax4Elem"];
Note that if the query string is "invalid" according to our rule, the pattern may not capture all values.
A: Or you can use HttpServerUtility.HtmlDecode method to decode the value to '&' (ampersand) sign
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Subsets and Splits