text stringlengths 8 267k | meta dict |
|---|---|
Q: Reorganizing large amount of files with regex? I have a large amount of files organized in a hierarchy of folders and particular file name notations and extensions. What I need to do, is write a program to walk through the tree of files and basically rename and reorganize them. I also need to generate a report of the changes and information about the transformed organization along with statistics.
The solution that I can see, is to walk through the tree of files just like any other tree data structure, and use regular expressions on the path name of the files. This seems very doable and not a huge amount of work. My questions are, is there tools I should be using other than just C# and regex? Perl comes to mind since I know it was originally designed for report generation, but I have no experience with the language. And also, is using regex for this situation viable, because I have only used it for file CONTENTS not file names and organization.
A: Yes, Perl can do this. Here's something pretty simple:
#! /usr/bin/env perl
use strict;
use warnings;
use File::Find;
my $directory = "."; #Or whatever directory tree you're looking for...
find (\&wanted, $directory);
sub wanted {
print "Full File Name = <$File::Find::name>\n";
print "Directory Name = <$File::Find::dir>\n";
print "Basename = <$_\n>";
# Using tests to see various things about the file
if (-f $File::Find::name) {
print "File <$File::Find::name> is a file\n";
}
if (-d $File::Find::name) {
print "Directory <$File::Find::name> is a directory\n";
}
# Using regular expressions on the file name
if ($File::Find::name =~ /beans/) { #Using Regular expressions on file names
print "The file <$File::Find::name> contains the string <beans>\n";
}
}
The find command takes the directory, and calls the wanted subroutine for each file and directory in the entire directory tree. It is up to that subroutine to figure out what to do with that file.
As you can see, you can do various tests on the file, and use regular expressions to parse the file's name. You can also move, rename, or delete the file to your heart's content.
Perl will do exactly what you want. Now, all you have to do is learn it.
A: If you can live with glob patterns instead of regular expressions, mmv might be an option.
> ls
a1.txt a2.txt b34.txt
> mmv -v "?*.txt" "#2 - #1.txt"
a1.txt -> 1 - a.txt : done
a2.txt -> 2 - a.txt : done
b34.txt -> 34 - b.txt : done
Directories at any depth can be reorganized, too. Check out the manual. If you run Windows, you can find the tool in Cygwin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to remove collapsed space in a listbox with items type wrappanel, full source + pic included I have a ListBox with ItemsPanelTemplate of WrapPanel. There's some left & right padding of the collapsed elements, which I want to get rid of... When the elements are visible, the image is a nice square with five buttons per row. Here is an image:
http://iterationx.posterous.com/71739342
How can I get rid of the padding at the beginning of the first button when my A-E buttons are collapsed?
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" SizeToContent="WidthAndHeight"
>
<Grid Margin="100,100,100,100">
<StackPanel>
<ListBox Name="MainButtonListBox" HorizontalContentAlignment="Stretch" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Padding="0" Width="550">
<ListBox.ItemsPanel>
<ItemsPanelTemplate >
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate >
<DataTemplate>
<Button Content="{Binding Path=ButtonName}" Click="Button_Click" DataContext="{Binding}" Width="100" Height="75" Visibility="{Binding Path=Visibility}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public class ButtonObj
{
public string ButtonName { get; set; }
public Visibility Visibility { get; set; }
}
List<ButtonObj> AEList = new List<ButtonObj>();
List<ButtonObj> MainButtonList = new List<ButtonObj>();
public MainWindow()
{
InitializeComponent();
AEList.Add(new ButtonObj() { ButtonName = "A", Visibility = Visibility.Collapsed });
AEList.Add(new ButtonObj() { ButtonName = "B", Visibility = Visibility.Collapsed });
AEList.Add(new ButtonObj() { ButtonName = "C", Visibility = Visibility.Collapsed });
AEList.Add(new ButtonObj() { ButtonName = "D", Visibility = Visibility.Collapsed });
AEList.Add(new ButtonObj() { ButtonName = "E", Visibility = Visibility.Collapsed });
foreach (ButtonObj b1 in AEList) MainButtonList.Add(b1);
MainButtonList.Add(new ButtonObj() { ButtonName = "Expand A-E", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "G", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "H", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "I", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "Collapse A-E", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "K", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "L", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "M", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "N", Visibility = Visibility.Visible });
MainButtonList.Add(new ButtonObj() { ButtonName = "O", Visibility = Visibility.Visible });
MainButtonListBox.ItemsSource = MainButtonList;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
ButtonObj obj = btn.DataContext as ButtonObj;
if (obj.ButtonName == "Expand A-E")
{
foreach (ButtonObj b1 in AEList) b1.Visibility = System.Windows.Visibility.Visible;
}
if (obj.ButtonName == "Collapse A-E")
{
foreach (ButtonObj b1 in AEList) b1.Visibility = System.Windows.Visibility.Collapsed;
}
MainButtonListBox.ItemsSource = null;
MainButtonListBox.ItemsSource = MainButtonList;
}
}
}
A: you just collapse the content of the listbox item.
You have to style the ListBoxItem (which is not removed).
<ListBox Name="MainButtonListBox" HorizontalContentAlignment="Stretch" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Padding="0" Width="550" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Padding" Value="0,0,0,0"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate >
<WrapPanel />
</ItemsPanelTemplate>
...
generally it would be better to use the filter possibilities, so that the items are realy removed from the listbox and not just the content hidden (the items are still selectable with the keyboard)
you also can (better than first style) collapse the whole item:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Visibility" Value="{Binding Path=Visibility}"/>
</Style>
</ListBox.ItemContainerStyle>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: geolocation array with static variables I have two locations (markers) to display on a google map, one is a static variable called "companyLocale". The second is a dynamic variable based on your current location "initialLocation". I am trying to group them into an array called "localArray" but I can't get the "companyLocale" variable to display within the array . Can someone please help me?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: iPhone Geolocation</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var initialLocation;
var companyLocale = new google.maps.LatLng(33.206060, -117.111951);
var localArray = [initialLocation,companyLocale];
var noGeo = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
function initialize() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Safari supports the W3C Geolocation method
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var placeMarker = new google.maps.Marker({
position: initialLocation,
map: map,
});
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation();
}
function handleNoGeolocation() {
initialLocation = noGeo;
map.setCenter(initialLocation);
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
A: You're populating localArray with the two values before your initialize function gets called. As you've already defined companyLocale as a LatLng, that one is fine, but you don't create the initialLocation LatLng until later in your execution.
I would say remove initialLocation from the array initially. Then after you create it, add it into the array. I don't know if the order of the array items is important here for you or not. If it isn't, just use .push() to append it into the array. Otherwise use unshift() to prepend it.
<script type="text/javascript">
var initialLocation;
var companyLocale = new google.maps.LatLng(33.206060, -117.111951);
var localArray = [companyLocale];
var noGeo = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
function initialize() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Safari supports the W3C Geolocation method
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
localArray.unshift(initialLocation);
var placeMarker = new google.maps.Marker({
position: initialLocation,
map: map,
});
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation();
}
function handleNoGeolocation() {
initialLocation = noGeo;
localArray.unshift(initialLocation );
map.setCenter(initialLocation);
}
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does "too many positional options" mean when doing a mongoexport? mongoexport -h db.mysite.com -u myUser -p myPass -c myCollection
But the response I get is:
ERROR: too many positional options
What's that about?
A: I had the same issue with mongodump. After searching a bit, I found out that using the --out parameter to specify the output directory would solve this issue. The syntax for using the out parameter is
mongoexport --collection collection --out collection.json
Also in case your Mongodb instance isn't running, then you could use the --dbpath to specify the exact path to the files of your instance.
Source: http://docs.mongodb.org/manual/core/import-export/
A: I had this same problem. In my case, I was using mongoexport with the --query option, which expects a JSON document, such as:
mongoexport ... --query {field: 'value'} ...
I needed to surround the document with quotes:
mongoexport ... --query "{field: 'value'}" ...
A: I had the same issue with the mongoexport utility (using 2.0.2). My fix was to use the FULL parameter name (i.e. not -d, instead use --db).
A: Sometimes editor will screw it up (such as evernote). I fixed the issue by retyping the command in terminal.
A: I was also stuck in same situation and found what was causing it.
*
*Make sure you are exporting in CSV format by adding parameter --type csv
*Make sure there are no spaces in fields name,
Example: --fields _id, desc is wrong but --fields id,desc,price is good
A: This also works if you place the -c option first. For me, this order does work:
mongoexport -c collection -h ds111111.mlab.com:11111 -u user -p pass -d mydb
You can also leave the pass out and the server will ask you to enter the pass. This only works if the server supports SASL authentication (mlab does not for example).
A: for the (Error: Too many arguments)
Dont Use Space Between the Fields
try:
mongoexport --host localhost --db local --collection epfo_input --type=csv --out epfo_input.csv --fields cin,name,search_string,EstablishmentID,EstablishmentName,Address,officeName
Dont_Try:
mongoexport --host localhost --db local --collection epfo_input --type=csv --out epfo_input.csv --fields cin,name,search_string,Establishment ID,Establishment Name,Address,office Name
A: I had the same problem. Found a group post somewhere which said to remove the space between the '-p' and the password, which worked for me.
Your sample command should be:
mongoexport -h db.mysite.com -u myUser -pmyPass -c myCollection
A: The same error I have encountered while importing a csv file.
But its just, the fact that the field list which you pass for that csv file import may have blank spaces.
Just clear the blank spaces in field list.
Its the parsing error.
A: I had the same issue with starting mongod. I used the following command:
./mongod --port 27001 --replSet abc -- dbpath /Users/seanfoley/Downloads/mongodb-osx-x86_64-3.4.3/bin/1 --logpath /Users/seanfoley/Downloads/mongodb-osx-x86_64-3.4.3/log.1 --logappend --oplogSize 5 --smallfiles --fork
The following error message appeared:
Error parsing command line: too many positional options have been specified on the command line
What fixed this issue was removing the single space between the '--' and 'dbpath'
A: Had a similar issue
$too many positional arguments
$try 'mongorestore --help' for more information
Simply fix for me was to wrap the path location in quotes " "
This Failed:
mongorestore -h MY.mlab.com:MYPORT -d MYDBNAME -u ADMIN -p PASSWORD C:\Here\There\And\Back\Again
This Worked:
mongorestore -h MY.mlab.com:MYPORT -d MYDBNAME -u ADMIN -p PASSWORD "C:\Here\There\And\Back\Again"
A: I had the same issue while using the "mongod --dbpath" command. What I was doing looked somewhat like this:
mongod --dbpath c:/Users/HP/Desktop/Mongo_Data
where as the command syntax was supposed to be:
mongod --dbpath=c:/Users/HP/Desktop/Mongo_Data
This worked for me. Apart from this one may take a note of the command function and syntaxes using the mongod --help command.
A: In my case, I had to write the port separately from the server connection. This worked for me:
mongoexport --host=HOST --port=PORT --db=DB --collection=COLLECTION
--out=OUTPUT.json -u USER -p PASS
A: Create a json file in the same folder where you have your mongod.exe.
eg: coll.json
and open a command prompt in this folder.
type this below in CMD.
mongoexport --db databasename --collection collectionname --out
coll.json
and you will see like a progress bar very cool exporting all data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: How do I properly emit javascript in Kynetx rule? I have code from my ad network that I am trying insert into an existing rule to call an ad from the server and place it into a div.
The javascript code is given to me to, normally, to embed in my header:
<script type="text/javascript">var z=document.createElement("script");z.type="text/javascript";z.async=true;z.src="http://engine.adzerk.net/z/12735/azk1_2_5";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(z, s);</script>
And then the div portion that is placed in the body:
<div id="azk1"></div>
The div is being placed like with this:
rule NAME {
select when pageview "url"
pre {
ad = '<div id="azk1"></div>';
}
replace_inner("#ad-slot-1", ad);
}
First, is the div placement done correctly? and second, how do I need to format the javascript for the rule? Do I use a global emit? can I store it on another server and call it? If so, how should that be formatted?
Thx
A: You can do it two ways. The first is the use resource syntax. Put this in the global block:
use javascript resource "http://yourserver.com/path/to/javascript.js"
Then put the JavaScript like normal in that file.
The second option is to use an emit in the rule itself. It goes in the action block, so your new rule would look like this:
rule NAME {
select when pageview "url"
pre {
ad = '<div id="azk1"></div>';
}
{
emit <|
// Your JavaScript here
|>;
replace_inner("#ad-slot-1", ad);
}
}
The JavaScript you would put in the file or in that emit block is everything between the <script> tags in the code you originally gave.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: css selector question, how to change font colover of parent li when child ul is focused Alright ive been bashing my head against the wall on this one for the last two hours and i have finally given up.
I have a unordered list that has no background at the top level with a text color of #fff. and when rolled over the background turns #fff and the text color turns #000. I also have children ul's that have a background of #fff and text color of #000.
Now what i need to know is how do you style that text color change at the top level when the child ul elements are open but the top level links arent moused over. I can't get it to force the top level li's to stay #000 (i got the background to stick) as soon as i take my mouse off the top level links to move to a child ul the top level text goes back to #fff.
<div class="menu">
<ul>
<li><a href="#">Home</a></li>
<li>About
<ul class="children">
<li><a href="#">About Us</a></li>
</ul>
</li>
</ul>
</div>
.menu ul li{
color: #ffffff;
text-decoration:none;
}
.menu ul li:hover{
color:#000000
background-color:#ffffff;
}
.children{
background-color:#ffffff;
color:#000000
}
This is the markup that i could think of as a best fit scenario. menu ul li has no bg with text color #ffffff. When the user rolls over "About" the background turns to #ffffff, and text turns to #000000. The dropdown falls down and exposes the .children ul/li's. which also have the same bg/text color. as soon as the user moves their mouse off of the parent li link the parent li link goes back to white font on a white background. but the children stays white bg..
I need the font to turn black and white bg for as long as the user is hovered/clicked on a child.
A: you should use the Parents function of jquery when you detect child click .
and when you detected the click - you go to its parents ( where he has some class) - and then
you give the parent the style...
http://jsbin.com/ehuke4/25/edit
A: Maybe give each set of grouped elements a shared class, then use jQuery to set the css for all members of the class. So for menu1, menu2, etc. add the following code:
$(".menu_1").hover(
// on mouseover
function () {
$(".menu_1).css("background-color", "red");
},
// on mouseout
function () {
$(".menu_1).css("background-color", "white");
}
);
A: You are missing a semi colon in your css:
.menu ul li:hover{
color:#000000; <!-- insert this semi-colon -->
background-color:#ff0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET - Connecting a drop box to a data source I've created a SQL server database and it's in the App_Data folder.
I created a drop-down menu on a page that I want populate from a table in the database. But when I do 'choose data source' option in Visual Studio it doesn't display the database.
Why is this?
A: *
*After you click on "Choose Data Source..." and the 'Data Source Configuration Wizard' pops up click on the First DropDown there.
*Select the "New Data Source" option.
*Click on the "DataBase" icon. You can optionally add a ID for your new datasource or leave the Default ID.
*Click the Ok Button. A new window will appear with the connection string configuration.
*If you already have a connection string to connect to your database select it from this list. Otherwise click on the "New Connection..." Button. Follow the steps to create your connection string, or reply if you need help with this.
*Continue with the wizard and select where you want the data for the DropDownList from.
Hopefully this is what you needed.
Hanlet
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Control to display files and folders tree from an FTP server I'd like to display a tree of all the folders and files on an FTP server.
My question is: is it possible to configure FolderBrowserDialog and OpenFileDialog to read from an FTP location, and if not does anybody know about an existing control that would do that?
I've experimented with the OpenFileDialog and although it can read files from an FTP URI, the folder tree on the left isn't populated with FTP folders and it asks me for connection credentials every time.
A: I remember seeing something like that on code project
(http://www.codeproject.com/KB/IP/FtpBrowseDialog.aspx)
But I haven't looked at the code. It sounds like exactly what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fatal error: Call to a member function get_results() on a non-object (jQuery From Plugin & WordPress) I'm trying to use jQuery's Form plugin with in a Wordpress plugin. I'm following this example. I've enqueued my scripts and built my form. In csf_form_handler.php, the equivalent of the example's json-echo.php, I can access the items selected in my form (I have a radiobutton group).
My goal is to use the values selected in the form in a SELECT statement to return data from a custom wordpress database table.
$csf_selected_sport = $_POST['csf_radiobutton_group_sport'];
global $wpdb;
$csf_db_table = $wpdb->prefix . "activity";
$csf_data = $wpdb->get_results($wpdb->prepare("
SELECT *
FROM " .$csf_db_table. "
WHERE " . $csf_selected_sport ." "));
Unfortunately, I'm getting:
Notice: Trying to get property of non-object (on the $wpdb->prefix
line)
Fatal error: Call to a member function get_results() on a non-object
(on the $csf_data line)
The code above in csf_form_handler.php isn't in a function. I don't know if that makes a difference.
How can I change the code so that I can use $wpdb?
Thank you.
A: When writing plugins, it's a good idea to keep your data-handling within the plugin's main file (i.e. not sending it to a separate file), and activate functions to handle it accordingly. Basically, you can set your form's action to point to either the plugin's file, or the page that contains the form.
Let’s assume this form you are working on is displayed on the front end of the site, on the sidebar. To handle data coming from that form when a user clicks “submit”, you could create a function in our plugin's file such as:
function $csf_get_data(){
global $wpdb; //since your this function is in your plugin’s file, $wpdb should be available, so no errors here! =)
$csf_selected_sport = $_POST['csf_radiobutton_group_sport'];
$csf_db_table = $wpdb->prefix . "activity";
$csf_data = $wpdb->get_results($wpdb->prepare("
SELECT *
FROM " .$csf_db_table. "
WHERE " . $csf_selected_sport ." "));
//do your stuff with $csf_data
}
//now run it everytime the plugin is run
if(isset($_POST[‘submit’])){
$csf_get_data();
}
Now, you can set up your form action’s property to send the data to the same page, which will be able to handle it using the function above. You could use either:
action=””
or
action="<?php the_permalink()?>"
Please note: to make sure the data is coming from your site (especially public forms), remember to use wp_nonce_field() to create a nonce field that can be validated byt wordpress via wp_nonce(): http://codex.wordpress.org/Function_Reference/wp_nonce_field
Hope that helps,
Vq.
A: Where are you running this code? It sounds like you are running it BEFORE the $wpdb instance is created (or is out of scope).
How are you loading your csf_form_handler.php file? Are you including as part of a script within Wordpress, or is it your own plugin? If it's the latter, remember that you need to activate it first, so WP can include it in the loading sequence (I'm assuming it's already activated, but JIC)
To see if the $wpdb object has already been created, you could run <?php print_r($wpdb);?> to print out the object's contents.
Let me know more, and hopefully I'd be able to help you.
A: I came across the same issue but I got it resolved by including the wp-config.php file from the root of the WordPress folder like this:
require_once('../../../wp-config.php');
global $wpdb;
I hope this helps.
A: I got this fatal error because I forgot to put
global $wpdb;
inside the file where I put the $wpdb->get_results() function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Populating ASP.NET Menu from both sitemap and database I'm currently using a sitemap as a datasource for my ASP.NET Menu control, however I have one dropdown in the menu that I would like to be dynamically populated from a database. Does anyone know if this would be possible? I haven't been able to find anything online about using both a sitemap and a database.
Thanks in advance!
A: You would need to build your own sitemap provider to mix the two. Look here for a good artivle on building your own.
http://geekswithblogs.net/casualjim/articles/52749.aspx
You would need a slightly different approach where you let most of the default behaviour occur and then patched in your database driven data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to reuse logic inside my custom JSP tag? So I've got this custom JSP tag I've been working on. I now need to do pretty much what <c:url> will do in my tag plus my custom logic.
Is there a way to just re-use <c:url> logic? Inheritance doesn't look like an option since <c:url> will set/print its own setAttributes on the pageContext that I don't want. And overriding that method will means code it again.
Any ideas?
A: Displaytag is a good solution to this as Dave pointed out, it has a lot of built in functionality making it a lot more easier, or else you could manually create page links(this is what I would do, its not complicated and there are plenty of samples around.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: difference between: [ScaffoldColumn (false)] and [Display (AutoGenerateField = false)] To render HTML in my edit view, I use the helper @Html.EditorForModel().
My model:
[Required(ErrorMessage = "Campo obrigatório")]
[Display(Name = "Nome completo")]
public string Name { get; set; }
[Required(ErrorMessage = "Campo é obrigatório")]
[StringLength(100, ErrorMessage = "A {0} deve ter pelo menos {2} characteres.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Senha")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmar senha")]
[Compare("Password", ErrorMessage = "A nova senha e a confirmação da senha não conincidem.")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Campo obrigatório")]
[Display(Name = "Convidado")]
[UIHint("IsGuest")]
public bool IsGuest { get; set; }
[RequiredIf("IsGuest", true, ErrorMessage = "Campo é obrigatório")]
[ScaffoldColumn(false)]
public string CodeGuest { get; set; }
Property: CodeGuest should not be created by the helper @Html.EditorForModel(). (I would like to create it manually.)
Reading on the Internet, I found several points and would like to know the difference.
Remembering that I do not want it to be hidden, this field will only be created by this
EditorTemplates (IsGuest.cshtml):
@using BindSolution.AndMarried.Model;
@model BindSolution.AndMarried.Models.RegisterModel
@Html.EditorFor(e => e.IsGuest)
<span>TESTE</span>
@Html.EditorFor(e => e.CodeGuest)
Question:
What is the difference between: [ScaffoldColumn (false)] and [Display (AutoGenerateField = false)]
Why can not I make [Display (AutoGenerateField = false)] have the effect: 'do not generate the HTML field when calling@Html.EditorForModel()`.
A: The EditorForModel() and DisplayForModel() Html helper methods makes decision of rendering view of the properties of the current Model based on the ViewData.ModelMetadata. The default DataAnnotationsModelMetadataProvider sets the properties of ModelMetadata based on the DataAnnotation attributes.
ScaffoldColumnAttribute.Scaffold affects two properties of ModelMetadata i.e. 'ShowForDisplay' and 'ShowForEdit'.
DisplayAttribute does not affects the above two properties of ModelMetadata.
That is why these two attributes do not have the same effect on generating Html.
A: I also wanted to know the difference, the following is from MSDN - http://msdn.microsoft.com/en-us/library/dd411771(v=vs.95).aspx
"AutoGenerateField - A value that indicates whether the field is included in the automatic generation of user-interface elements such as columns. This value is used by the DataGrid control."
From this it appears that this particular property is meant for DataGrid only.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Symbol font on ABCpdf I'm using the ABCpdf.net component to convert HTML to PDF. Some of the HTML uses the Symbol font to display certain characters. Unfortunately, we are consuming the HTML from a third-party, and it cannot be changed.
My development environment displays the font correctly, but my production environment will not. It acts as though the font is not installed, even though it is. If I render the same HTML in Internet Explorer on the production environment, it displays just fine.
I have tried embedding the font as an .eot and providing a @font-face style in the header. I have tried using TheDoc.AddFont('Symbol'). Any suggestions?
Product: ABCpdf .NET 7 x64
Production OS: Windows Server 2003 x64, IE8
Development OS: Win7 x64, IE8
A: The WebSuperGoo support team responded with the fix: setting font-related HtmlOptions. I set these options, and it fixed the issue. Yay!
If you want to embed the fonts used in a web page/HTML you need to use:
Doc.HtmlOptions.FontEmbed = True
You may also need to set
Doc.HtmlOptions.FontSubstitute = False
and possibly:
Doc.HtmlOptions.FontProtection = False
before you use the Doc.AddImageUrl or Doc.AddImageHtml methods.
Edit: As I mention in the comment below, the option that did the trick was FontProtection = false.
A: Try restarting the server.
I've had a similar issue with fonts on ABCPdf. Although the fonts were clearly installed, for some reason, ABDPdf didn't pick them up until the machine has been restarted.
There may be some non restart way of achieving the same thing, but that would entail understanding what the problem is! If it's easy, just try restarting.
A: Although I said that the Doc.HtmlOptions was the answer, it turned out that it was something else entirely. The symbols did not show up because the font-weight was not normal (i.e., it was bold). There is no bold subset that contains these characters. IE is smart enough to ignore the bold part, but PDF is rather finicky. It cannot find the character, so it just shows nothing.
The real solution was to comb through the HTML and ensure that all symbols were surrounded by a span with font-weight: normal !important. It is perhaps a less elegant solution, but it is effective. The only symbol that still randomly refused to show up is the angle symbol (∠). For this, I replaced it with an image. I still can't figure out why it won't appear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I use JPA to persist a Map (java.util.Map) object inside an entity and ensure the persistence cascades? I have recently started playing around with the Play! Framework for Java, version 1.2.3 (the latest). While testing out the framework, I came across a strange problem when trying to persist a Map object inside a Hibernate entity called FooSystem. The Map object maps a long to a Hibernate entity I have called Foo, with the declaration Map<Long, Foo> fooMap;
My problem is as follows: The correct tables are created as I have annotated them. However, when the FooSystem object fs is persisted, the data in fs.fooMap is not!
Here is the code I am using for the entities. First is Foo:
package models.test;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import play.db.jpa.Model;
@Entity
public class Foo extends Model
{
@ManyToOne
private FooSystem foosystem;
public Foo(FooSystem foosystem)
{
this.foosystem = foosystem;
}
}
And here is FooSystem:
package models.test;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import play.db.jpa.Model;
@Entity
public class FooSystem extends Model
{
@ManyToMany(cascade = {CascadeType.ALL, CascadeType.PERSIST})
@JoinTable(
name = "fooMap",
joinColumns = @JoinColumn(name = "foosystem"),
inverseJoinColumns = @JoinColumn(name = "foo")
)
private Map<Long, Foo> fooMap = new HashMap<Long, Foo>();
public FooSystem()
{
Foo f1 = new Foo(this);
Foo f2 = new Foo(this);
fooMap.put(f1.getId(), f1);
fooMap.put(f2.getId(), f2);
}
public Map<Long, Foo> getFooMap()
{
return fooMap;
}
}
Here is the Controller class I am using to test my set-up:
package controllers;
import javax.persistence.EntityManager;
import models.test.FooSystem;
import play.db.jpa.JPA;
import play.mvc.Controller;
public class TestController extends Controller
{
public static void index() {
EntityManager em = JPA.em();
FooSystem fs = new FooSystem();
em.persist(fs);
render();
}
}
The Play! framework automatically created a transaction for the HTTP request. Although data is inserted into the foo and foosystem tables, nothing is ever inserted into the foomap table, which is the desired result. What can I do about this? What am I missing?
A: I managed to solve this problem using the advice of Java Ka Baby. The issue was actually not in my Model classes; the problem lay within the Controller. Specifically, I was saving the entities in the wrong order. Once I realized that using the @ElementCollection annotation on the Map<Long, Foo> produced the same effects as the join table I was manually specifying, I tried I thought experiment where I re-thought how I was saving my entities.
In the code I posted above, you can see in the FooSystem constructor that two Foo objects, f1 and f2, are put into fooMap before the Foo objects are persisted. I realized that if f1 is not in the database when it is put into the map, how is JPA able to use its ID as a foreign key in the join table?
If you can see where I'm going with this line of reasoning, you can see that the obvious answer is that JPA is not able to accomplish this amazing feat of using a foreign key to reference a nonexistent key. The bizarre thing is that the Play! console did not note any errors at all for the original code I posted, even though it was not correct at all. Either the framework swallowed every Exception thrown during the process, or I've written code that should produce an Exception.
So to fix the problem, I persisted the Foo entities before any operations were performed on them. Only then did I put them into fooMap. Finally, once fooMap was populated, I persisted the FooSystem entity.
Here is the corrected TestController class:
package controllers;
import javax.persistence.EntityManager;
import models.test.Foo;
import models.test.FooSystem;
import play.db.jpa.JPA;
import play.mvc.Controller;
public class TestController extends Controller
{
public static void index() {
EntityManager em = JPA.em();
FooSystem fs = new FooSystem();
Foo f1 = new Foo(fs);
Foo f2 = new Foo(fs);
f1.save();
f2.save();
fs.put(f1.getId(), f1);
fs.put(f2.getId(), f2);
fs.save();
render();
}
}
And, since I changed FooSystem, here is the final code for that class:
package models.test;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import play.db.jpa.Model;
@Entity
public class FooSystem extends Model
{
@ElementCollection
private Map<Long, Foo> fooMap = new HashMap<Long, Foo>();
public FooSystem()
{
}
public Map<Long, Foo> getFooMap()
{
return fooMap;
}
public void put(Long l, Foo f)
{
fooMap.put(l, f);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to create a constant buffer with valid dimension Good evening,
I'm trying to send a XMFLOAT3X3 to a constant buffer (see code below).
ZeroMemory(&constDesc, sizeof(constDesc));
constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constDesc.ByteWidth = sizeof(XMFLOAT3X3);
constDesc.Usage = D3D11_USAGE_DEFAULT;
result = m_pDevice->CreateBuffer(&constDesc,0,&m_pTexTransformCB);
if (FAILED(result)) {
MessageBoxA(NULL,"Error creating constant buffer m_pTexTransformCB", "Error", MB_OK);
return false;
}
But the compiler tells me that XMFLOAT3X3 is an invalid dimension for the constant buffer bytewidth:
D3D11: ERROR: ID3D11Device::CreateBuffer: The Dimensions are invalid. For ConstantBuffers, marked with the D3D11_BIND_CONSTANT_BUFFER BindFlag, the ByteWidth (value = 36) must be a multiple of 16 and be less than or equal to 65536. [ STATE_CREATION ERROR #66: CREATEBUFFER_INVALIDDIMENSIONS ]
However, I'm sort of new to HLSL, so I'm not sure if I set the bytewidth to 48, the float3x3 in the cbuffer of the shader will register properly. How should I handle this best?
If you need any more information, comment and I'll edit the question. I hope it's clear enough.
A: In your case, you can just change the ByteWidth to 48 and it will be fine. If you want to group more than one value together, you're going to need to make sure that your data is aligned to 16 byte boundaries. To do this you can just add __declspec(align(16)) before defining your structures.
__declspec(align(16))
struct Data
{
XMFLOAT3X3 a;
//other stuff here
};
This way you can use sizeof(Data) and be guaranteed that your ByteWidth will be valid. I apologize for giving you an incorrect answer earlier, you do not need to manually pad.
A: “If the bind flag is D3D11_BIND_CONSTANT_BUFFER, you must set the ByteWidth value in multiples of 16”
See the MSDN
,notably the remarks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I cipher plaintext using ECDH? I'm looking for sample Java code to implement the cipher for ECDH encryption. I've already found the method to get the keys required but still haven't found a solution to encrypt the text. Appreciate if anyone can give some guidance.
Btw I am using SpongyCastle as I am programming for Android.
Many Thanks!
A: ECDH is not an encryption algorithm; it cannot encrypt some data you choose. It is a key agreement protocol, which results in a "shared secret": the data which both sender and receiver end up sharing is "secret" (only them know it) but they cannot control its contents.
The idea is that you can use the shared secret as the basis for a symmetric encryption algorithm. Since the shared secret has a relatively non-flexible format (with ECDH, the shared secret is an elliptic curve point, and about half of it is really secret), the normal way is to hash it with a secure hash function (say, SHA-256) and use the hash output (or part of it) as the actual encryption key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Starting a new project with just a header file I am taking a class in C++ and have been given my first project. In class, the professor just talks about syntax, grammar, etc. He never talks about how to use Visual Studio. He emailed us a header file with no explanation whatsoever and expects us to use it for the project. I am not too sure how to get started with this file. I tried creating an empty Visual C++ project, adding this file and running it but for one, there are red underline error everywhere and two, VS says it can't find the executable. If anybody can help me get VS and/or my project set up, I can take care of making the program (just got done writing the same exact program in Java).
This is the header file he sent us. Judging by the looks of it, he's kinda sloppy.
#pragma once
namespace control2 {
using namespace System;
using namespace System::IO; // added by Zhang
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
// added by Zhang
StreamReader ^sr = gcnew StreamReader("control.txt");
this->choice=Int32::Parse(sr->ReadLine());
sr->Close();
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
int choice;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"CS351";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
Graphics ^g = e->Graphics;
// g->Clear(BackColor);
// g->Clear(Color::Red);
for ( int y = 0; y < 10; y++ ) {
// pick the shape based on the user's choice
switch ( choice )
{
case 1: // draw rectangles
g->DrawRectangle(Pens::Black, 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
break;
case 2: // draw ovals
// g->DrawEllipse(Pens::Black, 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
g->DrawArc(Pens::Black, 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10, 0, 360 );
break;
case 3: // fill rectangles
g->FillRectangle(Brushes::Red, 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
break;
case 4: // fill ovals
// g->FillEllipse(gcnew SolidBrush(Color::Red), 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 );
g->FillPie(gcnew SolidBrush(Color::Red), 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10, 0, 360 );
break;
default: // draw lines
g->DrawLine(Pens::Black, 10 + i * 10, 60 + i * 20, 60 + i * 20, 10 + i * 10 );
break;
} // end switch
} // end for
choice=(choice+1)%5;
}
};
}
A: Ughh...pragma...Anyway...
If you open up VS, and go to file, you'll find the new project option. I'm assuming this is a Windows Forms App. So, select new project, under languages select C++, and then Windows Form App. When that's all set, go to file->save all and place it in a directory. Now take the file your professor gave you and put it with the rest of the code files in that directory. Back to your project, under the solution explorer, right click header files, add, add existing, and select your header. That should be enough to get you started!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reporting Services Connect a Report to Multiple Databases I have a report which I would like to have talk to different data sources on different database servers depending on some runtime parameters. Is there any way to set the report connection string on a run by run basis? I'm trying to avoid using a data processing extension but it a thin one to proxy the query seems to be the only way to do it.
Edit
There is a feature is called expression based query strings it did not appear until the SQL server 2005 version of reporting services. http://blogs.msdn.com/b/bimusings/archive/2006/07/20/673051.aspx One version too late for me.
A: One of the most powerful features of Reporting Services is that everything is an expression - including the SQL for your dataset. This means you can build your SQL expression from scratch.
We have a table of databases representing different snapshots of our data with a description and the database name. This is used as the query to populate a parameter the user can select from and then the database name is inserted into the SQL, so your dataset expression looks like this:
="SELECT Field1, Field2, Field3 "
&"FROM " & Parameters!Database.Value & ".dbo.MyTable "
Then when you need to add another database for the user to select from, you just add it to the table of database names and all reports immediately have access to that data.
With servers it should be similar, something like:
="SELECT Field1, Field2, Field3 "
&"FROM " & Parameters!Server.Value & "." & Parameters!Database.Value & ".dbo.MyTable "
You may need to set up the server that you are targeting as a linked server on the server that has the database that the dataset is connected to originally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use ClearCase annotate sub-command? I'm trying to find out how to get a code history report in which I get the file version for each of code line.
I don't need to get multiple rows for each code line. only one.
The 'annotate' sub-command has many arguments and I can't find the good one for that purpose. Do you know how to get that?
Many thanks
A:
the file version for each of code line
That almost looks like the last example of the cleartool annotate command:
cleartool annotate -out - -fmt "%Vn |" -rm -nheader util.c
Meaning: no header, only text line annotations, including the deleted ones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how can i call a range of numbers in an array? So im wanting to compare a number(pullNumb)(gotten by another function elsewhere) to a range of numbers in an array.
for this example, lets say:
var pullNumb = 100;
var morn_T= new Array(6,7,8,9,10,11,12,13,14,15,16,17,18,19);
if(pullNumb>morn_T[1]){ document.write(" xyz ");
}
now instead of me writing out morn_T[1],[2],[3]; etc...is there a way to shorten this?
ideally if i could add this range to a variable that would be great. but anything better than this long way ill gladly take.
i found some page on here but...man that page was WAY to advanced for me....had other languages so i got lost.
im still learning this so any tipslinks etc, i humble accept.
thanks in advance.
A: Hum, so you wan't a loop?
var morn_T= new Array(6,7,8,9,10,11,12,13,14,15,16,17,18,19);
for(var i = 0; i < morn_T.length; i++)
alert(morn_T[i]);
Demo (will spam alert).
I would suggest you read up on JavaScript. This is one of the best resource around.
A: You could make a simple Range type like so:
var Range = function(a,b) {
this.min = Math.min(a,b);
this.max = Math.max(a,b);
}
Range.prototype.contains = function(x) {
return ((this.min <= x) && (x <= this.max));
};
var oneThroughTen = new Range(1, 10);
oneThroughTen.contains(5); // => true
oneThroughTen.contains(0); // => false
You could add additional methods for inclusive/exclusiveness on the ends as well.
Of course, if your range is not continuous then you're best off looping through the contents of the array and comparing.
A: Is the array sorted at all?
Are these document.writes in another sort of string array?
If the array happens to be sorted upwards, you could do the following: (Pseudo code, my javascript isn't the best, please modify as necessary)
var i = 0;
do
{
if(PullNumb > morn_t[i])
{ var stringVar = " ";
for(var j = 0; j <= morn_t[i]; j++)
{
stringVar += morn_t[j];
}
break;
}
i++;
}
while( PullNumb < morn_t[i] && i < morn_t.Length());
So basically if the array is sorted, loop through it. Continue until the array is no more, or until the PullNumb is greater than that array value.
If the pullnumb is greater than that array value, start from the beginning of the array and append each corresponding string value to the stringVar variable.
If, however, the array is just random numbers, and the strings (from document.write) aren't in any sort of array, I suppose using a switch statement is moderately faster.
A: The concept you want may be Array.filter https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter It doesn't exist in every browser, but the page above explains how to implement it
The following code returns an array of all the numbers that are less than pullNumb
var biggerThan = morn_T.filter( function(a){ return pullNumb < a; } );
// Now you can just iterate through the filtered array
for (var i=0; i < biggerThan.length; i ++) { console.log( biggerThan[i] ); }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jEditable, undefined settings when using callback function I'm using jEditable and instead of using ajax to save, I just want to use the callback function to put the contents into a hidden form elements, the problem is using the callback function I receive this error:
Uncaught TypeError: Cannot read property 'settings' of undefined
This is the code I'm using:
$('.editable').editable(function(value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return(value);
}, {
submit : 'OK'
});
Any ideas what the problem could be? Thank you!
A: I had exactly the same error message. But in that case I used the plugin ajaxupload for jEditable in my Javascript and called it like that:
$("edit_photo").editable{type:"ajaxupload"};
On updating jQuery I made only one file containing all the minified stuff to reduce the web to a single request. Then I recognized, that the plugin ajaxupload just was missing.
A: I had simillar problem with dblckick event.
Jquery.validate plugin (v 1.7) was throwing this error.
Fixed by installing new version of Jquery.validate (v 1.9).
A: I was getting this error because I was making a call to $("#element").rules() before a call to $("#form").validate() on the form DOM element. There error was the same using both jQuery Validate version 1.7 and 1.9 (I upgraded per the above suggestion before getting it to work).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SOAP messages in REST based web service Disclaimer: I am really confused between REST and SOAP based services.
After reading many tutorials (which seems contradictory to each other) on REST based web service I was wondering whether we can/should use SOAP to send/receive messages in REST based web service ?
I tried following links
1) http://www.ibm.com/developerworks/webservices/library/ws-restful/
2) http://rest.elkstein.org/2008/02/how-simple-is-rest.html
A: By "SOAP based services" I assume you are meaning WS-I Basic Profile web services. The distinction is important because SOAP can be used with REST as well as WS-I BP web services. Let me explain.
SOAP is an XML based messaging format for exchange of data. Soap also defines a means for making remote procedure calls. SOAP is an open standard from the W3C. SOAP is agnostic about the underlying transport layer. Frequently HTTP is used as a transport layer, but it can happily run over SMTP and TCP, and other transports too.
REST is an architectural style (not a standard), so be careful not to compare REST and SOAP directly because you are not comparing apples with apples. REST takes HTTP and uses it is the way it was meant to be used, with all its subtleties and richness. The REST architectural style can used to transfer data in any format - it does not mandate any particular data format. So SOAP is a perfectly good serialization format for a REST style web service. But many people use JSON, XML, plain text and many other formats with REST. You can happily exchange binary data over REST too, like image files. The nice thing is you get to choose the data format that makes most sense for your application.
Note that since REST is a pattern, not a standard, there is a lot of debate about what it means to be truely RESTful. There is a concept called the Richardson Maturity Model which lays out a series of steps towards the REST ideal. By comparing with Richardson's model we can see exactly how RESTful a particular REST implementation is. WS-I BP web services are at Level 0 on this scale (ie. not very RESTful at all, just using HTTP as a dumb transport layer).
I would say this about choosing REST vs WS-I Basic Profile web services - it depends on your audience. If you are developing a B2B type interface within an enterprise, it is more common to see WSI-BP web services. Because there is an underlying standard, and because of the mature support by enterprise vendors (such as IBM, Oracle, SAP, Microsoft) and because of the level of framework support particularly in .NET and Java, WSI-BP makes a lot of sense when you need to get something going quickly and you want to make it easy for clients to connect in an enterprise environment, and the data being exchanged is business data that serializes nicely as SOAP.
On the other hand if you are exposing web services to the wider web audience, I would say there has been a trend away from WSI-BP and towards the RESTful style. Because REST only assumes the client supports HTTP, it can be made to interoperate with the widest possible audience. REST also gives you the scalability of the web itself, with the support for caching of resources etc which makes it will scale up to a large audience much better than WSI-BP web services.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: python unmanaged dll call, fails on win32 FindWindow api with Access Violation I have the following bare minimum function in a DLL
#define INTELHOOK_API extern "C" __declspec(dllexport)
INTELHOOK_API BOOL testFunc(void) {
BOOL success = false;
HWND parent = NULL;
parent = FindWindow("Arium.SourcePont", NULL);
if (parent != NULL) {
success = true;
}
return success;
}
If I call this from the main function in the DLL it works fine. If I call it from python I get the following:
WindowsError: exception: access violation reading 0x00439508
My python script looks like this:
from ctypes import *
dll = cdll.hook
print dll.testFunc()
I'm running on win7, 64-bit but both the dll and python are 32-bit:
c:\Projects\hg\hooklib>dumpbin /headers hook.dll
Microsoft (R) COFF/PE Dumper Version 9.00.21022.08
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file hook.dll
PE signature found
File Type: EXECUTABLE IMAGE
FILE HEADER VALUES
14C machine (x86)
'
print sys.version
2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
I attached a debugger but can't seem to solve it.
'python.exe': Loaded 'C:\Python27\python.exe'
'python.exe': Loaded 'C:\Windows\SysWOW64\ntdll.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\kernel32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\KernelBase.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\python27.dll'
'python.exe': Loaded 'C:\Windows\SysWOW64\user32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\gdi32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\lpk.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\usp10.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\msvcrt.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\advapi32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\sechost.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\rpcrt4.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\sspicli.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\cryptbase.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\shell32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\shlwapi.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.6161_none_50934f2ebcb7eb57\msvcr90.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\imm32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\msctf.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\PGPmapih.dll'
'python.exe': Loaded 'C:\Python27\DLLs\_ctypes.pyd'
'python.exe': Loaded 'C:\Windows\SysWOW64\ole32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Windows\SysWOW64\oleaut32.dll', Symbols loaded (source information stripped).
'python.exe': Loaded 'C:\Projects\hg\hooklib\hook.dll', Symbols loaded.
The thread 'Win32 Thread' (0x10b0) has exited with code 0 (0x0).
First-chance exception at 0x01d428ae (hook.dll) in python.exe: 0xC0000005: Access violation reading location 0x00439508.
The program '[3836] python.exe: Native' has exited with code 1 (0x1).
The same happens when I access the function with Java through JNA.
Given that the function works while calling from the main in the dll makes me believe it's some access restriction, but that doesn't make sense. I can't be the first one calling win32 functions indirectly in dll's...
Thank you in advance for taking the time to read all this!
Cheers
A: For what it's worth, this works fine for me in 32-bit Windows XP with Python 3.2.1 and 2.7.2, compiled with i686-w64-mingw32-g++.exe version 4.5.3:
c/test.cpp:
#include <windows.h>
#define INTELHOOK_API extern "C" __declspec(dllexport)
INTELHOOK_API BOOL test(void) {
BOOL success = FALSE;
HWND parent = NULL;
parent = FindWindow("notepad", NULL);
if (parent != NULL) {
success = TRUE;
}
return success;
}
// g++ test.cpp -o test.dll -shared
test.py:
import ctypes
dll = ctypes.cdll.LoadLibrary('c/test.dll')
print(dll.test())
It prints 1 if a Notepad window is open, else 0.
A: @eryksun
Thank you for trying. Your answer lead me to find the solution.
I was missing the MSVC equivalent to GCC's -shared (which is /LD) while compiling.
I initially developed and tested the DLL functions from C, then added exports but forgot to add the /LD option.
I'll mark this question as solved, but I still wonder why it causes an access violation if I don't have a proper DllMain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to have per-project formatter that affect tab key policy in Aptana? I'm trying to setup Aptana to be able to have different PHP formatting rules for different projects. For instance I work on both Drupal and Codigniter projects. Drupal coding standard wants 2 spaces for tabs. Codeigniter wants a single tab that shows up as 4 spaces.
The way I would think to make this happen is as follows:
*
*Project > Properties
*Select "Formatter" from options on the left
*Click "Enable project specific settings"
*Click the plus button to create a new profile (eg. call it Drupal)
*Select "PHP" from the list below "Preview:"
*Click the edit button pencil
*Select the indentation tab and set the Tab policy to "Spaces only" with indentation size to 2 and Tab size to 2
*Click Ok twice to apply the changes.
Then I restart Aptana just to make sure the new settings apply. However no matter what I do it still seems to use the settings that are set in Window > Preferences > General > Editors > Text Editors (Displayed tab width, Insert spaces for tabs).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How loop single 'element' in Adobe Edge I am looking for a way to loop the animation of a single element in an Adobe Edge project. I have seen the post telling how to loop the entire animation but I have elements whose timelines are shorter than others, I need it to start looping before the entire animation is over. Thanks in advance.
A: I know this question is super old, but to anyone else stumpling upon this:
Convert the layer to a symbol, and check the "Autoplay" box. This will give the layer its own timeline, and lets you loop it independently from the main stage.
A: This feature is not available in Edge yet.
A: take a look at this:
http://www.heathrowe.com/adobe-edge-apply-complete-action-to-loop-an-animation/
you can loop your animation to a timeline point.
cheers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the 'NerdDinner' OpenID popup window working So I'm trying to implement OpenID using NerdDinner 2 as an example. When you click on one of the OpenID providers, you get a popup window that looks like the screenshot below. I've got most of the underlying code setup correctly and my login page loads and displays the three provider buttons, but when I click on them, there's no popup. It doesn't do anything at all. No JS errors, just nothing happens. What am I missing?
I've looked through the NerdDinner code but I'm having trouble trying to figure out exactly what causes the popup to occur. I don't necessarily need someone to tell me what's wrong with my app, I just need to know what I'm looking for in the NerdDinner app that causes it to happen so I can compare it with mine.
I'm using the following code to render the buttons:
@model dynamic
@using DotNetOpenAuth.Mvc;
@using DotNetOpenAuth.OpenId.RelyingParty;
<div id="login-oauth">
<fieldset>
<legend>via 3rd Party (recommended)</legend>
@using (Html.BeginForm("LogOnPostAssertion", "Auth"))
{
@Html.Hidden("ReturnUrl", Request.QueryString["ReturnUrl"], new { id = "ReturnUrl" })
@Html.Hidden("openid_openidAuthData")
<div>
@MvcHtmlString.Create(Html.OpenIdSelector(new SelectorButton[] {
new SelectorProviderButton("https://me.yahoo.com/", Url.Content("~/Content/images/yahoo.gif")),
new SelectorProviderButton("https://www.google.com/accounts/o8/id", Url.Content("~/Content/images/google.gif")),
new SelectorOpenIdButton(Url.Content("~/Content/images/openid.gif")),
}))
<div class="helpDoc">
<p>
If you have logged in previously, click the same button you did last time!!
</p>
</div>
</div>
}
</fieldset>
</div>
@{
var options = new OpenIdSelector();
options.TextBox.LogOnText = "Log On";
}
@MvcHtmlString.Create(Html.OpenIdSelectorScripts(options, null))
EDIT: This happens in all browsers and there are no popup blockers.
A: For some reason, changing the following route in global.asax.cs from:
routes.MapRoute(
"OpenIdDiscover",
"Auth/Discover");
to:
routes.MapRoute(
"OpenIdDiscover",
"Auth/Discover",
new { controller = "Auth", action = "Discover" }
);
Seems to have fixed the problem. No idea why, but looking at the requests with Firebug showed a 500 error attempting to access this route.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: new data to observable with each method invocation this may be really simple to those in the know-how, but how can i directly provide new data to a given observable, whenever a method of mine is invoked?
IObservable<int> _myObservable;
void ThingsCallMe(int someImportantNumber)
{
// Current pseudo-code seeking to be replaced with something that would compile?
_myObservable.Add(someImportantNumber);
}
void ISpyOnThings()
{
_myObservable.Subscribe(
i =>
Console.WriteLine("stole your number " + i.ToString()));
}
i also dont know what kind of observable i should employ, one that gets to OnCompleted() under special circumstances only?
A: Here's the basic answer. I modified your code slightly.
Subject<int> _myObservable = new Subject<int>();
void ThingsCallMe(int someImportantNumber)
{
// Current pseudo-code seeking to be replaced with something that would compile?
_myObservable.OnNext(someImportantNumber);
}
void ISpyOnThings()
{
_myObservable.Subscribe(
i =>
Console.WriteLine("stole your number " + i.ToString()));
}
This should work. A subject is simply an IObservable and an IObserver. You can call OnCompleted, OnError, etc.
A: I tested and got this working:
static ObservableCollection<int> myCol = new ObservableCollection<int>();
static void Main(string[] args)
{
((INotifyCollectionChanged)myCol).CollectionChanged += new NotifyCollectionChangedEventHandler(Program_CollectionChanged);
ThingsCallMe(4);
ThingsCallMe(14);
}
static void ThingsCallMe(int someImportantNumber)
{
myCol.Add(someImportantNumber);
}
static void Program_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Debug.WriteLine(e.NewItems.ToString());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Enable copy for selected rows in NSTableView I've read through Cocoa Programming for Mac OS X by Aaron Hillegass about how to do Copy/Paste, but I can't get it to work for an NSTableView.
My NSWindowController has a window with a couple of textfields and an NSTableView. When the textfields have focus, the Copy menu is enabled and I can copy the values (which is all default behavior, no action/code on my part was required).
My NSWindowController has a -copy: method implemented and declared:
- (void) copy:(id)sender {
NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
// some code to put data on the pasteBoard
}
However, when I select a few rows and try to Copy, the copy menu is not enabled and I cannot copy the selected rows.
Is there something else I need to do to enable copy for my NSTableView?
A: The problem ended up being that my window's delegate wasn't set to be my window controller, so when the window was trying to validate the menu items it didn't know who to check for selectors.
A: inside the interface builder, make sure that the save menu's selector is connected to the first responder's "save:" action
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to use something other than a header tag to indicate a header in jQuery Mobile collapsible block? According to the documentation, after marking a div with data-role="collapsible" there needs to be a header tag (h1 - h6) so that jQuery Mobile will turn it into the header of the collapsible block.
My question is, is there other way to indicate the header? Something like: data-role="collapsible-header"?
A: Try using a legend rather than h#
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add an attribute to an existing C# class without losing existing extension methods? I have an existing partial class that has extension methods applied to it, in one project.
I want to add an attribute to that class within a different project, but when I create a second partial class the extension methods disappear.
Initially I created the class with the new attribute as a child of the original class, but I want to avoid the tedious up-cast of an instance of the original class to the new child class (though this may be the "best" way in the end).
Is there anyway to add the attribute without losing the extension methods, without using inheritance?
A: You can't declare a partial class across projects - it's got to be in a single project.
Basically if you need an extra attribute on the class, you'll have to put that in the original project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Version to use for Facebook SDK 3.1.1 What is the best version of PHP to run for Facebook SDK 3.1.1? I am currently running PHP 5.2.6, but was wondering if 5.3.8 is better? Is there any thing wrong running either/or?
A: You will need PHP5.2+ to use the Facebook SDK. I tried looking in their documentation for system requirements, but Facebook's docs aren't brilliant.
Using a more recent version of PHP is completely up to you and your application, as it won't give you any noticeable benefits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP PREG_REPLACE Returning wrong result depending on order checked I have stumbled upon a really odd bug with PHP's preg_replace function and some regex patterns. What I'm trying to do is replace custom tags delimited by brackets and convert them to HTML. The regex has to account for custom "fill" tags that will stay with the outputted HTML so that it can be replaced on-the-fly when the page loads (replacing with a site-name for instance).
Each regex pattern will work by itself, but for some reason, some of them will exit the function early if preceded by one of the other patterns is checked first. When I stumbled upon this, I used preg_match and a foreach loop to check the patterns before moving on and would return the result if found - so hypothetically it would seem fresh to each pattern.
This didn't work either.
Check Code:
function replaceLTags($originalString){
$patterns = array(
'#^\[l\]([^\s]+)\[/l\]$#i' => '<a href="$1">$1</a>',
'#^\[l=([^\s]+)]([^\[]+)\[/l\]$#i'=> '<a href="$1">$2</a>',
'#^\[l=([^\s]+) title=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" title="$2">$3</a>',
'#^\[l=([^\s]+) rel=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" rel="$2">$3</a>',
'#^\[l=([^\s]+) onClick=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" onClick="$2">$3</a>',
'#^\[l=([^\s]+) style=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" style="$2">$3</a>',
'#^\[l=([^\s]+) onClick=([^\[]+) style=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" onClick="$2" style="$3">$4</a>',
'#^\[l=([^\s]+) class=([^\[]+) style=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" class="$2" style="$3">$4</a>',
'#^\[l=([^\s]+) class=([^\[]+) rel=([^\[]+)] target=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" class="$2" rel="$3" target="$4">$5</a>'
);
foreach ($patterns as $pattern => $replace){
if (preg_match($pattern, $originalString)){
return preg_replace($pattern, $replace, $originalString);
}
}
}
$string = '[l=[site_url]/site-category/ class=hello rel=nofollow target=_blank]Hello there[/l]';
echo $alteredString = $format->replaceLTags($string);
The above "String" would come out as:
<a href="[site_url">/site-category/ class=hello rel=nofollow target=_blank]Hello there</a>
When it should come out as:
<a href="[site_url]/site-category/" class="hello" rel="nofollow" target="_blank">Hello there</a>
But if moved that pattern further up in the list to be checked sooner, it'd format correctly.
I'm stumped, because it seems like the string is being overwritten somehow every time it's checked even though that makes no sense.
A: Seems to me you're doing a lot more work than you need to. Instead of using a separate regex/replacement for each possible list of attributes, why not use preg_replace_callback to process the attributes in a separate step? For example:
function replaceLTags($originalString){
return preg_replace_callback('#\[l=((?>[^\s\[\]]+|\[site_url\])+)([^\]]*)\](.*?)\[/l\]#',
replaceWithinTags, $originalString);
}
function replaceWithinTags($groups){
return '<a href="' . $groups[1] . '"' .
preg_replace('#(\s+\w+)=(\S+)#', '$1="$2"', $groups[2]) .
'>' . $groups[3] . '</a>';
}
See a complete demo here (updated; see comments).
Here's an updated version of the code based on new information that was provided in the comments:
function replaceLTags($originalString){
return preg_replace_callback('#\[l=((?>[^\s\[\]]+|\[\w+\])+)([^\]]*)\](.*?)\[/l\]#',
replaceWithinTags, $originalString);
}
function replaceWithinTags($groups){
return '<a href="' . $groups[1] . '"' .
preg_replace(
'#(\s+[^\s=]+)\s*=\s*([^\s=]+(?>\s+[^\s=]+)*(?!\s*=))#',
'$1="$2"', $groups[2]) .
'>' . $groups[3] . '</a>';
}
demo
In the first regex I changed [site_url] to \[\w+\] so it can match any custom fill tag.
Here's a breakdown of the second regex:
(\s+[^\s=]+) # the attribute name and its leading whitespace
\s*=\s*
(
[^\s=]+ # the first word of the attribute value
(?>\s+[^\s=]+)* # the second and subsequent words, if any
(?!\s*=) # prevents the group above from consuming tag names
)
The trickiest part is matching multi-word attribute values. (?>\s+[^\s=]+)* will always consume the next tag name if there is one, but the lookahead forces it to backtrack. Normally it would only back off one character at a time, but the atomic group effectively forces it to backtrack by whole words or not at all.
A: You messed up the regular expressions. If you print the string on each iteration as:
foreach ($patterns as $pattern => $replace){
echo "String: $originalString\n";
if (preg_match($pattern, $originalString)){
return preg_replace($pattern, $replace, $originalString);
}
}
you will see that the string is not modified. From my run, I noticed that the second regular expression matches. I placed a third param to the preg_match call and printed the matches. Here is what I got:
Array (
[0] => [l=[site_url]/site-category/ class=hello rel=nofollow target=_blank]Hello there[/l]
[1] => [site_url
[2] => /site-category/ class=hello rel=nofollow target=_blank]Hello there )
A: The cause of your immediate problem at hand is twofold:
First, there is a typo in the applicable regex (the last one in the array). It has an extraneous literal right square bracket before the: " target=". In other words, this:
'#^\[l=([^\s]+) class=([^\[]+) rel=([^\[]+)] target=([^\[]+)]([^\[]+)\[/l\]$#i'
Should read:
'#^\[l=([^\s]+) class=([^\[]+) rel=([^\[]+) target=([^\[]+)]([^\[]+)\[/l\]$#i'
Second, there are two regexes in the array which both match the same string, and unfortunately the more specific of the two (the regex above which is the one we want), comes second. The other more general regex that matches is the second one in the array:
'#^\[l=([^\s]+)]([^\[]+)\[/l\]$#i'
Placing the more general regex last and removing the extraneous square bracket solves the problem. Here is your original code fixed with the above two changes applied:
function replaceLTags($originalString){
$patterns = array(
'#^\[l\]([^\s]+)\[/l\]$#i' => '<a href="$1">$1</a>',
'#^\[l=([^\s]+) title=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" title="$2">$3</a>',
'#^\[l=([^\s]+) rel=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" rel="$2">$3</a>',
'#^\[l=([^\s]+) onClick=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" onClick="$2">$3</a>',
'#^\[l=([^\s]+) style=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" style="$2">$3</a>',
'#^\[l=([^\s]+) onClick=([^\[]+) style=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" onClick="$2" style="$3">$4</a>',
'#^\[l=([^\s]+) class=([^\[]+) style=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" class="$2" style="$3">$4</a>',
'#^\[l=([^\s]+) class=([^\[]+) rel=([^\[]+) target=([^\[]+)]([^\[]+)\[/l\]$#i' => '<a href="$1" class="$2" rel="$3" target="$4">$5</a>',
'#^\[l=([^\s]+)]([^\[]+)\[/l\]$#i'=> '<a href="$1">$2</a>'
);
foreach ($patterns as $pattern => $replace){
if (preg_match($pattern, $originalString)){
return preg_replace($pattern, $replace, $originalString);
}
}
}
$string = '[l=[site_url]/site-category/ class=hello rel=nofollow target=_blank]Hello there[/l]';
echo $alteredString = $format->replaceLTags($string);
Note that this only fixes the immediate specific error described in your question and does not address some more fundamental problems with what you are attempting to accomplish. I have presented a somewhat better solution as an answer to your follow-up question: How do I make this REGEX ignore = in a tag's attribute?.
But as others have mentioned, mixing two different markup languages together and processing with regex is asking for trouble.
A: Here is some general purpose code you can use to have less expressions, you could always remove any tags that are not allowed from the final string.
<?php
function replaceLTags($originalString) {
if (preg_match('#^\[l\]([^\s]+)\[/l\]$#i', $originalString)) {
// match a link with no description or tags
return preg_replace('#^\[l\]([^\s]+)\[/l\]$#i', '<a href="$1">$1</a>', $originalString);
} else if (preg_match('#^\[l=([^\s]+)\s*([^\]]*)\](.*?)\[/l\]#i', $originalString, $matches)) {
// match a link with title and/or tags
$attribs = $matches[2];
$attrStr = '';
if (preg_match_all('#([^=]+)=([^\s\]]+)#i', $attribs, $attribMatches) > 0) {
$attrStr = ' ';
for ($i = 0; $i < sizeof($attribMatches[0]); ++$i) {
$attrStr .= $attribMatches[1][$i] . '="' . $attribMatches[2][$i] . '" ';
}
$attrStr = rtrim($attrStr);
}
return '<a href="' . $matches[1] . '"' . $attrStr . '>' . $matches[3] . '</a>';
} else {
return $originalString;
}
}
$strings = array(
'[l]http://www.stackoverflow.com[/l]',
'[l=[site_url]/site-category/ class=hello rel=nofollow target=_blank]Hello there[/l]',
'[l=[site_url]/page.php?q=123]Link[/l]',
'[l=http://www.stackoverflow.com/careers/ target=_blank class=default]Stack overflow[/l]'
);
foreach($strings as $string) {
$altered = replaceLTags($string);
echo "{$altered}<br />\n";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting Incorrect razor syntax errors I have the following code and I want to put the table headers outside of the @foreach but when i move it outside It no longer sees the closing tag. Thanks
@foreach (var item in Model)
{
<div class="data" ><label for="fullName" >Name: </label>@item.UserName.Replace('.', '')</div>
if (Model.Count > 0)
{
<table class="data">
<tr>
<th>
Work Date
</th>
<th>
Change Details
</th>
<th>
Ip Address
</th>
<th></th>
</tr>
<tr>
<td>
@{
var stringDate = item.WorkDate.ToShortDateString();
}
@Html.DisplayFor(modelItem => stringDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.ChangeDetail)
</td>
<td>
@Html.DisplayFor(modelItem => item.IpAddress)
</td>
</tr>
</table>
}
<br />
<hr />
}
So this is kinda what I'm trying to accomplish, but it keeps giving me errors no matter what way I try it.
<table class="data">
<tr>
<th>
Work Date
</th>
<th>
Change Details
</th>
<th>
Ip Address
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<div class="data" ><label for="fullName" >Name: </label>@item.UserName.Replace('.','')</div>
if (Model.Count > 0)
{
<tr>
<td>
@{
var stringDate = item.WorkDate.ToShortDateString();
}
@Html.DisplayFor(modelItem => stringDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.ChangeDetail)
</td>
<td>
@Html.DisplayFor(modelItem => item.IpAddress)
</td>
</tr>
</table>
}
<br />
<hr />
}
A: You must have your table closing tag outside of the for each loop.
A: Short answer: the closing tag </table> has to be placed outside of the foreach loop.
Long answer: You should put the Model.Count > 0 outside of the foreach loop because the moment you enter the code block within the loop, Model.Count > 0 always evaluates to true because you have at least one item.
If – and only if – your model contains any items, you print out the table header. After that, you append one row for each item in Model. Both <table> and </table> have to occur within the same level of nesting.
@if (Model.Count > 0)
{
<table class="data">
<tr>
<th>Date</th>
<th>Change Details</th>
<th>Ip Address</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<div class="data" >
<label for="fullName" >Name: </label>
@item.UserName.Replace('.', ' ')
</div>
@{
var stringDate = item.WorkDate.ToShortDateString();
}
<tr>
<td>@Html.DisplayFor(modelItem => stringDate)</td>
<td>@Html.DisplayFor(modelItem => item.ChangeDetail)</td>
<td>@Html.DisplayFor(modelItem => item.IpAddress)</td>
</tr>
}
</table>
<br />
<hr />
}
You should consider moving the logic (@item.UserName.Replace('.', ' ')) out of the view into the corresponding controller action.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using native code in java servlets (Server side) I have a c library which i am using in my application on various platforms. Currently, I am planning to develop a web service using same c library using JNI. I will host this webservice using some application server (planning to use weblogic on linux PCs).
Does any one has experience of using native code on java server. Is this approach efficient.
will i face any problems in future?.
A: General rule of thumb is to keep your logic inside native code, and avoid multiple jni calls (which generally cost much in terms of performance, more than having the same logic implemented only in java). But as always it depends greatly on your design and bottlenecks you have (io, cpu, network etc.).
Hope this helps.
A: I am using a native JNI API with Glassfish. The biggest problem is if the C code crashes the entire application server dies immediately, no graceful termination, stack trace, or anything.
I would keep as little on the C side as possible, since Java will be much easier to work with. If you have performance issues then optimize later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Converting XML table to XML treeview using XSLT key and previous-sibling This is my first attempt at XSLT and first post on SO. I need to transform table/row oriented XML to tree oriented XML with unique branches and leafs. I am using XSLT 1.1 and IE8 debugging in VS2008. I have examined XSLT 2nd Edition (M. Kay) and Tennison's article in the Muenchian Grouping Technique which I have tried to incorporate. I have tried to incorporate items related to possible problem areas such as rebuilding the sibling relationships with another variable in order to use previous-sibling to get uniqueness but my previous-sibling is always null and I never see Route 2 or zip 23456. I have examined many postings related to previous-sibling but am unable to get the output I expect. Sorry about the long post but I wanted to make it as clear as possible.
Thanks,
Al
My input is:
<?xml version="1.0"?><root><dataset><CITY_DATA>
<ROW count='1'><CITY>BOSTON</CITY><ZIP>12345</ZIP><ROUTE_NM>Route 1</ROUTE_NM></ROW>
<ROW count='2'><CITY>BOSTON</CITY><ZIP>12345</ZIP><ROUTE_NM>Route 1</ROUTE_NM></ROW>
<ROW count='3'><CITY>BOSTON</CITY><ZIP>34567</ZIP><ROUTE_NM>Route 2</ROUTE_NM></ROW>
<ROW count='4'><CITY>LAKEVILLE</CITY><ZIP>01234</ZIP><ROUTE_NM>Route 1</ROUTE_NM></ROW>
<ROW count='5'><CITY>LAKEVILLE</CITY><ZIP>01234</ZIP><ROUTE_NM>Route 1</ROUTE_NM></ROW>
<ROW count='6'><CITY>LAKEVILLE</CITY><ZIP>23456</ZIP><ROUTE_NM>Route 1</ROUTE_NM></ROW>
</CITY_DATA></dataset></root>
My XSL is:
<xsl:transform version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:output method="xml" indent="yes" version="1.0"/>
<xsl:key name="CITY" match="ROW" use="CITY" />
<xsl:template match="CITY_DATA">
<FIRST_BRANCH>
<xsl:for-each select="ROW[count(. | key('CITY', CITY)[1]) = 1]">
<xsl:sort select="CITY" />
<CITY>
<xsl:value-of select="CITY" />
<xsl:variable name="routes-list">
<xsl:for-each select="key('CITY',CITY)">
<xsl:copy-of select="."/>
</xsl:for-each>
</xsl:variable>
<xsl:for-each select="msxsl:node-set($routes-list)//ROUTE_NM">
<PRE_ROUTE_NM>
<xsl:value-of select="preceding-sibling::ROUTE_NM"/>
</PRE_ROUTE_NM>
<VAL_ROUTE_NM>
<xsl:value-of select="//ROUTE_NM" />
</VAL_ROUTE_NM>
<xsl:if test="//ROUTE_NM[not(preceding-sibling::ROUTE_NM[1])]">
<ROUTE_NM>
<xsl:value-of select="//ROUTE_NM" />
<xsl:for-each select="msxsl:node-set($routes-list)//ZIP">
<xsl:if test="//ZIP[not(preceding-sibling::ZIP[1])]">
<ZIP>
<xsl:value-of select="//ZIP" />
</ZIP>
</xsl:if>
</xsl:for-each>
</ROUTE_NM>
</xsl:if>
</xsl:for-each>
</CITY>
</xsl:for-each>
</FIRST_BRANCH>
</xsl:template>
</xsl:transform>
My Bad Output is:
****CURRENT WRONG OUTPUT ****************
<?xml version="1.0" encoding="utf-8"?>
<FIRST_BRANCH xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<CITY>BOSTON
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>12345</ZIP>
<ZIP>12345</ZIP>
<ZIP>12345</ZIP>
</ROUTE_NM>
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>12345</ZIP>
<ZIP>12345</ZIP>
<ZIP>12345</ZIP>
</ROUTE_NM>
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>12345</ZIP>
<ZIP>12345</ZIP>
<ZIP>12345</ZIP>
</ROUTE_NM>
</CITY>
<CITY>LAKEVILLE
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>01234</ZIP>
<ZIP>01234</ZIP>
<ZIP>01234</ZIP>
</ROUTE_NM>
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>01234</ZIP>
<ZIP>01234</ZIP>
<ZIP>01234</ZIP>
</ROUTE_NM>
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>01234</ZIP>
<ZIP>01234</ZIP>
<ZIP>01234</ZIP>
</ROUTE_NM>
</CITY>
</FIRST_BRANCH>
My Expected Output is:
***BELOW IS EXPECTED OUTPUT**********************
<?xml version="1.0" encoding="utf-8"?>
<FIRST_BRANCH xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<CITY>BOSTON
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>12345</ZIP>
</ROUTE_NM>
<PRE_ROUTE_NM>Route 1</PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<PRE_ROUTE_NM>Route 1</PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 2</VAL_ROUTE_NM>
<ROUTE_NM>Route 2
<ZIP>34567</ZIP>
</ROUTE_NM>
</CITY>
<CITY>LAKEVILLE
<PRE_ROUTE_NM></PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<ROUTE_NM>Route 1
<ZIP>01234</ZIP>
<ZIP>23456</ZIP>
</ROUTE_NM>
<PRE_ROUTE_NM>Route 1</PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
<PRE_ROUTE_NM>Route 1</PRE_ROUTE_NM>
<VAL_ROUTE_NM>Route 1</VAL_ROUTE_NM>
</CITY>
</FIRST_BRANCH>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Edit box: disable user formatting, but add my own I know that rich text boxes in HTML is a bit of a minefield, but I'm hoping this particular situation won't be too tricky. I want a text box which the user can't format, but through scripting I can have it add some light formatting to (so a textarea won't work).
My first thought was that I could use a contentEditable, and if the user doesn't have a toolbar, they can't do much, but there's still the Ctrl + B, Ctrl + I, etc combinations. So I did this:
ctrlHandler = function (event) {
event.preventDefault();
};
this.keydown(function (event) {
if (event.ctrlKey) {
$(this).bind('keypress', ctrlHandler);
}
});
this.keyup(function (event) {
if (event.ctrlKey) {
$(this).unbind('keypress', ctrlHandler);
}
});
So when the Ctrl key is pressed (keydown) an event handler is bound to keypress which prevents the default and when it's released the event handler is unbound. Clever, eh? (I'd work out how to handle cut/copy/paste etc combinations later.) With this, the event handler gets bound correctly, but event.preventDefault() doesn't actually prevent the default! The text gets made bold/italic/underlined exactly as if I'd done nothing. The formatting change seems to happen before the event fires. Using keydown or keyup instead of keypress doesn't work either. Can anyone think of another (cross browser) approach, or how to make this one work?
A: Aha! It seems I've misunderstood what event.ctrlKey does. Pressing Ctrl + B doesn't fire two keydown events... it fires one with event.ctrlKey set to true. So if (event.ctrlKey) event.preventDefault() will do the trick. Not yet tested in all browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java: Calling self-invoking method without freezing? So this is really complicated, it took me a while to realize what's actually happening. Hopefully you understand it better than me though.
I have a Swing class that displays the GUI. In the GUI i have a button, and in the Swing class i have a method that is called whenever i click the button.
When that method is called, i call another method in an object called "Manager". The method in manager then calls another method in a class called "Core". That method in Core sets a local variable, and then calls another method in Core, that self-invokes itself.
The problem is that since it's self-invocing, it never stops running, right? And since it never stops running, nothing is ever returned to the first method in Core. And since nothing is returned to that method, nothing is returned to Manager either. And since that method is never called, the GUI class never gets a response, which leaves the GUI frozen.
Horribly sorry for the messy description. I can't post the code unfortunately. I hope anyone gets my point though, someone must have had the same issue before.
Thanks!
EDIT:
I forgot to mention that the Core class is a thread.
A: Your long-running process is preventing the main Swing thread, the EDT or event dispatch thread, from continuing, and this will make your GUI completely unresponsive. The solution is to do any long-running process in a background thread such as created by a SwingWorker object. Please check out the link called Concurrency in Swing to learn more about use of SwingWorker objects.
A: Self-invocation is called recursion. It's a powerful technique, but could lead to infinite loops (hanging) if you're not careful. You need to make sure every recursion (i.e. every time the method invokes itself) something changes towards a terminating state. For example, you could have a number that is guaranteed to decrease every recursion and have as exit condition that your number is negative. Another example is that you're recursively "eating up" some data structure, let's say a string, until there's nothing left. Usually this "something that changes towards a terminating state" is passed to the method as an argument. Your recursive method should start with a check: is my argument in a terminating state? If yes, terminate, if no, do magic.
Secondly, with Swing you should be careful not to violate it's architecture. It's not really MVC, but rather a 2-layered framework. If you're interested in how to use Swing, I recommend reading up on design patterns like MVC.
A: You got a number of problems.
1) Your recursive function needs an exit condition. So something like
public int imRecursive(int arg) {
if (arg > 100) return;
imRecursive(arg++);
}
in that example, imRecursive doesn't get called over and over, it stops once arg reaches 100.
2) With a swing app, only GUI related code should run in the main event-dispatching thread. If your recursive method is long running, you should use a SwingWorker to do it in another thread so your GUI doesn't lock up.
A: Post some code. You say Core is a Thread, I assume that means class Core extends Thread but we need to see where you are spawning a new thread (calling a method in a class that extends Thread does not make it run in a separate thread).
Your recursive (self-invoking) method, if it never breaks the recursion, will before too long cause StackOverflowError. If you are not getting that then either you are not using a recursive function or breaking the recursion somewhere. The right way to code a method that never terminates is not recursion, it is iteration.
The GUI freezing is almost certainly because some time-consuming processing is occurring in the GUI thread, one more reason to believe that the method in Core is not running in a separate thread.
A: I don't understand WHY you have to self-invoke your method...
are you trying to do some recursion?
if the method never ends, you got a infinite loop, its not good.
Depending for what you are trying, you may use Java Threads, or, rethink your code.. i bet you're doing something wrong.
A: You need to analyse your self-invoking method call - This is a recursive call - but every recursive method must have some condition that stops the recursion - check under what conditions in your case you should get such a condition
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Oracle SQL Input Issue I need to write a script that will prompt a database user in SQL+ to type in the name of a stored procedure and then that stored procedure's code will be displayed.
This will give me the prompt:
accept spinput prompt “Enter Stored Procedure Name:”
Then I can type in the stored procedure name.
Then if I run this code, the stored procedure code will be displayed.
select text from user_source
where type = 'PROCEDURE'
and name = ‘&spinput’;
How do I combine that all into a script that just asks for the input and runs the rest? What is the best way to do this?
Thanks!
A: Perhaps I'm missing something, but aren't you almost there? Can't you just combine your two statements into one file, along with some formatting commands in say, prc.sql:
set feedback off
set heading off
set verify off
accept spinput prompt "Enter Stored Procedure Name:"
select text from user_source
where type = 'PROCEDURE'
and name = UPPER('&spinput');
exit
Then run the following:
sqlplus -s user/pw @prc.sql
Your procedure text will be output to the screen.
I modified your query slightly to translate user input to upper case, since most of the time stored procedure names will be in upper case in the database. This means the user can type text without regard to case and the procedure will be found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Vertical scrolling parallax background effect Background
I have been asked to write a script that will create a vertical scrolling parallax background effect for a project. My initial attempt looks a little something like this:
(function($){
$.fn.parallax = function(options){
var $$ = $(this);
offset = $$.offset();
var defaults = {
"start": 0,
"stop": offset.top + $$.height(),
"coeff": 0.95
};
var opts = $.extend(defaults, options);
return this.each(function(){
$(window).bind('scroll', function() {
windowTop = $(window).scrollTop();
if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
newCoord = windowTop * opts.coeff;
$$.css({
"background-position": "0 "+ newCoord + "px"
});
}
});
});
};
})(jQuery);
// call the plugin
$('.lines1').parallax({ "coeff":0.65 });
$('.lines1 .lines2').parallax({ "coeff":1.15 });
This code does give the required effect, but the bind on the scroll event is a real performance drain.
Question
Part 1. How could I change my plugin to be more efficient?
Part 2. Are there any resources (books, links, tutorials) I can read to find out more?
A: You may try something like:
(function($){
$.fn.parallax = function(options){
var $$ = $(this);
offset = $$.offset();
var defaults = {
"start": 0,
"stop": offset.top + $$.height(),
"coeff": 0.95
};
var timer = 0;
var opts = $.extend(defaults, options);
var func = function(){
timer = 0;
var windowTop = $(window).scrollTop();
if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
newCoord = windowTop * opts.coeff;
$$.css({
"background-position": "0 "+ newCoord + "px"
});
}
};
return this.each(function(){
$(window).bind('scroll', function() {
window.clearTimeout(timer);
timer = window.setTimeout(func, 1);
});
});
};
})(jQuery);
So the browser will not scroll the background if there are multiple scroll events is sequence. I wrote func outside the event handler to avoid the creation of a new closure in every event.
A: You should make the actual "scroll" event handler start a timer:
var opts = $.extend(defaults, options);
var newCoord = null, prevCoord = null;
setInterval(function() {
if (newCoord !== null && newCoord !== prevCoord) {
$$.css({
"background-position": "0 "+ newCoord + "px"
});
prevCoord = newCoord;
}
}, 100);
return this.each(function(){
$(window).bind('scroll', function() {
windowTop = $(window).scrollTop();
if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
newCoord = windowTop * opts.coeff;
}
else
prevCoord = newCoord = null;
});
});
Or something like that. This way, you're only doing the DOM manipulation at most 10 times a second.
A: One thing you could do is instead of:
$(window).bind('scroll', function() {
windowTop = $(window).scrollTop();
if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
newCoord = windowTop * opts.coeff;
$$.css({
"background-position": "0 "+ newCoord + "px"
});
}
});
You can create the window jQuery object outside of the scroll event.
$window = $(window); //create jQuery object
$window.bind('scroll', function() {
windowTop = $window.scrollTop();
if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
newCoord = windowTop * opts.coeff;
$$.css({
"background-position": "0 "+ newCoord + "px"
});
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there some way to write scripts for Winamp? I like to write some scripts for Winamp. How might I do this?
A: You can also use gen_scripting plugin which uses JSpript or VB which might be of use to you.
And a few words to the wise: Just add the plugin to the winamp plugins directory and remember to register it with regsvr32 from the command prompt. Scripting only works with Winamp running :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Local Server Vs. Production Server Im kinda going a little crazy here. I moved my web application to a server and im getting this error below, but on my localhost it works great. Im kinda at a loss of what i should try. Any help would be very much appreciated. Im finding that the error has to have something to do with the dataset not pulling back any data, when I do a for each statement. But the weird thing is that I do a for each statement on another page and it works fine. Here is my for each statement, that im assuming doesnt work. The reason im assuming it b/c when i test it on local it works fine:
Dim retObj As New ClassLibrary1.sql_class
For Each row As DataRow In retObj.sel_all_email_list(company).tables(0).rows
email += row("EMAIL_ADDRESS") & "/"
Next
'*****************************
sql_class
query = "SELECT * " _
& " FROM EMAIL_LIST " _
& " WHERE UCASE(COMPANY) = '" & company & "'"
Dim adapter As New OleDbDataAdapter(query, myConnection)
Dim ds As New DataSet
Try
myConnection.Open()
adapter2.Fill(ds, "test_table")
*returns the dataset, didnt want to type all of the code
Catch ex As Exception
Finally
myConnection.Close()
End Try
'*****************************************************
Error:
Exception Details: System.IndexOutOfRangeException: Cannot find table 0.
A: Check the SQL DB running in Production.
The SQL statement used to fill the Dataset isn't returning any data. That leads to the Dataset not having any tables.
As a result when you make your call to Dataset.Tables(0) a System.IndexOutOfRangeException gets thrown (as there are no tables in the Tables collection).
You can mitigate against this by calling Dataset.Tables.Count to ensure it has items before attempting to access the collection.
If retObj.sel_all_email_list(company).tables.count > 0 Then
'Do something
End If
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: XCode Product > Analyze results I'm getting some unusual responses from the Produce > Analyze option in Xcode 4 that don't seem to make any sense to me. For example, I've always been taught to release instance variables in the dealloc method, but Analyze gives me this:
- (void)dealloc {
[self.fileName release];
//Incorrect decrement of the reference count of an object that is not owned at this point by the caller
Very confusing, can anyone shed some light on this one?
The property looks like this:
@property (nonatomic, retain) NSString * fileName;
A: Confusing wording, but correct, error message.
When you do:
[self.foo release];
That can easily produce a dangling reference for the instance variable backing the foo property. I.e. as far as the compiler is concerned, there is no retain that said release is balancing.
Either do:
[fooIVar release];
(Assuming @synthesize foo = fooIVar;)
Or:
self.foo = nil;
A: The code should read:
[fileName release]
I get the same error if I add self.
Also do not forget to add
[super dealloc];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: sorting by a related item with ming on mongodb setup
A TurboGears2 project using ming as an ORM for mongodb. I'm used to working with relational databases and the Django ORM.
question
Ming claims to let to interact with mongodb like it's a relational database and a common thing to do in a relational database is sort a query by a property of a foreign key. With the Django ORM this is expressed with double underscores like so: MyModel.objects.all().order_by('user__username')
Is there an equivalent for this in ming?
A: I have never used ming, but they seem to have a sort method that you can add to a query, check it out here, not much in the form of documentation
I use mongoengine, it has great documentation and its very similar to the django ORM
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery datepicker year change when select month, IE7 Our project using JSF1.2, Icefaces 1.8.2, jQuery UI component datepicker (veresion 1.8.14). Problem with IE7 (Firefox is fine). Problem will happen with following sequence: Select a date (for example, couple days befor doday). Note we have set year range from 1991 to 2012. Our business logic is print a document use that date (in code, called dateOfStudy) as title, once done, in the JSF back bean, I clear the calendar inputext date field to null. Now click datepicker icon again, the year corrtly shows 2011, select any previous month (for example go back to Auguest, 2011), problme happend right here: the year will change to 1991, can not keep at 2011.
The problem will not happen if I do not touch that date field (don't do clear, keep the old date). The problem will still appear even I just change the date font to other color via CSS (seems whenever I touch that field, datepicker will messed up). The problem will not happen if you click today once, or close datepicker, open again.
Seems the datepick need some initializtion after I cleared date?
I attached some code. I have trid method/option like setDate, onChangeMonthYear, beforShowDay, can not solve. Any help is appreciated !!
<script type="text/javascript">
var jq = jQuery.noConflict();
jq(document).ready(function() {
jq("[id$=fmv]").live('click', function() {
jq(this).datepicker( {
showOn : 'focus',
changeMonth : true,
changeYear : true,
dateFormat : 'mm/dd/yy',
yearRange : '-20:+1',
showButtonPanel : true,
closeText : 'Close'
}).focus();
});
});
</script>
<ice:inputText id="fmv"
style="background-image:url ('../../../jquery/images/calendar1.png');
background-repeat:no-repeat;background-position:right;"
value="#{pItem.dateOfStudy}"
validator="#{pItem.validate}"
partialSubmit="true"
name="fmv"
valueChangeListener="#{pItem.dateChangeListener}">
</ice:inputText>
A: When backbean clear or change input text in calendar inputText, I think that causes a focus event, and calendar confused under IE7. The reason I am using showOn focus is the code is in a table AJAX display area, so use calendar show on image button not work since the button image will not show when AJAX update comes back (the jQuery calendar will not get called), which force me to use showOn focus. I finally solved this year change problem by adding the following refresh calendar line after the final .focus():
jq(this).datepicker("setDate",jq("[id$=fmv]").datepicker("getDate"));
things working fine now. I am not sure how to make this call only when backbean clean the calendar date, but performance seems ok.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to insert as first element in dictionary? I have a dictionary structure, with multiple key value pairs inside.
myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
My dictionary is used as a data source for some control. In the control's dropdown I see the items are like this:
key1
key2
key3
The order looks identical to my dictionary.
I know Dictionary is not like arrayList - you can get the index or so.
I cannot use sortedDictionary.
Now I need to add one more key value pair to this dictionary at some point of my program and I hope it has the same effect as I do this:
myDict.Add(newKey, newValue);
myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
If I do this, I know newKey will display in my control as first element.
I have an idea to create a tempDict, put each pair in myDict to tempDict, then clear myDict, then add pairs back like this:
myDict.Add(newKey, newValue);
myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
Is there better way than this?
Thanks!
A: You cannot do that with the Dictionary class. It is working in your example because of a quirk in the way the data structure is implemented. The data structure actually stores the entries in temporal order in one array and then uses another array to index into the entry array. Enumerations are based on the entry array. That is why it appears to be ordered in your case. But, if you apply a series of removal and insertion operations you will notice this ordering gets perturbed.
Use KeyCollection instead. It provides O(1) retrieval by both key and index and preserves temporal ordering.
A: Dictionary<K,V> does not have an ordering. Any perceived order maintenance is by chance (and an artifact of a particular implementation including, but not limited to, bucket selection order and count).
These are the approaches (just using the Base Class Libraries BCL) I know about:
*
*Lookup<K,V>
*
*.NET4, immutable, can map keys to multiple values (watch for duplicates during building)
*OrderedDictionary
*
*Old, non-generic, expected Dictionary performance bounds (other two approaches are O(n) for "get(key)/set(key)")
*List<KeyValuePair<K,V>>
*
*.NET2/3 okay, mutable, more legwork, can map keys to multiple values (watch for duplicates in inserts)
Happy coding.
Creating a hash data-structure that maintains insertion order is actually only a slight modification of a standard hash implementation (Ruby hashes now maintain insertion order); however, this was not done in .NET nor, more importantly, is it part of the Dictionary/IDictionary contract.
A: From the MSDN page on Dictionary(TKey, TValue):
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<(Of <(TKey, TValue>)>) structure representing a value and its key. The order in which the items are returned is undefined.
I'm assuming you can't use SortedDictionary because the control depends on your data source being a Dictionary. If the control expects both the Dictionary type and sorted data, the control needs to be modified, because those two criteria contradict each other. You must use a different datatype if you need sorting/ordering functionality. Depending on undefined behavior is asking for trouble.
A: Don't use a dictionary - there is no guarantee the order of the keys won't change when you add further elements. Instead, define a class Pair for your Key-Value-Pairs (look here What is C# analog of C++ std::pair? for an example) and use a List<Pair> for your datasource. The List has an Insert operation you can use to insert new elements anywhere into your list.
A: Dictionary Should not be used to sort objects, it should rather be used to look up objects. i would suggest something else if you want to have it sort the objects too.
If you expand the Dictionary, there are no rule that would stop it from mixing up your List.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Why doesn't object have an overload that accepts IFormatProvider? When converting for instance a decimal to a string, you use the CultureInfo.InvariantCulture and pass it as an IFormatProvider. But why is this overload not in object?
A nice implementation would be:
public virtual string ToString()
{
// yadayada, usual ToString
}
public virtual string ToString(IFormatProvider provider)
{
return ToString();
}
This would cause no harm or benefit to the object class, but objects deriving from it can instead override the overload and it will be a lot easier to call it when you are unsure of the type.
The problem that made me run into this was when I was making a method that would be getting all properties of a class and writing it to xml. As I didn't want to check the type of the object, I just called ToString. But would this have been a decimal, the output would be based on the CurrentCulture of the thread, which is not optimal. The only workaround I can see is changing the CurrentCulture to InvariantCulture and then changing it back to whatever it was before. But that would just be ugly as I would have to write try finally blocks etc.
My current code is:
foreach (var property in typeof(Order).GetProperties(BindingFlags.Public | BindingFlags.Instance).
Where(c => ValidTypes.Contains(c.PropertyType)))
{
var value = property.GetValue(order, null);
if (value != null)
{
writer.WriteElementString(property.Name,
value.ToString());
}
}
But I would want it to be:
foreach (var property in typeof(Order).GetProperties(BindingFlags.Public | BindingFlags.Instance).
Where(c => ValidTypes.Contains(c.PropertyType)))
{
var value = property.GetValue(order, null);
if (value != null)
{
writer.WriteElementString(property.Name,
value.ToString(CultureInfo.InvariantCulture));
}
}
Any benefit of not having this overload on object?
A: Try one of these:
string valueString = XmlConvert.ToString(value);
string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
XmlConvert.ToString() is made for XML, so it will keep things closer to the XML spec, such as using "true" instead of "True". However, it is also more brittle than Convert.ToString(). For example, this will throw an exception because of the UTC time:
XmlConvert.ToString(DateTime.UtcNow)
but this works:
XmlConvert.ToString(DateTime.UtcNow, "o")
A: Try to cast your value to IFormattable:
foreach (var property in typeof(Order).GetProperties(BindingFlags.Public | BindingFlags.Instance).
Where(c => ValidTypes.Contains(c.PropertyType)))
{
var value = property.GetValue(order, null);
if (value != null)
{
var formattable = value as IFormattable;
writer.WriteElementString(property.Name,
formattable == null ? value.ToString() : formattable.ToString(null, CultureInfo.InvariantCulture));
}
}
A: Handy extension method of Peter's solution (modified to test also for IConvertible).
public static string ToInvariantString(this object obj)
{
return obj is IConvertible ? ((IConvertible)obj).ToString(CultureInfo.InvariantCulture)
: obj is IFormattable ? ((IFormattable)obj).ToString(null, CultureInfo.InvariantCulture)
: obj.ToString();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Starting a View from a Service? Already asked a similar question, yet without much luck.
Suppose I have a service and I need a view to pop up above it. In the same time, they both should be intractable, i.e. the user should be able to both click buttons within the view, as well as ones on the service in the background.
Is this in theory possible? If yes, how should I initialize that view?
Thanks!
A: Yes it's possible, what you need to do is call the WindowManager service and add your view via the same.
WindowManager windowManager=(WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout layout=(RelativeLayout) inflater.inflate(R.layout.box,null);
You need a WindowManager.LayoutParams object which should contain the parameters for the layout
windowManager.addView(layout,params);
Well, adds the view
A: What you want is to add a view from your running service instance. This way you can persist the view across all activities - and from anywhere else. See this great example:
http://www.piwai.info/chatheads-basics/
A: Services most definitely can have a user interface: Input methods are an obvious example. See http://developer.android.com/resources/samples/SoftKeyboard/index.html for an example.
A: I guess you are misusing the word "Service".
Service is invisible, Activities are visible.
There are no buttons in an Service!
So you have no choice! You should put both views in one Activity, and I would use a RelativeLayout and set the visibility of your chidren to GONE/Visible.
http://developer.android.com/reference/android/widget/RelativeLayout.html
Also using a popup and making the layout under it clickable will disturb the user. You are completely changing User experience. I strongly suggest too make your popup appear at the top/bottom of your initial layout
A: Services run in the background and do not have an UI. So you can not show something over a Service.
If you need a Service to notify user about something, then use Notification.
Ayou could use a Toast, but I advise against it, as it can confuse users since it can pop-out over another app's activity.
A: What you want is an Activity instead of a Service and a Dialog instead View. I suggest you read this document by google: http://developer.android.com/guide/topics/fundamentals.html
However to answer your question about both being interactable. This isn't possible. At any given time 1 and only 1 activity is on the top of the activity stack. The user can only interact with that activity. If you want something like a floating window then will have to create it yourself. Although keep in mind that goes against the android design principles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: c++: Passing const int to template function I am using the rapidxml lib.
It defines a function to parse files in this way:
template<int Flags>
void parse(Ch *text)
The lib provides const int flags for example:
const int parse_declaration_node = 0x20;
So I created a pointer to a static int in my class:
const int * parser_mode;
And in the class constructor I assigned it its value:
parser_mode = &rapidxml::parse_declaration_node;
Then when I try to use this const int * as template argument to the parse function:
tree->parse<parser_mode>(file->data());
I get this error message:
error: ‘GpxSectionData::parser_mode’ cannot appear in a
constant-expression
This rest of the statement seems correct since:
tree->parse<0>(file->data());
doesn't produce compilation error...
Could you please tell me what I am missing here?
Thank you!
Thanks to the explanations below I will probably define it out of the class:
So I think this is:
class Myclass {
static const int parser_mode;
[...]
}
static const int Myclass::parser_mode = rapidxml::parse_declaration_node;
A: template<int Flags> void parse(Ch *text) ... const int * parser_mode;
Your template takes an int as a template parameter, but you are passing it an int*. The types int and int* are not the same.
Try tree->parse<rapidxml::parse_declaration_node>(file->data());
A: You cannot use variable for value of template parameter.
Instead you can add Flags template parameter to your class
template<int Flags>
class CClass {
//...
};
And set Flags parameter for class instance
CClass<rapidxml::parse_declaration_node> obj;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Focus input box when a div is clicked I have an input inside a div element (id = "edit). I was wondering how, onclick of the div area, I could activate the cursor in the input field.
A: You could use a <label for="edit"> element. That would focus the <input> element when clicked.
A: $("#myDiv").click( function() {
$("#myTextField").focus();
});
A: $('#edit').click(function() {
$(this).find('input').focus()
})
A: use .focus() function like this:
$('#yourDiv').click(function() {
$('#yourInput').focus();
});
A: use .attr() to add and removeAttr() to remove attribute "disabled" for the text box on the event click on the div.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need some HTML element with HTMLAgilityPack in C# - how to do it? I have the following scenario:
<a href="test.com">Some text <b>is bolded</b> some is <b>not</b></a>
Now, how do I get the "test.com" part and the anchor of the text, without having the bolded parts?
A: Assuming the following markup:
<html>
<head>
<title>Test</title>
</head>
<body>
<a href="test.com">Some text <b>is bolded</b> some is <b>not</b></a>
</body>
</html>
You could perform the following:
class Program
{
static void Main()
{
var doc = new HtmlDocument();
doc.Load("test.html");
var anchor = doc.DocumentNode.SelectSingleNode("//a");
Console.WriteLine(anchor.Attributes["href"].Value);
Console.WriteLine(anchor.InnerText);
}
}
prints:
test.com
Some text is bolded some is not
Of course you probably wanna adjust your SelectSingleNode XPath selector by providing an unique id or a classname to the anchor you are trying to fetch:
// assuming <a href="test.com" id="foo">Some text <b>is bolded</b> some is <b>not</b></a>
var anchor = doc.GetElementbyId("foo");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IDEs and development tools for Omap 5912 I've got one Omap5912 board and I'm willing to do some coding for practice in my spare time. I did google for some IDEs and dev tools but apart from TI Code Composer Studio I coudn't find anything appealing. Any suggestion?
A: http://chickenfreighter.blogspot.com/2010/05/beginners-omap-l138-arm-tutorial.html here is one tutorial for using OMAP L138 via code composer studio hope so it will help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set up form for a hash in Rails? I have some data associated with a model that is in a hash. The hash is generated in the controller: @hash.
What is the proper way to create a form for this data?
I came up with the following code for the view:
<% @hash.keys.each do |key| %>
<div class="field">
<%= f.label key %><br />
<%= text_field_tag "hash_" + key, @hash[key] %>
</div>
<% end %>
This generates the form, but it creates each hash item as a separate variable in the form. This doesn't seem to be the proper way to submit the data back. I would like to get the data back as a hash, and access it with params[:hash].
What is the best way to do this?
Working in Rails 3.07, Ruby 1.9.2.
Thanks.
EDIT: I should have made this clear. This code is inside of a form generated for a model. So, the form needs to submit all the fields for the model, plus the above hash.
A: My answer is not strictly on topic but I really recommend you to take a look at http://railscasts.com/episodes/219-active-model. You could use ActiveModel APIs to simulate a model object with Rails 3. Doing that you could simply do something like
<%= form_for(@object) %>
and leaving the populating of your object to Rails APIs.
A: Based on this article you should change the name in text_field_tag to
<% @hash.keys.each do |key| %>
<div class="field">
<%= f.label key %><br />
<%= text_field_tag "hash[" + key + "]", @hash[key] %>
</div>
<% end %>
A: When you use the helpers that end with _tag that's what happens.
Instead of text_field_tag ... use f.text_field ....
In order to get a hash like params => {:hash => {:field1 => "", :field2 => ""}} you have to pair up form_for with f.input_field_type instead of simply input_field_tag.
See the difference?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Passing unsigned integers from C++ COM object to VB6 I am trying to access (from a VB6 application) an unsigned 32 bit integer data type returned by the method of a C++ COM object. The part of an interface is declared like:
...
interface ICOMCanvasPixelBuffer : IUnknown
{
HRESULT GetWidth([retval][out] DWORD *pWidth);
HRESULT GetHeight([retval][out] unsigned __int32 *pHeight);
...
When I am browsing this interface using the Object Browser in VB6, it shows Function GetWidth() As <Unsupported variant type> hint for both of these methods.
Is there way to pass the unsigned integer data type to VB6?
A: VB6 does not have unsigned datatypes. Is the COM object yours? Just change the interface to a regular, signed int. Do you really have images with width and height over 2 billion?
If the COM object is not yours, sorry, its interface is not Automation-compliant. You can put together a proxy C++ object that would convert all the unsigned's to int's.
A: Here is an excerpt from Wnidows SDK which is really helpful in understanding which types to use:
enum VARENUM {
VT_EMPTY = 0,
VT_NULL = 1,
VT_I2 = 2,
VT_I4 = 3,
VT_R4 = 4,
VT_R8 = 5,
VT_CY = 6,
VT_DATE = 7,
VT_BSTR = 8,
VT_DISPATCH = 9,
VT_ERROR = 10,
VT_BOOL = 11,
VT_VARIANT = 12,
VT_UNKNOWN = 13,
VT_DECIMAL = 14,
VT_I1 = 16,
VT_UI1 = 17,
VT_UI2 = 18,
VT_UI4 = 19,
// on and on
You will be absolutely safe staying above 16 (with possibly VT_ARRAY | VT_UI1 for byte arrays, which is also common) and this set is flexible enough to cover a lot of scenarios.
In your particluar case you will want VT_I4 which is type LONG.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Uploading a file from a C# desktop application to a PHP script? I am looking to create a desktop application in C# which :
*
*Allows the user to select a file / multiple files / folder containing files from his computer.
*Upload the files selected to a PHP script (which is already equipped to handle file uploads using the $_FILES array.)
I'm a PHP developer and have never coded a single line of .NET before. So, you can assume I have no experience with .NET whatsoever.
I have looked this up online and all I seem to come up with are ASP.NET server side upload controls which i do not want. I'm looking for a client side solution. Also, will i have to make any changes in my PHP script ? The script already handles uploads from an HTML multipart form.
If anyone can help me point in the right direction of where to look, what C# controls are available which can help me create the application I need, I would really appreciate it.
A: The first, and simplest, way to go about this is to use any of the WebClient's UploadFile methods.
Here's some info an an example;
http://msdn.microsoft.com/en-us/library/36s52zhs.aspx
I have a feeling that this will not be enough for you, since you want to upload multiple files in a single request. The WebClient class can be used to manually build a http multipart request, which is probably your best bet.
It's a bit much to explain how to achieve this here on SO, but there are good guides out there.
Here are a couple of very to-the-point articles
http://www.codeproject.com/KB/cs/uploadfileex.aspx
http://www.codeproject.com/KB/IP/multipart_request_C_.aspx
And if you're interested in the details, or better OO design, here's an alternative (a bit harder to follow if you're not experienced with C#)
http://ferozedaud.blogspot.com/2010/03/multipart-form-upload-helper.html
I think both articles should give you enough info to get started.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Concatenating Numbers Together in Oracle APEX using SQL Ok. Here is some background: I have created a simple APEX application that is going to replace a handful of static HTML pages, an Access Database, and LOTS of manual work. Users use the application to submit work requests to my team and upon submission of the form the information is presented back to them in a 'receipt' with a new 'Request #' which they can use kind of like a UPS tracking number to make inquiries of their project. This number is the primary key of the submitted table and is auto-incremented by a sequence. This all works perfectly so far.
My problem is that for auto-incrementing to work, my PK obviously has to be a 'Number'. Again not really a problem. The issue is that prior to migrating to the APEX tool our 'Request #s' were formatted as a string of numbers 8 digits long with the necessary number of zeros (0's) to the left of the actual number. So Request # 789 is actually stored as 00000789 in our Access database. My boss has indicated that this same format needs to be mimicked when the # is displayed in the APEX tool as well since that is what our clients are used to seeing.
I need the Request # to continue to be stored as a Number so that I can continue to auto-increment but I need to find some way to append/concatenate the appropriate number of 0's to the front of the number when it is displayed. This is will likely need to be done with SQL. I am currently using this simple SQL script to display the #:
SELECT req_num
FROM proj_apex
WHERE req_num = (SELECT MAX(req_num) FROM proj_apex)
Thoughts? Any APEX or SQL developers have ideas?
A: select to_char(req_num, '00000009') ...
http://www.techonthenet.com/oracle/functions/to_char.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android - Multiple EditText in single TableRow I have two EditText controls in one TableLayout>TableRow. I have another TableLayout>TableRow that has a single EditText control. When I hit "Enter" or "Next" from the first EditText field, the focus goes to the next table/row instead of the EditText field in the same TableRow. I've searched, but haven't had any luck finding an answer to this. How can I make the focus go to the next EditText field, instead of the EditText field in the next table?
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_width="fill_parent">
<TableRow
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:text="State"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2sp"
android:layout_marginRight="47dp"
android:padding="3dp"
android:textColor="@color/white"
android:textStyle="normal"
android:textSize="12dp">
</TextView>
<EditText
android:layout_height="30sp"
android:id="@+id/addeditServeeDetail_StateTextBox"
android:layout_width="50dp"
android:singleLine="true"
android:textSize="10sp"
android:maxLength="2" android:imeOptions="actionNext">
</EditText>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:text="Zip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2sp"
android:layout_marginRight="5dp"
android:layout_marginLeft="20dp"
android:padding="3dp"
android:textColor="@color/white"
android:textStyle="normal"
android:textSize="12dp">
</TextView>
<EditText
android:layout_height="30sp"
android:id="@+id/addeditServeeDetail_ZipTextBox"
android:layout_width="100dp"
android:singleLine="true"
android:textSize="10sp"
android:maxLength="10">
</EditText>
</TableRow>
</TableLayout>
<TableLayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_width="fill_parent">
<TableRow
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dp"
android:paddingTop="3dp">
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:text="County"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2sp"
android:layout_marginRight="35dp"
android:padding="3dp"
android:textColor="@color/white"
android:textStyle="normal"
android:textSize="12dp">
</TextView>
<EditText
android:layout_height="30sp"
android:id="@+id/addeditServeeDetail_CountyTextBox"
android:layout_width="200dp"
android:singleLine="true"
android:textSize="10sp">
</EditText>
</TableRow>
</TableLayout>
A: If you need the focus to move from item to item in an exact order you need to specify that in the layout file.
See this: http://developer.android.com/guide/topics/ui/ui-events.html#HandlingFocus
android:nextFocusDown="@+id/YourNextEditText"
A: do it manually...:P
place an event which triggers when first edittext loses focus, in that event set focus to second edittext by using edittext.requestFocus() function.
use this event for focus in/out:
editText.setOnFocusChangeListener();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I require that at least one part is imported when using the ImportMany attribute? By default the ImportAttribute requires that exactly one part will satisfy the contract specified in the attribute. This behavior can be modified with the ImportAttribute.AllowDefault property. Essentially this changes the behavior to allow zero or one parts to satisfy the contract. If there are no parts, the default value for that import is used instead.
ImportManyAttribute allows zero or more parts to satisfy the contract. MEF will satisfy this import using an empty collection, or a singleton collection, or a set of parts depending on what it finds.
How do I tell MEF that the empty collection is invalid?
Should I:
*
*Implement IPartImportsSatisfiedNotification and throw an exception from OnImportsSatisfied if the collection is empty?
*Implement my own ImportOneOrMoreAttribute?
*Use some built in functionality of MEF that somehow I am missing?
A: MEF only understands three cardinalities by default: ZeroOrOne, ExactlyOne, or ZeroOrMore. See ImportCardinality. So you cannot express it yourself within the constraints of the MEF attributes. I would not suggest throwing exceptions in OnImportsSatisfied because you will likely run into other unpredictable issues.
I'm afraid the best you can do is ImportMany and verify it in the context of when you would use these imports.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make a class template argument optional? Is there any way to make a template class argument optional?
Specifically in this example:
template <typename EVT>
class Event : public EventBase {
public:
void raise(EVT data){
someFunctionCall(data);
}
}
I want to have a version of the same template equivalent to this:
class Event : public EventBase {
public:
void raise(){
someFunctionCall();
}
}
But I don't want to duplicate all the code. Is it possible?
A: With default template argument, and template specialization :
template <typename EVT=void>
class Event : public EventBase {
public:
void raise(EVT data){
someFunctionCall(data);
}
};
template <>
class Event<void> : public EventBase {
public:
void raise(){
someFunctionCall();
}
};
However, I don't see how would the EventBase look like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google Maps V3: Marker Images displayed in incorrect position after map drag and zoom I'm adding a collection of markers to a map in the v3 api. Everything works fine, but when I drag the map (enough so the markers are off the screen), zoom in, and then drag the map back to the original center, the marker images are offset by roughly the distance I dragged the map. They're still arranged in the correct shape, just moved.
A few other notes:
*
*The marker images don't move if I drag and don't zoom in, or if I drag and zoom out.
*If I just zoom in on the map until the markers are off the screen, the same thing happens
*Polylines do not move (i.e., they retain their correct position no matter what)
*In Firefox, marker images move (or rather, stay in their same pixel position and don't move with the coordinates point on the map) whenever i zoom in on a point other than map center
Here's the code I'm using the add markers:
var bounds = new google.maps.LatLngBounds;
for (i=0, len=points.length; i<len; i++) {
var myPoint = points[i];
var myLatLng = new google.maps.LatLng(myPoint.lat, myPoint.lng);
var markerImage = new google.maps.MarkerImage(
'http://www.mysite.com/images/marker.png',
new google.maps.Size(21,21), // size
new google.maps.Point(0,0), // origin
new google.maps.Point(10,10), // anchor
new google.maps.Size(21,21) // scale
);
var markerOptions = {};
markerOptions.map = this.map;
markerOptions.position = myLatLng;
markerOptions.icon = markerImage;
markerOptions.draggable = true;
this.markers[i] = new google.maps.Marker(markerOptions);
bounds.extend(myLatLng);
}
It's like the pane for the markers is disconnected from the pane for the map and polylines. Is there something I can do differently when adding the markers so the images retain their correct display position? This wasn't a problem in V2.
A: I'm fired.
Just after the block of code in the example, I had
if (init) {
//a bunch of stuff, PLUS
this.map.fitBounds(bounds);
} else {
//a bunch of other stuff, BUT NO fitBounds
}
so, adding
this.map.fitBounds(bounds);
in both logic paths fixed the problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: regex match urls NOT containing given set of strings I need to match all urls that DO NOT contain either /admin/ or ?page=.
I'll be using this as a redirect rule in an iirf.ini file (supports htaccess syntax).
How can I accomplish this?
A: Use a negative look-ahead (?!...) with a regex OR (a|b):
^(?!.*(/admin/|\?page=))
This is saying that when positioned at the start (^) the input should contain either of your two test strings
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Android viewflow validation Currently I have a few forms using this horizontal sliding view.
https://github.com/pakerfeldt/android-viewflow
Is their a way to prevent the user from sliding to the next screen when the form is filled in incorrectly? e.g. disable the horizontal scroll.
A: Yes, change this portion of your copy of the ViewFlow
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
....
case MotionEvent.ACTION_MOVE:
//Add an if / else here that validates your input.
//If it is incorrect don't let the rest of the code that is here do the scrolling.
A: I had the same problem, just added a Boolean variable and a setter and getter:
...
public class ViewFlow extends AdapterView<Adapter> {
private Boolean flagAllowScroll = false;
//the rest of the code
...
public Boolean getFlagAllowScroll() {
return flagAllowScroll;
}
public void setFlagAllowScroll(Boolean flagAllowScroll) {
this.flagAllowScroll = flagAllowScroll;
}
And the put it on the onTouchEvent function
...
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!getFlagAllowScroll())
return false;
//the rest of the code
...
And other in the onInterceptTouchEvent function
...
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!getFlagAllowScroll())
return false;
//the rest of the code
...
And change it of this way:
...
//Allows changes
viewFlow.setFlagAllowScroll(true);
...
//Doesn't Allows changes
viewFlow.setFlagAllowScroll(false);
...
I hope this works for you =)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: SIP deregistration using PJSIP In our app, we need to de-reg a user when he pushes the app to the background.
We are using PJSIP. My applicationDidEnterBackground:
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"did enter background");
__block UIBackgroundTaskIdentifier bgTask;
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self deregis];
[application endBackgroundTask: bgTask]; //End the task so the system knows that you are done with what you need to perform
bgTask = UIBackgroundTaskInvalid; //Invalidate the background_task
NSLog(@"\n\nRunning in the background!\n\n");
});
}
The deregis method is as below:
- (void)deregis {
if (!pj_thread_is_registered())
{
pj_thread_register("ipjsua", a_thread_desc, &a_thread);
}
dereg();
}
And the de-reg method is as below:
void dereg()
{
int i;
for (i=0; i<(int)pjsua_acc_get_count(); ++i) {
if (!pjsua_acc_is_valid(i))
pjsua_buddy_del(i);
pjsua_acc_set_registration(i, PJ_FALSE);
}
}
When we push the app to the background, the dereg gets called. But when the server sends back a 401 challenge, the stack isn't sending back the auth details in SIP call until I bring the application back to foreground.
Does anyone have any idea why this is happening?
Thanks,
Hetal
A: You don't want to end the background task in your background thread:
e.g.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self deregis];
// don't do below...
// [application endBackgroundTask: bgTask]; //End the task so the system knows that you are done with what you need to perform
// bgTask = UIBackgroundTaskInvalid; //Invalidate the background_task
NSLog(@"\n\nRunning in the background!\n\n");
});
You want to end the background task when the registration is updated. So you need to hook into the pjsua on_reg_state callback.
e.g. this example may only assume one unregister, for multiple accounts you have to wait until all are unregistered
-(void) regStateChanged: (bool)unregistered {
if (unregistered && bgTask != UIBackgroundTaskInvalid) {
[application endBackgroundTask: bgTask]; //End the task so the system knows that you are done with what you need to perform
bgTask = UIBackgroundTaskInvalid; //Invalidate the background_task
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I construct a connectstring given all the parameters? In C#, how do I manually build a proper connection string? I have the server name, database name, user name, and password. This is a SQL Server database and .NET 4.0.
I looked at the SQLConnectionStringBuilder and that appears to be what I want but I don't know how to specify the server.
A: On the SqlConnectionStringBuilder use the DataSource property for the server host name/ip address.
A: Have a look at the examples at MSDN:
MSDN - SqlConnectionStringBuilder Class
The line of code in question:
builder["Server"] = yourServerName;
A: Your looking for the DataSource Property
Although you could just set the ConnectionString to something like
Data Source =myServerAddress; Initial Catalog =myDataBase; User Id =myUsername; Password =myPassword;
For alternative connection string for SQL Server 2008 see
http://www.connectionstrings.com/sql-server-2008#p1
A: You're right : SqlConnectionStringBuilder is the way to go. The DataSource property is the server name. You can find more info about this class on the msdn library. One easy way to figure out what properties you have to set may be to initialize a SqlConnectionStringBuilder using an existing connection string and seeing which properties are used.
For instance, it's likely that you'll use IntialCatalog (the name of the database you want to connect to).
A: I suggest taking a look at connectionstrings.com.
You can use the SQLConnectionStringBuilder constructor overload that takes a connectionstring as described in the above site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simultaneously bluetooth remote (android) and run program I'm a student on a hogeschool in the Netherlands. We're working with the LEGO Mindstorms NXT for a project.
However, I'm using my phone (minddroid and other applications) to drive the NXT, but I don't know how to simultaneously run a program.
For example, I drive it over a black line with the remote, and because the program is running, the sensor sees in the program that if it drives over a black line, it has to stop.
A: Is your question how to get the NXT to both communicate on bluetooth and monitor the line at the same time? If so:
Then there are two general solutions:
Main Loop
In your main loop, first check for communications from the bluetooth system, and then check the sensor to see if the black line is detected. Then repeat.
Interrupt
In this solution, the main process would handle communications with the Android phone. The line sensor would be setup to cause a program interrupt when it detects the black line.
The interrupt service routine (ISR) would either set a flag to indicate that the robot should stop or would directly stop the robot.
Choosing which of the above solutions you choose is often dependent on the features of your operating system.
PS It could also be that I'm not understanding your question correctly. In that case, never mind...
A: No I meant that I wanted to run a program simultaneously with the bluetooth remote.
But I solved it, I connected the nxt with a mobile app, so I could only send direct commands. I solved it by connecting with the program, not the nxt robot.
Thanks anyway!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Draw Network in R (control edge thickness plus non-overlapping edges) I need to draw a network with 5 nodes and 20 directed edges (an edge connecting each 2 nodes) using R, but I need two features to exist:
*
*To be able to control the thickness of each edge.
*The edges not to be overlapping (i.e.,the edge form A to B is not drawn over the edge from B to A)
I've spent hours looking for a solution, and tried many packages, but there's always a problem.
Can anybody suggest a solution please and provide a complete example as possible?
Many Thanks in advance.
A: If it is ok for the lines to be curved then I know two ways. First I create an edgelist:
Edges <- data.frame(
from = rep(1:5,each=5),
to = rep(1:5,times=5),
thickness = abs(rnorm(25)))
Edges <- subset(Edges,from!=to)
This contains the node of origin at the first column, node of destination at the second and weight at the third. You can use my pacake qgraph to plot a weighted graph using this. By default the edges are curved if there are multiple edges between two nodes:
library("qgraph")
qgraph(Edges,esize=5,gray=TRUE)
However this package is not really intended for this purpose and you can't change the edge colors (yet, working on it:) ). You can only make all edges black with a small trick:
qgraph(Edges,esize=5,gray=TRUE,minimum=0,cut=.Machine$double.xmin)
For more control you can use the igraph package. First we make the graph:
library("igraph")
g <- graph.edgelist(as.matrix(Edges[,-3]))
Note the conversion to matrix and subtracting one because the first node is 0. Next we define the layout:
l <- layout.fruchterman.reingold(g)
Now we can change some of the edge parameters with the E()function:
# Define edge widths:
E(g)$width <- Edges$thickness * 5
# Define arrow widths:
E(g)$arrow.width <- Edges$thickness * 5
# Make edges curved:
E(g)$curved <- 0.2
And finally plot the graph:
plot(g,layout=l)
A: While not an R answer specifically, I would recommend using Cytoscape to generate the network.
You can automate it using a RCytoscape.
http://bioconductor.org/packages/release/bioc/html/RCytoscape.html
A: The package informatively named 'network' can draw directed networks fairly well, and handle your issues.
ex.net <- rbind(c(0, 1, 1, 1), c(1, 0, 0, 1), c(0, 0, 0, 1), c(1, 0, 1, 0))
plot(network(ex.net), usecurve = T, edge.curve = 0.00001,
edge.lwd = c(4, rep(1, 7)))
The edge.curve argument, if set very low and combined with usecurve=T, separates the edges, although there might be a more direct way of doing this, and edge.lwd can take a vector as its argument for different sizes.
It's not always the prettiest result, I admit. But it's fairly easy to get decent looking network plots that can be customized in a number of different ways (see ?network.plot).
A: The 'non overlapping' constraint on edges is the big problem here. First, your network has to be 'planar' otherwise it's impossible in 2-dimensions (you cant connect three houses to gas, electric, phone company buildings without crossovers).
I think an algorithm for planar graph layout essentially solves the 4-colour problem. Have fun with that. Heuristics exist, search for planar graph layout, and force-directed, and read Planar Graph Layouts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: strtotime question This should be a simple fix;
I currently have a calendar for selecting a range of date:
http://protekco.com/index.php/en/reservations/1718-carvelle-drive-westpalm-beach.html
When the dates are selected in the calendar, it populates 2 input fields for Check in and Check out dates. The problem is, the calendar initially was set 1 day late, so Thursday Sept 22 actually showed as a Thursday Sept 21. I was able to just echo a +1 on the day count, but the input boxes still show the erroneous date. Essentially, I'm trying to add the same +1, but because the date is returned as yyyy/mm/dd, +1 doesn't do much.
Here is the code:
$listsFrom = $this->lists['from'];
$selectedFrom = $listsFrom ? strtotime($listsFrom) : 0;
$listsTo = $this->lists['to'];
$selectedTo = $listsTo ? strtotime($listsTo) : $selectedFrom;
if ($selectedTo) {
ADocument::addDomreadyEvent('Calendars.checkOut = ' . $selectedTo . ';');
}
if ($selectedFrom) {
ADocument::addDomreadyEvent('Calendars.checkIn = ' . $selectedFrom . ';');
}
$listOperation = $this->lists['operation'];
ADocument::addDomreadyEvent('Calendars.operation = ' . $listOperation . ';');
Any ideas?
Thank you!
Edit:
<td class="<?php echo implode(' ', $class); ?>" <?php if ($canReserveBox) { ?> id="day<?php echo $firstDay->Uts+84600000; ?>" onclick="Calendars.setCheckDate('day<?php echo $firstDay->Uts+84600000; ?>','<?php echo AHtml::getDateFormat($firstDay->date, ADATE_FORMAT_MYSQL_DATE, 0); ?>','<?php echo AHtml::getDateFormat($firstDay->date, ADATE_FORMAT_NORMAL); ?>')"<?php } ?> >
<span class="date" >
<?php echo AHtml::getDateFormat($firstDay->date, ADATE_FORMAT_NICE_SHORT)+1;
?>
</span>
This is what actually calls the changes. The + 84600000 is my addition, it doesn't seem to do much tho.
A: If the date is in yyyy/mm/dd format, first use strtotime() to convert it to a timestamp, and then you can use it again to add one day.
$date = '2011/06/01';
$ts = strtotime('+24 hours', strtotime($date));
$date = date('Y/m/d', $ts);
That is just one possible solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I do test-driven development using Vaadin? What's the best way to structure a Vaadin-based application so that I can use TDD (test-driven development) to create the application? In other words, I don't want to write tests that require a server or browser (or even simulators of those) as those might be too brittle, too slow, or both.
The question Translating GWT MVP Pattern to Vaadin is somewhat related in that I'm looking for the correct pattern to use to make my UI "logic" as testable as possible, but I'm not sure that MVP translates to the world of Vaadin.
A: Look at the Model View Presenter pattern, also known as the “humble view”.
If done correctly the View is the only object that you can't test, and as it does not contain any logic, you can simply not bother to test it.
A: I've only just started using Vaadin, and "Can I do TDD with Vaadin?" was my first consideration. I have found (so far anyway) that it is actually quite easy; though I do end up writing a lot of code.
The first thing I had to do was write a number of factory classes. This is so that I can inject mock UI objects into my classes. For example:
public class ButtonFactory {
public Button create() {
return new Button();
}
public Button create(String caption) {
return new Button(caption);
}
public Button create(String caption, Button.ClickListener listener) {
return new Button(caption, listener);
}
}
I then created factories for the main UI components that I needed:
@ApplicationScoped
public class SiteAdminButtonBarFactory implements Serializable {
private static final long serialVersionUID = -462493589568567794L;
private ButtonFactory buttonFactory = null;
private HorizontalLayoutFactory horizontalLayoutFactory = null;
public SiteAdminButtonBarFactory() {}
@Inject
public SiteAdminButtonBarFactory(HorizontalLayoutFactory horizontalLayoutFactory, ButtonFactory buttonFactory) {
this.horizontalLayoutFactory = horizontalLayoutFactory;
this.buttonFactory = buttonFactory;
}
public SiteAdminButtonBar create() {
HorizontalLayout layout = horizontalLayoutFactory.create();
layout.addComponent(addButton());
layout.addComponent(removeButton());
layout.addComponent(editButton());
return new SiteAdminButtonBar(layout);
}
private Button addButton() {
return buttonFactory.create("Add");
}
private Button removeButton() {
return buttonFactory.create("Remove");
}
private Button editButton() {
return buttonFactory.create("Edit");
}
}
The associated test code is:
public class SiteAdminButtonBarFactoryTest {
private HorizontalLayout horizontalLayout = null;
private HorizontalLayoutFactory horizontalLayoutFactory = null;
private Button addButton = null;
private Button removeButton = null;
private Button editButton = null;
private ButtonFactory buttonFactory = null;
private SiteAdminButtonBarFactory siteAdminButtonBarFactory = null;
@Test
public void shouldCreateAHorizontalLayout() throws Exception {
givenWeHaveAFullyConfiguredSiteAdminButtonBarFactory();
SiteAdminButtonBar siteAdminButtonBar = siteAdminButtonBarFactory.create();
assertThat(siteAdminButtonBar, is(notNullValue()));
verify(horizontalLayoutFactory).create();
}
@Test
public void shouldContainAnADDButton() throws Exception {
givenWeHaveAFullyConfiguredSiteAdminButtonBarFactory();
siteAdminButtonBarFactory.create();
verify(buttonFactory).create("Remove");
verify(horizontalLayout).addComponent(removeButton);
}
@Test
public void shouldContainARemoveButton() throws Exception {
givenWeHaveAFullyConfiguredSiteAdminButtonBarFactory();
siteAdminButtonBarFactory.create();
verify(buttonFactory).create("Edit");
verify(horizontalLayout).addComponent(editButton);
}
@Test
public void shouldContainAnEditButton() throws Exception {
givenWeHaveAFullyConfiguredSiteAdminButtonBarFactory();
siteAdminButtonBarFactory.create();
verify(buttonFactory).create("Add");
verify(horizontalLayout).addComponent(addButton);
}
private void givenWeHaveAFullyConfiguredSiteAdminButtonBarFactory() {
horizontalLayout = mock(HorizontalLayout.class);
horizontalLayoutFactory = mock(HorizontalLayoutFactory.class);
when(horizontalLayoutFactory.create()).thenReturn(horizontalLayout);
addButton = mock(Button.class);
removeButton = mock(Button.class);
editButton = mock(Button.class);
buttonFactory = mock(ButtonFactory.class);
when(buttonFactory.create("Add")).thenReturn(addButton);
when(buttonFactory.create("Remove")).thenReturn(removeButton);
when(buttonFactory.create("Edit")).thenReturn(editButton);
siteAdminButtonBarFactory = new SiteAdminButtonBarFactory(horizontalLayoutFactory, buttonFactory);
}
}
I'll admit that at first I had to write the code first and then the test until I figured out how to structure things. Also, I haven't yet got as far as TDDing the event listeners etc (you'll notice that the button have captions, but no action listeners). But I'm getting there!
A: Once Vaadin is a web-framework based on UI, you can choice a solution of tests based on acceptance-tests, like Selenium. So, you still can use test-driven development in your business/model layer that should be totally isolated from your UI classes.
UI is a thing you can touch, you can change it and see in the moment the modifications, you can in real-time accept the behaviour and with some good tools, automatize that.
Business/model is a critical layer, you need to improve the API design for a good understand and business translate to the code. For any change, you need be safe its don't broke your rules - and to do that, just using unit tests (TDD is totally applied here, but not mandatory)
A: Model View Presenter pattern is actually good and recommended way to divide the presentation logic of Vaadin applications. It is even part of the official Advanced Vaadin Training course. Here is the example of implementation of MVP in Vaadin. However, depending on the concrete application, various versions of MVP can be used.
The ideal state is that testable presenter contains as much logic as possible and the view is as much passive as possible. For the testing of actual view, it is preferrable to use Web Tests to test from the users point of view. Vaadin provides a special tool for that - Vaadin TestBench, which is based on Selenium Webdriver and is modified to Vaadin Environment. TestBench has some advantages ofer plain selenium such as vaadin adjusted wait for ajax actions and advanced screenshot comparison. This should be combined with some kind of Selenium Grid, such as SauceLabs, which provides wide range of combinations of OS, web browsers andtheir versions, which can be used in your tests.
Note that Vaadin TestBench is not free and requires a license or Vaadin pro subscription.
A: You can use the karibu-testing framework: https://github.com/mvysny/karibu-testing . It allows you to run and test your app using actual full-blown Vaadin components, so you don't have to use MVP nor custom component factories to construct special UI for testing. Please see the link above on concrete examples and tutorials on how to write and run Vaadin unit tests for your app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Relationship between Service and Handler So, originally, I was pushing intents that needed to be sent across my application at regular intervals using a Service and a TimerTask. After reading the article at http://developer.android.com/resources/articles/timed-ui-updates.html it seemed that this would be the better approach. So, now, my Service creates a handler and sends it on its way. As in the article, my Handler postDelayed()'s itself, making it effectively run indefinitely (until the widget is removed, in which case I clear the handler, thus terminating execution).
My issue is, I know that Services can be eaten by Android for memory in the event that the user needs it. My Handler is a member variable of my Service. Say, for instance, Android eats my service, and then restarts it later on. That, as far as I understand, is a new instance of my Service, and so a new Handler will be instantiated and sent on its way. Aren't there now two handlers running? Or does the old handler get garbage collected (I'd think not because it has to be referenced somewhere else if it's still active)? Or does the first handler somehow get shut down automatically? I don't want 8 of these things running at the same time.
A: Handler is part of the Thread and Thread is part of Process. When OS kills a Serivce it purges the whole process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Inlining an overloaded operator c++ Can/should an overloaded operator have to be inlined to gain better efficiency (wrt time or whatever) if that operator will have to be used frequently?
I want to overload the '+' operator to add big vectors very frequently in my code. Hence the question.
A: Ideally, you'd profile your code and then decide what to inline. There really isn't much of a difference between when you decide to inline regular operators, over overloaded ones.
A: If you are adding big vectors, then the overhead of a function call to the plus will be small relative to the time to actually add the two vectors. So marking the operator+ inline is not likely to improve your overall run time.
A: Let the compiler to decide about optimization.
The keyword inline is misleading: the compiler can -in fact- always do what it needs, just like with the old auto (do you remenber those days?) and register.
It's modern meaning is "defined in header: discard if not used, merge if seen more times".
A: The compiler should inline smallish functions for you automatically in release builds.
Much more important is to define a move constructor and move assignment. If your arrays are very large and you're doing multiple operations at the same time, you can also use expression classes to improve execution speed.
template <class left, class right>
struct AddExpr {
const left& _left;
const right& _right;
AddExpr(const left& Left, const right& Right)
:_left(Left), _right(Right)
{assert(left.count() == right.count());}
int count() const {return _left.count();}
int operator[](int index) const {return _left[i]+_right[i];}
};
class Array {
int* data;
int size;
int count() const {return size;}
Array& operator=(AddExpr expr) {
for(int i=0; i<expr.count(); ++i)
data[i] = expr[i];
};
AddExpr operator+(const Array& lhs, const Array& rhs)
{return AddExpr<Array, Array>(lhs, rhs);}
AddExpr operator+(const Array& lhs, const Expr& rhs)
{return AddExpr<Array, Expr>(lhs, rhs);}
AddExpr operator+(const Expr& lhs, const Array& rhs)
{return AddExpr<Expr, Array>(lhs, rhs);}
AddExpr operator+(const Expr& lhs, const Expr& rhs)
{return AddExpr<Expr, Expr>(lhs, rhs);}
int main() {
Array a, b, c, d;
Array c = (a+b) + (c+d); //awesome on lines like this
}
This removes all the temporary objects, and greatly improves cache efficiency. But I've completely forgotten what this technique is called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: UNIX run program within another program I am trying to execute a program from within a C program (inside UNIX).
I have been given an executable ( the program requires a string input during execution and writes that input to another file called sample ) called exec and I want to execute it in program.c, but giving the string input through indirection.
For that I created a file as follows:
% vim input
I wrote the following inside the input file
content
Now in program.c,
#include<unistd.h>
int main()
{
const char* command = "./exec < input";
execvp(command, NULL);
return 0;
}
When I run the program, the content is not entered into the sample file.
But when I run it without indirection, i.e.
const char* command = "./exec";
then it works, and input entered in saved in sample file.
Can someone please tell what am I doing wrong in the indirection syntax.
Thanks.
A: The syntax you are using is supposed to be interpreted by a shell like bash, csh, ksh, etc.
The system call execvp only expects the path to the executable and a number of arguments, the shell is not invoked there.
To perform redirection in this manner, you'll have to use the dup2(2) system call before calling execvp:
int fd = open("input", O_RDONLY);
/* redirect standard input to the opened file */
dup2(fd, 0);
execvp("/path/to/exec", ...);
Of course, you'll need some additional error checking in a real-world program.
A: You can't do redirection like that with execvp. Use system() or start getting friendly with dup() and friends. You might google 'implementing redirection'.. you'll likely turn up plenty of examples of how shells (for example) handle this problem.
A: The exec(3) family of functions does not know anything about input redirection or parsing command lines: it tries to execute exactly the executable you give it. It's trying to search for an executable file with the name "./exec < input", which unsurprisingly does not exist.
One solution would be to use the system(3) function instead of exec. system invokes the user's shell (such as /bin/bash), which is capable of parsing the command line and doing appropriate redirections. But, system() is not as versatile as exec, so it may or may not be suitable for your needs.
The better solution is to do the input redirection yourself. What you need to do us use open(3) to open the file and dup2(3) to duplicate the file descriptor onto file descriptor 0 (standard input), and then exec the executable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jquery sortable droponempty fix I am working with jQuery's sortable (jQuery ui)
By default dropOnEmpty = true, and as a speedup I'm applying the connectwith after I apply .sortable() to my selectors as follows:
<script type="text/javascript">
$('#selector1').sortable({
over: function(ev,ui){
console.log('Dragging over: '+$j(ui.placeholder).parent().parent().parent().attr('id'));
}
)};
$('#selector2').sortable({
over: function(ev,ui){
console.log('Dragging over: '+$j(ui.placeholder).parent().parent().parent().attr('id'));
}
)};
$('.ui-sortable').sortable('option', connectWith', '.ui-sortable');
</script>
I've demonstrated my logging to try to figure out what's going on - Imagine I first drag from #selector1 to #selector2 (which is empty) - no logging appears, but than if I drag back into the source, I get the logging, and than when I drag back into the target column it works?
The empty selector even has ui-sortable class but it's not connecting!
How should I make sure that even the empty lists while applying the connect-with after initializing the the connectWith separately?
A: http://jsfiddle.net/MMyP3/5/
EDIT: Code as requested:
HTML:
<div id="container" style="display:inline">
<div id="column1" class="column">
<div class="element">Element 1</div>
<div class="element">Element 4</div>
</div>
<div id="column2" class="column">
<div class="element">Element 2</div>
<div class="element">Element 3</div>
</div>
<div id="column3" class="column">
</div>
CSS:
.column{
border: 1px solid #E9EAEA;
border-radius: 5px 5px 5px 5px;
margin: 10px;
min-width:100px;
padding: 5px;
float:left;
width:100px;
}
.element{
border: 1px solid #E9EAEA;
border-radius: 5px 5px 5px 5px;
}
Javascript:
$('.column').sortable({
var $this = $(this);
activate: function(en, ui) {
$this.css('min-height', '100px');
$this.css('background-color', '#666');
},
deactivate: function(en, ui) {
$this.css('min-height', '0px');
$this.css('background-color', '#FFF');
},
placeholder: 'ui-state-highlight'
});
$('.column').sortable('option', 'connectWith', '.column');
Edit: I updated my link, I think the main issue was your html structure which I adjusted, also make sure you are dragging the elements to the top of the empty divs. Just because you are changing the background color and min-height doesn't mean the actual sortable's height is changing. So it may look like you can place the items any where in the open area, in reality you actually can't, unless you define heights for the sortables on the get go.
A: @Jack's explanation of why you can't drop into empty sortables is correct. Sortable caches the positions of its sortables at the beginning of a drag start before any callbacks have been run. So if you change the height of the drop zones in the callback, those are ignored as it still uses cached values.
If you use the Sortable's 'refreshPositions' method just after you adjust the height in your callback, the sortable should now have accurate positioning info so that you can successfully drop in the target zone without having to touch a non-empty sortable list.
$('#sortable').sortable({
start: function (e, ui) {
$('.sortable_drop_zone').css('min-height', '50px');
$('#sortable').sortable('refreshPositions');
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Perforce p4 "describe" command does not list affected files When "p4 describe changelist#" is issued, sometimes the affected files are listed; sometimes they are not and just show:
Affected files ...
Anyone knows why that is?
A: If the changelist only contains shelved files, you will see that behavior. For example:
d:\projects>p4 describe -s 925745
Change 925745 by mark.allender@client-mark.allender on 2011/08/11 07:48:04 *pending*
New SDK
Affected files ...
but since I have files that are shelved, I can use the -S option with describe to see the files that are shelved.
d:\projects>p4 describe -S -s 925745
Change 925745 by mark.allender@client-mark.allender on 2011/08/11 07:48:04 *pending*
New SDK
Shelved files ...
... //path/to/fileA#8 edit
... //path/to/fileB#11 edit
... //path/to/fileC#1 edit
... //path/to/fileD#3 edit
Also, it will display no files if there are indeed no files in the changelist, which might be the case for pending changelists. Notice that the first line of the describe output above says pending, which means that this changelist hasn't been submitted yet. Pending changelists can be empty, contain files, contain files and shelved file, or only shelved files. Depending on that state, the output of 'p4 describe' might not show any files.
A: Most likely explanation: You do not have 'list' rights for the affected files. The docu for p4 protect explains the respective rights.
For example, if you have list, but no read rights, p4 describe will output:
Affected files:
//depot/path/to/file
Difference:
...
Likewise, if the list right is also missing, p4 describe will have the output that you saw. Check with your Perforce admin what the rights are for the respective depot path (let him issue p4 describe for the mentioned checklist :))
A: Another possibility: files or file revisions have been obliterated.
Obliterating can leave submitted changelists that refer to no files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Accessing SQL CE from WP7 Mango error I'm running through the sql access example on the MSDN website (http://msdn.microsoft.com/en-us/library/hh202876(v=VS.92).aspx) and i can't understand why the following code isn't working.
MSDN Example: http://msdn.microsoft.com/en-us/library/hh202876(v=VS.92).aspx
My Code: http://pastebin.com/MxWtGvPw
The Error: The type or namespace name 'ObservableCollection' could not be found (are you missing a using directive or an assembly reference?)
I'm really struggling to get my head around this so if anyone has any pointers, that would be great.
Thanks!
A: You seem to be missing:
using System.Collections.ObjectModel;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does the OSGi framework set the Bundle ID? I am trying to run OSGi framework (Equinox) in a main method.
Each time I start the framework, when I print BundleContext.getBundles().length, it says the framework has only 1 Bundle installed on (that is certainly the system bundle).
When I install my first bundle the bundle ID will continue from the last session. let's say if I had 4 bundles last session (and I have stopped and uninstalled all of them before stopping the system bundle), the first Bundle ID is set 5.
Now, I want to know how does the framework choose the bundle ID? Why and how does the framework remembers the last session, even though I had uninstalled all of the bundles? Is it because of Bundle Cache? And if it is, how can I clear the cache (to restart numbering from 1)?
A: The framework has the last used bundle id somewhere in the persistent store it manages. What this store looks like is a framework implementation detail. When you launch the framework, you can specify the org.osgi.framework.storage.clean framework configuration property. This will clear all installed bundles but I am not sure if it will reset the last used bundle id.
A: Deleting the equinox/org.eclipse.osgi folder resets the numbering. Before the delete make sure that your bundles don't have any important data under this folder.
The bundle command with a valid bundle id can show the absolute path of the equinox/org.eclipse.osgi folder:
osgi> bundle 7
slf4j.api_1.6.1 [7]
Id=7, Status=ACTIVE Data Root=D:\temp\test\equinox\org.eclipse.osgi\bundles\7\data
...
A: Here's what OSGI Core Release 8 specification says about bundle identifiers:
Bundle identifier - A long that is a Framework assigned unique
identifier for the full lifetime of a bundle, even if it is updated
or the Framework is restarted. Its purpose is to distinguish
bundles in a Framework. Bundle identifiers are assigned in
ascending order to bundles when they are installed. The method
getBundleId() returns a bundle's identifier.
So that at tells us two important properties about bundle identifiers: 1.) the relationship between bundleId and bundle is stable from the time that it is installed to the time that it is uninstalled, and 2.) that bundle identifiers are assign in ascending order to when they were installed.
Going back to the original question, trying to get bundles identifier number assignments to start over works against the OSGI specification for bundle identity, and you shouldn't mess around with trying to control bundle identity. For example, let's assume you have three bundles installed:
b1(0), b2(1), b3(2)
Now lets assume you uninstall bundle b2 (with id = 1):
b1(0),b3(2)
Now lets assume you re-install b2:
b1(0),b3(2),b2(3)
Notice that b2 gets a new id assigned to it. That id is stable for referencing b2 as long as b2 is not uninstalled. And if you notice, the id of 1 is no longer used. Bundle id is an identifier, not an index into an array. The bundleId of b3 can't be changed because it wasn't uninstalled, b2 could not be assigned the bundleId of 1, since that would violate the rule the bundle identifiers are assigned in ascending order to when they were installed (the OSGI framework doesn't remember that b2 was previously installed and uninstalled - it looks like its just being installed for the first time). Given that the bundleId is a long, that means we would need to do 9,223,372,036,854,775,807 bundle uninstalls before OSGI's bundle id number assignment scheme would run out of id's.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Combobox's SelectedValue (or SelectedItem) OneWay binding not working. Any ideas? In the below window, the Existing Reports combo is bound to an observeablecollection of reportObjects. I have a reportObject property currentReport bound to the combo's SelectedValue property, OneWay. However, that's not working when bound in XAML.
SelectedValue="{Binding currentReport, Mode=OneWay}"
TwoWay binds fine, but I can't do it that way without writing an undo() method to the reportObject class. I'm binding the currentReport's properties to the various textboxes for editing. I want to bind OneWay so the source doesn't get changed. The currentReport's properties are all TwoWay bound to the corresponding textboxes so when I update the table in SQL [Save], it'll pull from that object, who's data is current.
<TextBox Text="{Binding currentReport.reportName, Mode=TwoWay}"
All of the properties bound from currentReport to the textboxes work fine as well. The only problem is the OneWay binding from the SelectedValue to the currentReport object. Does anyone have any ideas how to get this to work? I saw there was a bug, but the post I saw was 2009.
Sorry about the yellow. Not my idea. =)
EDIT: Added this XAML just in case.
<ComboBox ItemsSource="{Binding reportsCollection}" SelectionChanged="cboReports_SelectionChanged"
DisplayMemberPath="displayName"
SelectedValue="{Binding currentReport, Mode=TwoWay}"
x:Name="cboReports" Width="342" Height="40" VerticalAlignment="Center"/>
A: Forget about you need to change values - that is a separate problem - need to review your data design. Start with the UI problem question. If you want a user to be able to select an item from a combo box then it must have two way binding. Your first question is SelectedValue="{Binding currentReport, Mode=OneWay}" is failing why?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery - Modal dialog seems to be disabling its form fields
Possible Duplicate:
Jquery Modal Dialog disables form elements
I'm using JQuery UI to make a modal dialog, I have the html code in my page set to display:none and the modal is shown on button click, the modal shows fine but all the text fields that I have in it are locked, for some reason. Anyone had this issue?
EDIT:
Here's the code of what I'm doing: http://jsfiddle.net/5Xmmb/1/ here it seems to work. What I meant by locked is that my fields seem to be disabled in my actual code.
A: The z-index of the form is most likely the problem. Try setting it to "auto":
#my_dialog_form {
z-index: auto;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I handle "updates" of content for old users, without affecting new users? The subject was too vague - let me explain:
I have an application in which I include a navigational chart. If someone bought the application in 2011, they got the 2011 version of the navigational chart.
If someone purchases the application in 2012, they will get the 2012 navigational chart.
However - someone who purchased the application in 2011 should be able to upgrade their chart (to the 2012 chart) on a paid basis.
How can I reliably implement this?
Furthermore, if someone purchased the app in 2011, they should not be able to simple unload the application and reload it (from the AppStore) and get the updated chart for free.
This is not as simple as a straight-forward "in-app purchase" - because newer purchasers would already have received the update.
P.S. Before you comment on how I am being unfair to existing users, etc by "penalizing" them - please note that it is not the case. As with any and all navigation charts, purchasing one (either electronic or paper) does not necessarily give you the rights to all future ones for free. Futhermore, I have chart providers which I am required to pay a royalty for the updates.
A: If you want to base this on a single upgradable App, which I think you should, for customer continuity, then you're probably going to need to maintain your own server that manages entitlements based on what has been purchased via In-App purchases, and when.
This process is outlined in Apple's In-App purchase documentation.
A:
Furthermore, if someone purchased the app in 2011, they should not be
able to simple unload the application and reload it (from the
AppStore) and get the updated chart for free.
The suggestions that you need to run your own entitlement server sound like they might be correct, and the most technically robust approach. However, that relies on being able to uniquely identify your users to your server, and as noted by JustSid the UDID is not going to be available to a developer. In any case, the UDID identifies unique devices, while purchases are based on AppleIDs, so I'm not sure that would really work. The most unpalatable part would however be the need to maintain your own server for this, adding complexity, if there is another approach.
This partly depends on your pricing. If the price of a new chart is less than or equal to your current app price, then there is one simple approach you could use, if it is acceptable to you. When the 2012 chart becomes available, ship the app with the 2011 map, reduce the price of the app by the price of the 2012 chart, and make the 2012 chart available as an in-app purchase for all users.
I have no idea what your app costs, but here's an example:
Currently
App with 2011 chart: $10.
2012 chart becomes available
Price of app for new purchasers: $5. (Ships with 2011 chart).
In-app purchase to 2012 chart: $5.
Total: $10
Price of updating app for existing customers: $0.
In-app purchase to 2012 chart: $5.
Total: $5
New customers pay the same total price as before, existing customers get an update at a 50% discount over buying the app outright. If you were going to do this, you would need to make it very clear in the app store that the $5 purchase was for the platform that gave you a legacy chart, and that a $5 in-app purchase was required to get the 2012 chart, as customers are not accustomed to having to make an in-app purchase immediately after purchase of a paid app.
Alternatively, you might not want to distinguish between upgrades and new purchasers. In that case, just set the price of the app with the 2011 chart to $0 in the app store, with a $10 in-app purchase to get the 2012 chart. Personally, I quite like this approach because having downloaded a free app, people will be much more understanding of the need to make an in-app purchase immediately to get full functionality.
This is not as simple as a straight-forward "in-app purchase" -
because newer purchasers would already have received the update.
This is the tricky bit. The scenario I outline above does not exactly give you what you wanted.
I don't claim to have the definitive word on what is possible with in-app purchases, but the only way I can see that you could achieve this is to sell a new app for 2012 purchasers, while offering the 2012 chart as an in-app purchase within the 2011 app for earlier customers. Two apps in the app store. Not sure Apple would like it.
Later
The ideal outcome could be achieved if it was possible to programmatically access the original purchase date of the app for the current user (rather than download date), in the same way that you can get details about in app purchases that have occurred. Then you could just say something like (pseudo code):
if ((purchaseDate > 1-Dec-2011) || (hasPurchased2012ChartInApp == YES)) {
// give access to 2012 charts
}
else {
// only give access to 2011 charts
}
But... I've not been able so far to find a way to get that original purchase date.
A: So is the problem that you have a paid app, rather than one that relies entirely on in-app purchase?
You should be able to give them one free chart purchase. Charge for the next one(s).
A: If you can set the price of the in-app purchase dynamically, you could have it try to restore the users purchases when they first open the app, and if there are no purchases to restore, give them the current purchase for free. This would ensure that only users who have not yet received any content, wether through initial download or in-app purchase, would be able to receive the new map without additional charge.
A way to achieve similar functionality would be to make it a free app (perhaps with demo content) with non-consumable in-app purchases for each chart. In newer updates, you could make it so that you can only buy the new version but can still restore purchases and get the old version that way.
A: You can send a message to your server the first time the user opens the application. Get the device identifier UUID/UDID and post it to your server. I know for the user it might look like your 'stealing' his identity (they say it's a bad thing, but still use google). You can say something like "hey this app will now check if you are allowed to get a free chart" yes/no this would even let them choose not to send the device data.
On the server side you can check if it's a new device and then write the ID in a database or whatever. Now even if the user reload the app and contact the server again you will notice that the id already exist in your DB.
A: For this to work, I am assuming that once 2011 passes, there is no point in getting the 2011 navigational charts (you italicized upgrade in your question, and that's my basis for this assumption) AND you won't be paying any royalty charges for the old maps (I guess it will still work with these charges, but you get less profit, in which case use it as a last resort).
Currently, you're selling the 2011 navigation charts, which comes free when you purchase the app. Once you have the 2012 charts, you will keep the app more or less the same, but you will add the 2012 chart as an in-app purchase for the new version. You will also make the app free once you make that update (at the beginning of 2012) and keep the 2011 charts as a sample (but maybe someone is depending on it, so leave it there; also apple requires that an app be useful once downloaded, and it doesn't require an in-app purchase to be useful).
That way, if someone buys the app in 2011, he doesn't get the 2012 charts for free, unless they upgrade via in-app purchase, in which case, you get your money. He/she also isn't frustrated that the once priced map became free, because it is useless now that 2012 has passed. The person that downloads the app in 2012 for free doesn't get the map for free, he will consider the 2011 charts as a sample, gets impressed (hopefully) and purchase the 2012 ones.
For later years, simply add the 2013 charts, 2014 charts, etc. as in-app purchases and keep the rest the same. You said in a comment, you don't want to leave gaps, so leave the previous maps there. Hope this helps.
A: What I would like to do for this, is mentioned in the following steps:
*
*I would maintain a version information (some date or year only) of the application at server side.
*I would send the update information for calendars via push notifications.
*When the user registers himself for push notifications, I will store the application version along with device UDID and the device tokens in the database. (You can also do this via some web service but I am just suggesting my way).
*So I can always check whether to charge the user or not by the help of user's application version and device UDID information.
*If the user Deletes his app and reloads it and registers himself for push notification again, I will not update his application version information.
I hope it helps.
Thanks,
Madhup
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Android Button subclassing with custom background I've been having this issue and figuring out how to fix it for a few days now, here is my problem:
I have a class called GuiButton, which extends android.widget.Button.
I override the onDraw method to draw my own bitmap as background since i also had
problems getting android to draw (and switch between when pressed) a button background
the way i wanted it with the setBackgroundDrawable() method.
Long story short, whever the button appears on screen, it has a black background the entire
area of the button and on top of that my own button graphic is drawn. This is a problem
since the button has an alpha channel and is transparent in the middle and at the edges and the button is drawn on top of a background that has "slots" for the button, so with the black background auto-drawing, part of this background isnt visible and the button looks ugly.
Here is my draw code, if you need to know anything else please ask and Ill provide.
@Override
public void onDraw(Canvas canvas)
{
// Create a new paint
Paint paint = new Paint();
// Apply the filter flag for when the bitmap gets
// scaled on different screen sizes
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
// Clear the canvas
canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
if(_pressed)
{
canvas.drawBitmap(_pressedBitmap, null, new Rect(0,0,this.getWidth(),this.getHeight()), paint);
}
else
{
canvas.drawBitmap(_normalBitmap, null, new Rect(0,0,this.getWidth(),this.getHeight()), paint);
}
super.onDraw(canvas);
}
Yeah, that fixes the problem of the black background, however it creates a bunch more:
1: The text on the button now gets drawn below the bitmap. Ergo, you can't see it.
2: The background of the button is now ALWAYS the first "background.png" i draw on it.
When I press the button, the "regular"background gets drawn and on top of that the "pressed state" background. However, this looks ugly since they both contain an alpha channel in different positions. This means the "normal button" is still partially visible trough the transparent parts of the "pressed button".
Here is an example (with ugly simplified images to illustrate the problem):
Normal button:
Pressed Button:
As you can see, the normal (blue) button always draws. I also checked the If Else statement in my onDraw method, but it never reaches the draw code for the "normal" button if the button is pressed. So for some reason, the button is still in memory or something :S.
A: You need to make your call to super.onDraw(canvas) the first thing you do, not the last.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with getJSON response I have some problem with $.getJSON response in Chrome
The query is
$.getJSON("http://www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json?callback=?&points=55.77184,37.623553",
function(json){
<some code>
}
);
if you click on this link you'll get an json text.
By when I run this query Chrome shows an error:
Resource interpreted as Script but transferred with MIME type application/json
SyntaxError: Unexpected token : timezone.json:1
Does it try to convert json response to JavaScript object? If it is so why it cann't do that? Is there any way of resolving this problem?
in Chrome debugger I found the file "timezone.json" with this content:
{"code":0,"message":"ok","data":[{"timeZone":"Europe/Moscow","currentOffsetMs":14400000,"latitude":55.77184,"longitude":37.623553}]}
A: The server you are requesting data from is not setup to return JSONP. therefore, you need to build some kind of proxy to get the data for you, or use YQL.
Edit:
If you were to use YQL, this is the url you would use:
http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A%2F%2Fwww.askgeo.com%2Fapi%2F428014%2Fsf2t36ujv1tsf325t5734gstr4%2Ftimezone.json%3Fpoints%3D55.77184%2C37.623553%22&format=json&diagnostics=true
and for information on how I generated that url, visit:
http://developer.yahoo.com/yql/console/#h=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A//www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json%3Fpoints%3D55.77184%2C37.623553%22
You can find the url at the bottom.
Fiddle using YQL: http://jsfiddle.net/JGwU3/1/
there is however one quirk with using YQL. if the result only contains one result, it's contents is an object, however, if it is multiple, its contents will be an array. you can see the difference by console.logging the response.
A: EDIT
OK, my post was wrong, it is a JSONP issue. See this jQuery documentation page on how to retrieve the data from the URL:
http://api.jquery.com/jQuery.ajax/
A: In the API documentation it says, that you should provide the query paramaters in a separate JSON object as the second argument.
$.getJSON('http://www.askgeo.com/api/428014/sf2t36ujv1tsf325t5734gstr4/timezone.json', {'callback':'', 'points': '55.77184,37.623553'}, function(json) {
alert(json.data[0].timeZone);
});
Works fine when I tested it.
(This is totally ignoring JSONP)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails 3.1 Engines Modules When creating a mountable Rails 3.1 engine using
rails plugin new my_engine --mountable
it creates the engine at MyEngine::Engine < Rails::Engine
Is there a way to generate it like the jQuery::Rails engine (Jquery::Rails::Engine), or do I have to do it manually?
I tried these, and of course it didn't work.
rails plugin new "my_module/my_engine" --mountable
rails plugin new "my_module::my_engine" --mountable
A: I took a peek in the rails source, and you won't like the answer. Plugin generation seems to make the assumption that your engine name isn't nested, like here.
If you really insist on not doing this by hand, you could try to hack your way through the generator or use a PluginBuilder with the -b option of the rails plugin new command. It doesn't look documented though, a quick search on Google didn't reveal any info, but I may have overlooked something.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Errors with iOS CLLocationManager class and constants (Xcode 3.2.6, iOS 4) I'm getting errors and build failure in a sample app. Apparently, there's an internal problem with CLLocationManager and its associated constants. I have no idea what's causing it or how to fix it.
I'm working through an Apple developer tutorial for CoreData on iPhone. The tutorial is a walkthrough of how to build an app called "Locations", which maintains a persistent list of the places a user has been. The user can commit his/her current location to the list by pressing a button, at which point the app runs some exemplary managed object logic. A location manager is set up at launch, and it runs continuously during the lifespan of the app.
My build is failing. This is troubling, since I'm entering code that Apple has provided. I'm getting two mysterious errors regarding my use of:
1.) a Core Location constant, kCLLocationAccuracyNearestTenMeters; and
2.) one of the classes, CLLocationManager.
These problems don't seem to originate from errors in my code. I've triple-checked that I'm typing everything correctly and in the proper places, and that I've imported the correct headers where necessary. The error entries in the build results window don't correspond to any line in the program. Instead, the problems appear to lie in .o files and low-level aliases.
Here are the logs from the results window (typed exactly as they appear):
"_kCLLocationAccuracyNearestTenMeters", referenced from:
_kCLLocationAccuracyNearestTenMeters$non_lazy_ptr in RootViewController.o
(maybe you meant: _kCLLocationAccuracyNearestTenMeters$non_lazy_ptr)
"_OBJC_CLASS_$_CLLocationManager", referenced from:
Objc-class-ref-to-CLLocationManager in RootViewController.o
Symbol(s) not found
Collect2: ld returned 1 exit status
Can anyone tell me what the source of the problem is, and what I can do to fix it?
Thanks in advance.
A: You have to add coreLocation framework to your project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring MVC , JSON, @ResponseBody I have a Spring @Controller returning an ArrayList(Brew)to an Android client as JSON. When using @ResponseBody on the method, it works fine. When not using that annotation, I receive an exception in Android. I have compared the JSON payload being returned to Android both ways and they are identical. Does anyone know why I would receive the following exception ONLY when not using @ResponseBody?
Unable to invoke no-args constructor for class [Lcom.androidologist.gb.beans.Brew;. Register an InstanceCreator with Gson for this type may fix this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getting the values from Objects in NSMutableArray (console) As newbie, Im stuck on getting the values from objects I have put in a NSMutableArray. To give a full picture of my problem I would appreciate you reading the following:
(writing to console in Xcode)
Lets say I produce a new object as follows:
Person *player = [[Person alloc] init];
player.age = 10;
player.height = 10;
player.name = @"player";
As I continue to write my programme I can change the above values of player i.e
player.age = 23; etc.....
If I want to create another Person (player2) I repeat the above like this:
Person *player1 = [[Person alloc] init];
player1.age = 13;
player1.height = 4;
player1.name = @"player1";
In my programme I can now change and compare values of the 2 objects i.e.
if (player.age == player1.age) bla bla bla
My problem starts if I want to create 20+ Person objects - I know how to place all the objects in a loop/NSMutableArray as follows:
for (int i = 0; i < 20; i++)
{
Person *player = [[Person alloc] init];
player.age = 10;
player.height = 10;
player.name = @"player";
[myArray addObject:player];
[player release];
}
All the objects in myArray are individual but have the same values. Thats fine ! But how to get or change the objects in myArray ? (not at run time)
If [myArray objectAtIndex:4]; holds the following values:
player.age = 10;
player.height = 10;
player.name = @"player";
how do I get to the object(s) in myArray so I can compare/sort/add etc..
Heres example of what I want to do but I know is wrong:
if (player.age == [myArray personAtIndex:15.age];
or
NSLog(@"@ has a height of %i",[myArray personAtIndex:15:name:height];
prints out>> person has a height of 10
I really would appreciate you helping me on this - As a newbie I'm finding it hard to move on until I get an understanding of this problem. Thank you very much for reading this.
A: You need to study the documentation for NSArray, in particular the objectAtIndex method.
[[(Person*)myArray objectAtIndex:15] age]
Will give you the value you want. I'll break this down:
*
*(Person*) tells the compiler that you expect to get a Person object back
*objectAtIndex returns an object (any object, hence the cast to Person above which prevents the compiler complaining that it might not respond to age) at index 15 of myArray
*age has to be called on the returned object because you can't use dot notation on cast objects
Alternatively, you could do:
Person *aPerson = (Person*)[myArray objectAtIndex:15];
aPerson.age = 15;
Once you have an object of known type you can use dot syntax.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: First image in gallery is stuck Solved
This is now solved: In the tmbLoaded function all I had to do was place the if/else statement after photoBmp and photoBack creation and remove the tween inside the if/else statement. Also, I was advised to not use a global variable for TweenLite because I need not worry about garbage collection using TweenLite.
Original Issue
I'm working with an image gallery and the first image in the transition ends up stuck near the bottom of the file, but the remaining images fly right into place.
I have a sneaking suspicion it may have something to do with my positioning somewhere or with my tweening. I added a global variable thinking it may have something to do with garbage collection causing my tween to partially stop, but that didn't solve the problem. It's just that first image when it transitions onto the stage. After that, everything works perfectly. Even the click transition.
This is part of my final project and given that I get this fixed, everything will finally be working. Everything is built using as3, so you could just copy and paste it, if you'd like. Except, of course, for the xml (which I'll post in a comment), the url button which is imported from the library, and the text format which can be faked with any embedded font and exported as Myriad.
var fileNameArray = new Array();
var urlArray = new Array();
var targetArray:Array = new Array();
var titleArray = new Array();
var descArray = new Array();
var i:Number;
var iTmb:Number = 0;
var imgTween:TweenLite;
var tweenDuration:Number = 0.4;
var tmbTotal:Number;
var dataXML:XML = new XML();
var photoFolder:String = "imgs/png/galleryImgs/";
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.load(new URLRequest("scripts/xml/gallery.xml"));
xmlLoader.addEventListener(Event.COMPLETE, xmlComplete);
var tmbGroup:MovieClip = new MovieClip();
tmbGroup.x = 400;
tmbGroup.y = 165;
addChild(tmbGroup);
var txtFace:Font = new Myriad();
var headingFormat:TextFormat = new TextFormat();
headingFormat.font = txtFace.fontName;
headingFormat.color = 0x0099cc;
headingFormat.size = 14;
headingFormat.align = "left";
headingFormat.bold = true;
var bodyTxt:TextFormat = new TextFormat();
bodyTxt.font = txtFace.fontName;
bodyTxt.color = 0x333333;
bodyTxt.size = 14;
bodyTxt.align = "left";
// Text Fields
var headingTxt = new TextField();
headingTxt.condenseWhite = true;
headingTxt.autoSize = TextFieldAutoSize.LEFT;
headingTxt.selectable = false;
headingTxt.defaultTextFormat = headingFormat;
headingTxt.wordWrap = true;
headingTxt.width = 409;
headingTxt.height = 21;
headingTxt.x = 196;
headingTxt.y = 355;
var urlTxt = new TextField();
urlTxt.condenseWhite = true;
urlTxt.autoSize = TextFieldAutoSize.LEFT;
urlTxt.selectable = false;
urlTxt.defaultTextFormat = bodyTxt;
urlTxt.wordWrap = true;
urlTxt.multiline = true;
urlTxt.width = 490;
urlTxt.height = 21;
urlTxt.x = 196;
urlTxt.y = 375;
var descTxt = new TextField();
descTxt.condenseWhite = true;
descTxt.autoSize = TextFieldAutoSize.LEFT;
descTxt.selectable = false;
descTxt.defaultTextFormat = bodyTxt;
descTxt.wordWrap = true;
descTxt.multiline = true;
descTxt.width = 490;
descTxt.height = 150;
descTxt.x = 196;
descTxt.y = 401;
var urlTxtTarget = new TextField();
urlTxtTarget.condenseWhite = true;
urlTxtTarget.autoSize = TextFieldAutoSize.LEFT;
urlTxtTarget.selectable = false;
urlTxtTarget.defaultTextFormat = bodyTxt;
urlTxtTarget.wordWrap = true;
urlTxtTarget.multiline = true;
urlTxtTarget.width = 490;
urlTxtTarget.height = 21;
urlTxtTarget.x = 196;
urlTxtTarget.y = 5000;
var urlBtn:URLBtn = new URLBtn();
urlBtn.x = 196;
urlBtn.y = 375;
addChild(headingTxt);
addChild(urlTxt);
addChild(descTxt);
addChild(urlTxtTarget);
addChild(urlBtn);
urlBtn.visible = false;
function xmlComplete(e:Event):void {
dataXML = XML(e.target.data);
tmbTotal = dataXML.thumbnail.length();
for( i = 0; i < tmbTotal; i++ ) {
fileNameArray.push( dataXML.thumbnail[i].@filename.toString() );
urlArray.push( dataXML.thumbnail[i].@url.toString() );
targetArray.push( dataXML.thumbnail[i].@target.toString() );
titleArray.push( dataXML.thumbnail[i].@title.toString() );
descArray.push( dataXML.thumbnail[i].@description.toString() );
}
generateTmbs();
}
function generateTmbs():void {
var tmbRequest:URLRequest = new URLRequest( photoFolder + fileNameArray[iTmb] );
var tmbLoader:Loader = new Loader();
tmbLoader.load(tmbRequest);
tmbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, tmbLoaded, false, 0, true);
iTmb++;
}
function tmbLoaded(e:Event):void {
if( iTmb < tmbTotal ) {
generateTmbs();
descTxt.text = "Loading " + iTmb + " of " + tmbTotal + " gallery images.";
} else {
headingTxt.text = titleArray[0];
descTxt.text = descArray[0];
urlTxt.text = urlArray[0];
urlTxtTarget.text = targetArray[0];
var photoContainer:MovieClip = MovieClip( tmbGroup.getChildAt(tmbTotal-2) );
photoContainer.addEventListener( MouseEvent.CLICK, transitionOut, false, 0, true );
imgTween = new TweenLite(photoContainer, tweenDuration, {rotation:0,
ease:Expo.easeInOut});
urlBtn.visible = true;
urlBtn.addEventListener(MouseEvent.CLICK, goto_URL, false, 0, true);
}
var photoBmp:Bitmap = new Bitmap();
var photoBack:MovieClip = new MovieClip();
photoBmp = Bitmap(e.target.content);
photoBmp.x = - photoBmp.width * 0.5;
photoBmp.y = - photoBmp.height * 0.5;
photoBmp.smoothing = true;
var photoBGWidth = photoBmp.width + 16;
var photoBGHeight = photoBmp.height + 16;
photoBack.addChild(photoBmp);
photoBack.graphics.lineStyle(1, 0x999999);
photoBack.graphics.beginFill(0xFFFFFF);
photoBack.graphics.drawRect( - photoBGWidth * 0.5, - photoBGHeight * 0.5, photoBGWidth, photoBGHeight );
photoBack.graphics.endFill();
photoBack.x = 200;
photoBack.y = 365;
photoBack.rotation = 45;
photoBack.name = "gallery " + tmbGroup.numChildren;
imgTween = new TweenLite(photoBack, tweenDuration * 2, {x:Math.random() * 20 - 10,
y:Math.random() * 20 - 10,
rotation:Math.random() * 20 - 10,
ease:Expo.easeInOut});
tmbGroup.addChildAt(photoBack, 0);
}
function transitionOut(e:MouseEvent):void {
var photoContainer:MovieClip = MovieClip(e.target);
photoContainer.removeEventListener( MouseEvent.CLICK, transitionOut );
imgTween = new TweenLite(photoContainer, tweenDuration, {x:220,
y:180,
rotation:45,
ease:Expo.easeInOut,
onComplete: transitionIn});
}
function transitionIn():void {
var photoContainer:MovieClip = MovieClip( tmbGroup.getChildAt(tmbTotal-1) );
var photoContainer2:MovieClip = MovieClip( tmbGroup.getChildAt(tmbTotal-2) );
var slideNum:Number = parseInt( photoContainer.name.slice(8,10) ) + 1;
if(slideNum == tmbTotal) slideNum = 0;
imgTween = new TweenLite(photoContainer, tweenDuration, {x:Math.random() * 20 - 10,
y:Math.random() * 20 - 10,
rotation:Math.random() * 20 - 10,
ease:Expo.easeInOut,
onComplete: photoClick});
imgTween = new TweenLite(photoContainer2, tweenDuration, {rotation:0,
ease:Expo.easeInOut});
tmbGroup.addChildAt( photoContainer, 0 );
headingTxt.text = titleArray[slideNum];
descTxt.text = descArray[slideNum];
urlTxt.text = urlArray[slideNum];
urlTxtTarget.text = targetArray[slideNum];
}
function photoClick():void {
var photoContainer:MovieClip = MovieClip(tmbGroup.getChildAt(tmbTotal-1) );
photoContainer.addEventListener( MouseEvent.CLICK, transitionOut, false, 0, true );
}
function goto_URL(me:MouseEvent) {
navigateToURL(new URLRequest(urlTxt.text), urlTxtTarget.text);
}
The xml is too long for a comment:
<?xml version="1.0" encoding="utf-8"?>
<thumbnails>
<thumbnail filename="photoNumber01.jpg"
url="http://www.barnesjewish.org"
target="_blank"
title="Barnes-Jewish"
description="The dedicated heart transplant team members at Barnes-Jewish and Washington University focus only on patients undergoing transplant and those with congestive heart failure. Each person on the transplant team is an expert in a different area of transplantation. Together, they bring their expertise, knowledge and understanding to each patient in our program." />
<thumbnail filename="photoNumber02.jpg"
url="http://www.utsouthwestern.edu"
target="_blank"
title="UT Southwestern"
description="UT Southwestern Medical Center's Heart Transplant Program continues to rank among the best in the nation in survival rates for post-transplant patients." />
<thumbnail filename="photoNumber03.jpg"
url="http://www.mayoclinic.org/heart-transplant/"
target="_blank"
title="Mayo Clinic"
description="The Mayo Clinic Heart Transplant Program encompasses heart, heart-lung and lung transplant, as well as the use of ventricular assist devices for infants, children and adults." />
<thumbnail filename="photoNumber04.jpg"
url="http://www.jeffersonhospital.org"
target="_blank"
title="Jefferson Hospital"
description="As a heart care patient at Jefferson, a knowledgeable and skilled team of physicians, surgeons, nurse coordinators, psychologists, pharmacists, dieticians, researchers and staff with robust expertise and state-of-the-art resources will support you." />
<thumbnail filename="photoNumber05.jpg"
url="http://www.massgeneral.org"
target="_blank"
title="Massachusetts General Hospital"
description="The Heart Transplant Program draws on state-of-the-art technology, leading-edge medical and surgical interventions and more than two decades of experience to provide patients with individualized care before and after their heart transplant." />
</thumbnails>
A: Solved
This is now solved: In the tmbLoaded function all I had to do was place the if/else statement after photoBmp and photoBack creation and remove the tween inside the if/else statement. Also, I was advised to not use a global variable for TweenLite because I need not worry about garbage collection using TweenLite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to lock WORD in text-box ASP.NET after pressing space? I have seen many websites that if you write something in text box and press space, the words become locked with a cross mark (X) on right on top ... and when you click cancel the word disappears.
I am having trouble understanding the description, for example of the StackOverflow TAG section when you ask a question page.
How can I achieve this with an ASP.NET text box?
A: If you don't like jQuery chosen then try Manifest
Manifest (License: MIT, examples) also by Justin Stayton enhances text inputs so multiple items can be selected and edited. The API is very consistent with Marco Polo, and Manifest can take a marcoPolo object if autocomplete functionality is required.
$('#recipients').manifest({
marcoPolo: {
url: '/contacts/search',
formatItem: function(data) {
return '"' + data.name + '" (' + data.email + ')';
}
}
});
The author also points out how these plugins differ from the popular Chosen plugin:
If you want to make a select element with a lot of options more
user-friendly, use Chosen. If you can’t reasonably list out every
possible option (like all users in a system), or you need to allow
arbitrary values (like new tags), use Manifest.
Source: DailyJS
A: Take a look at Tag It.
Demo: Here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you write a property so that you can access inner variables? I have a property enclosing a rectangle I have called it Window.
when I try to use the property to change the location or "X" value of the rectangle, I get an error: "Can not modify the return value of Window because it is not a variable."
Now I know I can just directly access the variable, but I would prefer to be able just modify the "X" value. I also don't want to be creating a new rectangle every time I modify it.
So is there something I can add to my property that will let me modify the X value through the property?
This is where I am trying to use the property:
Window.X -= amount;
This is where I have the proprty:
private Rectangle _window;
public Rectangle Window
{
get { return _window;}
set
{
if (/*condition*/)
_window = value;
}
}
A: Problem is that Rectangle is struct. Property accessor is actually a method and when it returns struct it is just copied, so you can't modify underlying struct that way.
Solutions:
*
*If Rectangle is your code make it class.
*r = Window; r.X -= amount; Window = r;
By the way you should thank C# compiler for that, becase technically it can modify that X, but it would be field/prop of temporary object, it would make later debugging a hell for you. In C++ it actually compiles.
Also it is good example why structures should be immutable. You just wouldn't have that temptation.
A: Rectangle is a struct - hence your property returns a value, not a variable.
A: It doesn't work because System.Drawing.Rectangle is be defined as a struct (value type).
It's not allowed because when you reference the property you get a copy of the value (struct). Assigning the X property on the struct therefore has impact on the Window property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Accessing HTML attributes in Nokogiri Here is the code I'm using:
location = block.xpath("*/img")
puts location
And this outputs:
<img src="/images/p.gif" height="1" width="0">
What I want to do is get the width attribute out of the html, but I can't seem to get that too work. I think I need to put ['width'] somewhere in my code, and I've tried following various examples online but couldn't get it to work.
A: Take a look at the xpath syntax from this XPath Tutorial.
Try block.at_xpath("*/img")["width"], or */img/@width if there is just one element.
A: CSS selectors tend to be easier and more readable:
puts block.at('img')[:height]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: AS3: Storing array of custom classes in a Locally Shared Object (LSO) I am having problems storing an array of objects, all of which are the same custom class in an LSO and then reloading that array from the LSO without losing the class type of the objects in the list.
I know how to store a single object of a custom class and load it withe the correct class type using the registerClassAlias() function, but I cannot seem to apply this to arrays of objects.
I am trying to save an array called messageList. Each element is a custom class GameMessage with a property called gameLevel. After I load the LSO I am trying to do something like
trace("0th message is from level " + GameMessage(messageList[0]).gameLevel);
And I am getting an exception of like this:
TypeError: Error #1034: Type Coercion failed: cannot convert Object@90fdfa1 to GameMessage.
I have registered the GameMessage class using
registerClassAlias("GameMessage", GameMessage);
and everything works if rather than a list of messages I try and save/load a single message.
Any help on how to solve this problem would be greatly appreciated!
A: Like The_asMan said I don't think you can do custom classes, only the basic datatypes from AS3. What you could do in your custom classes is set helper functions like fromObject(object) and toObject():Object in the class to help you convert them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery parents not working with remove I have the following code:
$(document).ready(function(){
$(".uiCloseButton").click(function(e)
{
e.preventDefault();
var element = $(this).parents('.uiOverlay');
alert(element);
element.fadeOut(200,
function()
{
alert(element);
element.remove();
});
});
});
The idea is that when the close button is clicked it will remove it's highest parent using the parents() method. I have been alerting the variable element to check its value and it always returns as [object Object] when surely it should contain the parent element?
However it does still fade the element so it's working BUT doesn't remove the element from the DOM so it's only half working...
Any ideas why it's not removing the element and why the element var is empty?
Thanks
A: Use console.log instead. Also you were getting the parents again before removeing, you can just do $(this).remove().
$(document).ready(function(){
$(".uiCloseButton").click(function(e)
{
e.preventDefault();
var element = $(this).parents('.uiOverlay');
console.log(element);
element.fadeOut(200,
function()
{
console.log( $(this) );
$(this).remove();
});
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PyDev: @DynamicAttrs for modules In the program I am writing, I created a module called settings that declares a few constants but loads other from a configuration file, placing them in the module namespace (for example: the value of π might be in the code of the module, but the weight of the user in a configuration file).
This is such that in other modules, I can do:
from settings import *
Everything works fine for me but - using Aptana Studio / PyDev, the code analysis tool throws a lot of undefined variable errors like this:
I found here that there is a flag usable to prevent this behaviour in class docstrings, but it has no effect if I try to use it at module level. So I wonder two things:
*
*Is there a way to selectively get rid of these errors (meaning that I wouldn't want to completely turn off the option "mark as errors the undefined variables": in other modules it could in fact be an error)?
*If not, is there an alternative pattern to achieve what I want in terms of wild imports, but without confusing the code analysis tool?
Pre-emptive note: I am perfectly aware of the fact wild imports are discouraged.
A: Actually you'd probably have the same error even if it wasn't a wild import (i.e.: import settings / settings.MY_VARIABLE would still show an error because the code-analysis can't find it).
Aside from the @UndefinedVariable in each place that references it (CTRL+1 will show that option), I think that a better pattern for your module would be:
MY_VARIABLE = 'default value'
...
update_default_values() # Go on and override the defaults.
That way, the code-analysis (and anyone reading your module), would know which variables are expected.
Otherwise, if you don't know them before, I think a better approach would be having a method (i.e.: get_settings('MY_VARIABLE')).
Unrelated to the actual problem. I'd really advise against using a wild import here (nor even importing the constant... i.e.: from settings import MY_VARIABLE).
A better approach for a settings module is always using:
import settings
settings.MY_VARIABLE
(because otherwise, if any place decides it wants to change the MY_VARIABLE, any place that has put the reference in its own namespace will probably never get the changed variable).
An even safer approach would be having a method get_setting('var'), as it would allow you to a better lazy-loading of your preferences (i.e.: don't load on import, but when it's called the 1st time).
A: You can use Ctrl-1 on an error and choose @UndefinedVariable or type #@UndefinedVariable on a line that has an error you want to ignore.
You can try to add your module to be scanned by the PyDev interpreter by going to Window > Preferences, then PyDev > Interpreter - Python. Under the Libraries tab, click New Folder and browse to the directory that contains settings, then click Apply. Hopefully, Pydev will find your package and recognize the wildly-imported variables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Maintain SelectList Options over postbacks I was wondering if there is a way to maintain your list of options on a Select List in MVC 3. I am pretty new to MVC but in WebForms you could populate the DropDownList on the first load of the page and then the ViewState would maintain that list for all of the AutoPostBacks. This was nice because often, DropDownLists are populated by query to the database. I know that ViewState does not exist in MVC but is there a better way of repopulating the SelectList without having to hit the database during the request of every post?
A: You have several options here.
Your selected value will be posted back. With that in mind since you no longer have ViewState you ideally want to
*
*Have your Repository (if you dont have one - create one. You simply ask the repository for the data and it controls the caching or loading) that you ask for the data in the drop down, cache the data and just simply request it again. Rebind your list (use DropDownFor)
*Use MVCContrib's Html.Serialize to essentially ViewState it, however the cache is a bit cleaner and doesnt rely on data sent back and forth.
Also remember that after you post your data, if everything is 'good' you want to REDIRECT back to your "GET" action to reload the data and display to the client. This was an issue in web forms that sometime a user saw XYZ after postback but after a refresh saw YXX. Using the PRG pattern in MVC posts-redirects-gets to load up fresh data.
After your post you should generally only redisplay the data if there was a validation error, otherwise redirect to a get method.
A: Your controller receives the value on postback. You have to place that value back in the model to tell the view what the selected value is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TextView failing hard to alignTop and alignBottom
The "sun is red" should align to the top of the image, and "2pm" should align to the bottom. Why don't attributes layout_alignTop and layout_alignBottom work as documented?
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="9dp">
<ui.RoundedImageView
android:id="@+id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="9dp"
st:cornerRadius="3"
android:background="@drawable/black_rounded3" />
<TextView
android:id="@+id/uname"
android:layout_toRightOf="@id/img_user"
android:layout_alignTop="@id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textStyle="bold" />
<TextView
android:id="@+id/time"
android:layout_toRightOf="@id/img_user"
android:layout_alignBottom="@id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#909191" />
<LinearLayout
android:id="@+id/layout_g"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="9dp"
android:layout_marginLeft="9dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:gravity="right">
<TextView
android:gravity="right"
android:layout_gravity="right"
android:id="@+id/gtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/text_detail" />
</LinearLayout>
</RelativeLayout>
A:
Why don't attributes layout_alignTop and layout_alignBottom work as documented?
-> They do.
The problem is with the RoundedImageView object you're using. My guess is that it is onMeasure is not correct and is not returning proper value for where the top and bottom of itself is. With out knowing anything else about this RoundedImageView that you're using I can't really point you in a direction to get it fixed.
I changed your code to this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="9dp">
<ImageView
android:id="@+id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="9dp"
android:background="@drawable/black" />
<TextView
android:id="@+id/uname"
android:layout_toRightOf="@id/img_user"
android:layout_alignTop="@id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="the sun is red"
android:textStyle="bold" />
<TextView
android:id="@+id/time"
android:layout_toRightOf="@id/img_user"
android:text="2pm"
android:layout_alignBottom="@id/img_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#909191" />
<LinearLayout
android:id="@+id/layout_g"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="9dp"
android:layout_marginLeft="9dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:gravity="right">
<TextView
android:gravity="right"
android:layout_gravity="right"
android:id="@+id/gtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</RelativeLayout>
And it properly aligns the text. Here is screenshot:
A: I had a similar problem with a customized view (in my case directly inherited from android.view.View) and a RelativeLayout.
I did not overwrite the onMeasure() method and used the canvas that I got in onDraw() as is to write my graphics into it. The graphical output was completely ok, but the alignment of other views in the RelativeLayout did not work as in the case described here.
It finally turned out that my constructor did not call the constructor of the superclass properly (I forgot to pass the AttributeSet). After I changed the first line of my constructor to
public MyNewView (Context context, AttributeSet attrs) {
super(context, attrs);
...
}
all of a sudden everything worked well.
Seems as if some magic of the layout algorithm of Android is already happening in the constructor of android.View.view long before onMeasure() is called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I get an 'identifier not found' error This is my first attempt to create a basic list (i need this at school) and i get a strange error.
This is the script:
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
using namespace System;
using namespace System::Threading;
struct nod
{
int info;
nod *leg;
};
int n, info;
nod *v;
void main()
{
....
addToList(v, info); //I get the error here
showList(v); //and here
}
void addToList(nod*& v, int info)
{
nod *c = new nod;
c->info=info;
c->leg=v;
v=c;
}
void showList(nod* v)
{
nod *c = v;
while(c)
{
cout<<c->info<<" ";
c=c->leg;
}
}
The exact error is:
error C3861: 'addToList': identifier not found
I dont know why I get this... sorry if it is a stupid question but i am very new at this. Thanks for understanding.
A: Identifiers must be declared before they are used. Move your declaration and definition of addToList earlier in the text file.
Thus:
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
using namespace System;
using namespace System::Threading;
struct nod
{
int info;
nod *leg;
};
int n, info;
nod *v;
void addToList(nod*& v, int info)
{
nod *c = new nod;
c->info=info;
c->leg=v;
v=c;
}
void showList(nod* v)
{
nod *c = v;
while(c)
{
cout<<c->info<<" ";
c=c->leg;
}
}
void main()
{
....
addToList(v, info); //No more error here
showList(v); //and here
}
A: Try declaring addToList above main:
void addToList(nod*& v, int info);
Similarly for showList. The compiler needs to see a declaration of the function before it can use it.
A: you need to put a forward declaration to use a method before it's implementation. Put this before main :
void addToList(nod*& v, int info);
In C/C++ a method should be used only after it's declaration. To allow recursive call between different methods you can use forward declarations in order to allow the use of a function/method that will be forward implemented.
A: Try placing the declarations of showList() and addToList() before main().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is it possible to distribute Image Units with my application? Mac OS X Mavericks
I was told that the issue was fixed in Mac OS X 10.9
Original
I read the documentation and didn't find the answer. It suggests to create Image Units, it requires to put this unit inside either ~/Library/Graphics/Image Units or /Library/Graphics/Image Units (putting the image unit inside Your.app/Contents/Library/Graphics/Image Units has no effect).
There is other, non-recommeneded way, to create Image Unit, which allows you to distribute cikernels and access the filter from your code. But it prevent you from creating non executable filters which is a big lack of performance.
I looked through the contents of bundles of applications like Pixelmator or Acorn and found that they don't use Image Units as well. I hope this is a mistake and there is a way to distribute Image Units within an application bundle.
I'm looking for a solution that will be accepted by Mac App Store validation.
Solution which doesn't allow you to use non executable filters
From the CIPlugIn header:
/** Loads a plug-in specified by its URL. */
+ (void)loadPlugIn:(NSURL *)url allowNonExecutable:(BOOL)allowNonExecutable
AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_7;
/** Loads a plug-in specified by its URL.
If allowExecutableCode is NO, filters containing executable code will not be loaded. If YES, any kind of filter will be loaded. */
+ (void)loadPlugIn:(NSURL *)url allowExecutableCode:(BOOL)allowExecutableCode
AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER;
New method isn't listed in official docs. So, to load bundle you simply do:
if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_6)
{
[CIPlugIn loadPlugIn:[[NSBundle mainBundle] URLForResource:@"YourPlugin" withExtension:@"plugin"]
allowNonExecutable:YES];
}
else
{
[CIPlugIn loadPlugIn:[[NSBundle mainBundle] URLForResource:@"YourPlugin" withExtension:@"plugin"]
allowExecutableCode:YES];
}
Unfortunately if you try to use CIFilter with QuartzCore framework (e.g. with CALayer) app will crash because of stack overflow.
frame #0: 0x00007fff8b6a5d36 CoreImage`-[CIFilter copyWithZone:] + 12
frame #1: 0x00007fff8b7d1c7e CoreImage`-[CIPlugInStandardFilter _provideFilterCopyWithZone:] + 18
frame #2: 0x00007fff8b6a5d59 CoreImage`-[CIFilter copyWithZone:] + 47
frame #3: 0x00007fff8b7d1c7e CoreImage`-[CIPlugInStandardFilter _provideFilterCopyWithZone:] + 18
frame #4: 0x00007fff8b6a5d59 CoreImage`-[CIFilter copyWithZone:] + 47
frame #5: 0x00007fff8b7d1c7e CoreImage`-[CIPlugInStandardFilter _provideFilterCopyWithZone:] + 18
frame #6: 0x00007fff8b6a5d59 CoreImage`-[CIFilter copyWithZone:] + 47
A: As well as the Library paths you mention, Mac OS X will also look in YourApp.app/Contents/Library.
I think everything should work if you put your Image Unit in YourApp.app/Contents/Library/Graphics/Image Units/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Do database stored procedures suffer from poor performance when returning large volumes of data? Under VoltDB Don'ts
http://community.voltdb.com/DosAndDonts
They state
Don't create queries that return large volumes of data (such as SELECT
* FROM FOO with no constraints) especially for multi-partition
transactions. Be conservative in the data returned by stored
procedures.
This is one of the use cases that I have. Is there some aspect of stored procedures that make them unsuitable for this type of query or is it something specific to VoltDB? Under this scenario, would performance degrade to a level that would be worse than a traditional RDBMS such as Postgres?
Edit: My query is not quite a select * from foo but I will need to select all financial transactions between certain date ranges and this could exceed 100m rows
A: All databases need to pay the materialization and i/o costs to transfer a large result set back to a user.
However, I can speak specifically to VoltDB.
In VoltDB, stored procedures are all transactions. Even a result set that selects a large portion of the database is a fully isolated from other concurrent procedures. The tuples in that result set need to be momentarily buffered internally (for example for cross-partition ordering or limiting) and then returned to the user.
The combination of needing to maintain full isolation over a result that can take many milliseconds (or seconds) of I/O to return to the user and the aggregation that happens at the coordinating node of a multi-partition procedure limits the maximum result set size.
I suspect a future release will address this limitation - many people have data-access requirements similar to what you describe.
A: The performance issue is that of large data transfers. This is generally true for all databases.
When a database needs to return large amounts of data, it needs to use lots of resources (memory, CPU, network IO for example), degrading performance.
The network IO alone can be an issue, as if it is a significant amount of data, nothing else could go through the network till the data transfer has completed.
A: If you are querying SELECT * FROM FOO in order to display the results to a user interface, or a similar use case, then paging is a good approach to limit the size of the data returned and the execution time of the transaction. There is a paging example in a.
If you are trying to extract data from VoltDB to export to another database or system, the better approach is use VoltDB's Export.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simple HTML DOM gets only 1 element I'm following a simplified version of the scraping tutorial by NetTuts here, which basically finds all divs with class=preview
http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/comment-page-1/#comments
This is my code. The problem is that when I count $items I get only 1, so it's getting only the first div with class=preview, not all of them.
$articles = array();
$html = new simple_html_dom();
$html->load_file('http://net.tutsplus.com/page/76/');
$items = $html->find('div[class=preview]');
echo "count: " . count($items);
A: Try using DOMDocument and DOMXPath:
$file = file_get_contents('http://net.tutsplus.com/page/76/');
$dom = new DOMDocument();
@$dom->loadHTML($file);
$domx = new DOMXPath($dom);
$nodelist = $domx->evaluate("//div[@class='preview']");
foreach ($nodelist as $node) { print $node->nodeValue; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CodeIgniter - mysql while loop I am relatively experienced PHP developer.
I have chosen the CodeIgniter framework. So far I have understood how it is used. Until now, I want to be able to do a while loop.
Within my controller I have:
$this->load->model('Test');
$data['result'] = $this->Test->getInfo();
$this->load->view('index1', $data);
In my Model I have:
$result = mysql_query("SELECT * FROM users WHERE last_name='Hart'")or die(mysql_error());
$row = mysql_fetch_array( $result );
return $row;
And in my View:
echo $result[0];
However, this only outputs the first field within the first row found.
Please could you help me with retrieving the information from a database - while loop.
Does the while loop happen in the Model? Am I just echoing out the result correctly?
A: There's actually a much easier way to do what you want to do using the ActiveRecord class that CodeIgniter includes which will allow you to just return an array of results. Here's the documentation.
Your model would become:
$this->db->where('last_name','Hart');
$result = $this->db->get('users');
return $result->result_array();
You may also have to setup your database in application/config/database.php, and also load the database class in application/config/autoload.php:
$autoload['libraries'] = array('database');
To display this information, using the MVC pattern properly your controller should pass the information it gets from the model to a view. To do this generally you do this:
$data['myinfo'] = $this->test->getInfo();
$this->load->view('test_view',$data);
Then you have to create a view like so in applications/views/test_view.php:
<h1>Some HTML goes here</h1>
<?php
foreach($myinfo as $row) {
echo $row['field'];
}
?>
<p>Some more HTML goes here</p>
I suggest you read the CodeIgniter User Guide before diving into creating an application as CodeIgniter includes libraries that greatly simplify and speed up the whole process.
A: Well mysql_fetch_array will only bring back one row at a time, so you would need to put the while loop around the mysql_fetch_array call
Something like
while($row = mysql_fetch_array($result)) {
//save/process data
}
I would however just use codeigniters libraries to load the db and then use it:
$this->load->database();
$result = $this->db->query("SELECT * FROM users WHERE last_name='Hart'");
$result = $result->result_array();
//check for data and handle errors
return $result[0]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android - Is there a way to listen if GPS was enabled or disabled I write this code to receive location updates -
PendingIntent launchIntent = PendingIntent.getBroadcast(context, 5000, intent, 0);
manager.requestLocationUpdates(selectProvider(), 0, 0, launchIntent);
I select the gps provider if its available, otherwise the network provider. Is there a way I could switch back to the gps one if it gets enabled later?
Does the system broadcast an intent when gps provider is enabled or disabled? Could I set up a listener for the same?
A: You can detect if GPS status changed, e.g. if a GPS satellite fix was acquired.
Look at GpsStatus.Listener. Register it with locationManager.addGpsStatusListener(gpsStatusListener).
A: public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "GPS disconnected", Toast.LENGTH_LONG);
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG);
Toast.makeText(this, "Please Switch on GPS." + provider,
Toast.LENGTH_LONG).show();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C# images inside of a ListView I want to make a ListView that has small images, that was taken from a scanner, inside of the ListView. (I have the scanning script done, and it saves the scanned image under C:/Temp/*.jpg. )
What I'm having trouble with is, I want the scanned images to be displayed inside of the ListView and when you click an image in the ListView it displayed the full Image in the PictureBox.
An Image of what i'm talking about.(tried to post the image inside of this post but rep isn't high enough)
I was thinking about having the images' location stored inside of an List array like
List<string> fileLocationArray = new List<string>();
foreach () {
...
string fileLoc = (@"C:\temp\" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".jpeg");
fileLocationArray.Add(fileLoc);
...
}
Then displaying the images inside the ListView using the List array.
Keep in mind that I plan on uploading these images to an FTP server. That's why I wanted to use a List array.
one more thing, they will be picture of document, not photos, if that means anything to you.
A: **Fill ListView :**
For(int i=0; i<fileLocationArray.Count();i++)
{
System.Windows.Controls.Image imgControl=new System.Windows.Controls.Image();
BitmapImage imgsrc = new BitmapImage();
imgsrc.BeginInit();
imgsrc.UriSource=fileLocationArray[i];
imgsrc.EndInit();
imgControl.source=imgsrc;
listView.Items.Add(imgControl);
}
**After filling ListView control create event listView SelectionChanged**
**imgContolShow // this control show selected image**
void listw_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
imgContolShow.Source = ((System.Windows.Controls.Image)listwiev.SelectedItem).Source;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Moving up a line in FSI.exe Ok, We all love fsi, but I hate it when I type in the wrong thing and then I want to go up a line and it won't let me....
Is there some kind of shortcut I am missing?
For example, here is a mutually recursive discriminated union. Oh crap, I screwed it up. I want to go back, but I can't.
How do I go up one line and fix stuff?
A: If you've already committed the line, you can either redefine it (you can define the same types/functions as many times as you want in FSI), or start over. That's why the preferred way to use FSI is: write the code in a script file and 'Send to Interactive'. That avoids this issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7521518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.