text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Can we add HTML5/Jscript to ASP.Net MVC2 Project I wonder to know if we can add HTML5/Jscript files to ASP.Net MVC2 Project?
If yes , How ?
A: ASP.NET MVC is a pattern where you have total control over the views. This means that you can write any javascript and HTML markup you like. If you like HTML5, then you can use HTML5.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ruby: search an multi-dimensional array for a value and update if needed Trying to look through an array and see if a particular value is set and if it is, update the numbers attached to it.
Example:
test = [['test',1,2],['watch',1,2],['fish',1,2]]
So I'd like to search this array for 'test' - if it exists, amend the values '1,2', if it doesn't exist, just add the new search term into the array.
New to ruby and having trouble searching inside a multi-dimensional array and getting the key back
A: I'd go for the hash method suggested in the comments, but if you're really wanting to store your data in the multidimensional array like that I suppose you could do something like:
search_term = "test"
search_item= nil
test.each do |item|
if item.include? search_term
search_item = item
end
end
if search_item.nil?
test << [search_term]
else
search_item << [1,2]
end
I think that would do it (although I'm a little fuzzy on what you were wanting to do after you found the item).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Database triggers that tells my website that something has been updated I am in the process of creating a friendlist using ASP.NET/C# and MSSQL 08. Simple datalist that lists the profile image and name of my friends.
Next to the name, I have a label showing current status of my friend. Like for instance, Online, Offile, Away etc.
My question is, how can I change the value of this label, without having a timer that calls the database all the time asking for the current status?
I would like to have the database (sql server 2008) tell me when a change as occured and tell my business logic to update the status label.
Is this possible?
Thanks!
A: To accomplish what you are looking for.. And this is just how I would do it, is to create a view based on the table with only the items that are needed to accomplish the task.. For instance, UserID | Online_Status.. Then using AJAX, make a call. It would be so small to the user that they would not even notice the bandwidth usage/processing... etc..etc...
This is pretty much exactly what you said you didn't want, but even if you had 1 million users and space them like 3-5 minutes apart.. You should be ok considering it would take milliseconds to perform the check.
Just my two cents..
A: I don't think you should do it like that. There are techniques to do this using comet but it will consume a lot of resources from your server clearly reducing the number of users that can access your site/app. The problem is that the the server and client needs to have a socket open for the server to be able to push data to the client.
What I would do is to have the client ask if there are any updates, keeping the payload to a minimum. If the server says there is data that changed the client makes another request to get that data.
A: You could use the SqlDependency class to get notified when the result of a database query changes.
There is an excellent article on MSDN explaining the SqlDependency class.
To use the SqlDependency class in the context of ASP.Net consider the strategy explained in the following video of MIX 2011.
Hope, this helps.
A: All options given to this moment are valid ones and that's how most websites do it today; however, the OP is asking for some sort push notification mechanism as opposed to pull, and I think for that kind of thing, websockets are the way to do it.
A: I believe this is what for the SqlCacheDependency is designed for. If you are using SQL Server 2005 or higher*, it implements a push-notification model from SQL Server to your application to notify you of when a change occurs in your dataset. So each time the cache is invalidated you can get the latest data, but until then it was just will read from your cached dataset and save a trip to the database. The documentation for it is here.
*However*,
As stated in the comments and such, this isn't really what SQL Server is designed for at its core, and I don't know to hand actually how efficient this solution is. If I understand your problem correctly, you would need a cache dependency PER USER which could very well be completely unscalable using this solution. Rather than second-guess what is going to be the most efficient solution, you really should develop, test, measure and find out for yourself. Every situation is going to be different, there is no "right way".
* In Sql Server 2000 and 7 it uses a pull-model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: $(document).ready(function() - don't work I am using Rails & jQuery.
Here is HTML which I get:
<head>
<title>Some</title>
<script src="/javascripts/jquery.js?1305699774" type="text/javascript"></script>
<script type="text/javascript">
alert("2");
$(document).ready(function() {
alert("1");
....
When I am refreshing the window I get only one alert message ("2").
Why I didn't get second alert message?
A: You have included prototype, which also defines $.
So use jQuery() instead of $ and run jQuery in .noConflict() mode
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AJAX4JSF/AjaxStateHolder | Session Memory Leak I am working on the performance tuning of an enterprise web application with about 300 simultaneous user. I have noticed from the GC log that the application heap is always growing and objects are always accumulating even after Full GC. I've acquired a production heap dump and I was surprised that the session objects are occupying more than 90% of the heap size! That's all because of the AjaxStateHolderObject.
The application is runing on JSF 1.X and RichFaces 3.3.0.
Before starting this discussion I tried the following:
*
*Added the following code to web.xml
<context-param>
<param-name>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</param-name>
<param-value>1</param-value>
</context-param>
*
*Added the following code to web.xml
<context-param>
<param-name>com.sun.faces.numberOfViewsInSession</param-name>
<param-value>1</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.numberOfLogicalViews</param-name>
<param-value>1</param-value>
</context-param>
*
*Upgraded from RichFaces 3.3.0 to 3.3.3
All the above attempts failed to solve the memory leakage problem.
Updates
*A single user session can consume up to 25 MB because of the AjaxStateHolder huge size.
*Most of the managed beans of the application are request scope and there is no unused referenced objects in session, the only problem concerning memory is the ajaxStateHolder.
Thanks in advance for any guidance.
Any kind of help will be appreciated because I didn't find anything concerning this issue on the web.
A: It seems that you have run into the JSF/a4j session memory leak defect. See link below for more description on the matter:
https://issues.jboss.org/browse/RF-3878
It appears as if the view state is being cached in session and not cleaned up. It is a bug with a4j and cannot be fixed, just worked around. The configurations you added to web.xml are the only suggested workaround but apparently this does not help too much.
It seems a4j is not very scalable so perhaps the best long term solution is to slowly refactor the a4j components out of the application and replace them with a different component framework? Sorry I could not be more of a help and I wish you luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: multiple image upload with dragonfly i was trying for multiple image upload with dragonfly in rails3. i searched for some tutorials, but couldn't find any. i found a tutorial for multiple image upload with Carrierwave, but couldnt find luck with dragonfly .. any help please :)
A: Preface
Dragonfly itself can be used to manage media for your project in general, similar to paperclip. The question itself boils down to the multiple file upload within a rails application. The some tutorials on this topic available, which can easily be adapted to models using Dragonfly for storing specific files on them. I would suggest you look into those and try to adapt them for your project.
However, I can present a minimum example which i built for a rails 3.2 app currently in development, which isn't perfect (validation handling for example), but can give you some starting points.
Example
Just for reference, the essential idea is taken from here. This example is done with Rails 3.2.x.
Let's say you have a vacation database, where users may create trip reports on vacations they took. They may leave a small description, as well as some pictures.
Start out by building a simple ActiveRecord based model for the trips, lets just call it Trip for now:
class Trip < ActiveRecord::Base
has_many :trip_images
attr_accessible :description, :trip_images
end
As you can see, the model has trip images attached to it via a has_many association. Lets have a quick look at the TripImage model, which uses dragonfly for having the file stored in the content field:
class TripImage < ActiveRecord::Base
attr_accessible :content, :trip_id
belongs_to :trip_id
image_accessor :content
end
The trip image it self stores the file attachment. You may place any restrains within this model, e.g. file size or mime type.
Let's create a TripController which has a new and create action (you can generate this via scaffolding if you like, it is by far nothing fancy):
class TripController < ApplicationController
def new
@trip = Trip.new
end
def create
@trip = Trip.new(params[:template])
#create the images from the params
unless params[:images].nil?
params[:images].each do |image|
@trip.trip_images << TripImages.create(:content => image)
end
if @trip.save
[...]
end
end
Nothing special here, with the exception of creating the images from another entry than the params hash. this makes sense when looking at the the file upload field within the new.html.erb template file (or in the partial you use for the fields on the Trip model):
[...]
<%= f.file_field :trip_images, :name => 'images[]', :multiple => true %>
[...]
This should work for the moment, however, there are no limitations for the images on this right now. You can restrict the number of images on the server side via a custom validator on the Trip model:
class Trip < ActiveRecord::Base
has_many :trip_images
attr_accessible :description, :trip_images
validate :image_count_in_bounds, :on => :create
protected
def image_count_in_bounds
return if trip_images.blank?
errors.add("Only 10 images are allowed!") if trip_images.length > 10
end
end
I leave this up to you, but you could also use client side validations on the file field, the general idea would be to check the files upon changing the file field (in CoffeeScript):
jQuery ->
$('#file_field_id').change () ->
#disable the form
for file in this.files
#check each file
#enable the form
Summary
You can build a lot out of existing tutorials, as dragonfly does not behave that differently to other solutions when it comes to just to uploading files. However, if you'd like something fancier, I'd suggest jQuery Fileupload, as many others have before me.
Anyways, I hope I could provide some insight.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: org.postgresql.util.PSQLException: ERROR: out of shared memory I am calling a function having more than 200 DROP Table Statements using JAVA and I am getting org.postgresql.util.PSQLException: ERROR: out of shared memory.
What approach should i follow in order to avoid out of shared memomry ?
PS : Restriction is that I can't change any parameters related to PostgresSQL.
A: If the cause of the error is on the server side: In PostgreSQL a function is always executed inside a transaction. DO blocks are anonymous functions and are handled the same way. And because even DML commands like CREATE or DROP are transactional in PostgreSQL, these commands also stress the usual resources used for ROLLBACK and COMMIT.
My guess is that dropping a huge number of large tables eats to much memory.
So if you don't need transactional behaviour in your function, the easiest way is to split the large function into several smaller ones. Call each function in a separate transaction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what wordpress theme is this? and is there a way to tell wordpress themes being used for all sites? I'm trying to figure out the theme for this site:
moneymachinefactory dot org
I know sometimes you can see it in the page source. in this case, i can't, but i know they're using wordpress.
A: It's possible that it's Wordpress, but that would be they went through great lengths to disguise that fact. Especially since this URL fails: http://moneymachinefactory.org/wp-admin , it could be expression engine, drupal or mambo or something else. Good luck, I would just email them and ask.
A: The blog http://moneymachinefactory.org/blog/ uses WP, but the other pages are static.
The style sheet in the WP theme doesn't have a standard WP style sheet header with theme info and is loaded from root instead of wp-content/themes/themename/style.css: http://moneymachinefactory.org/gzip.php?f0=style.css
They are probably rewriting the typical WP URLs with .htaccess. It's getting to be a popular thing to do for (some) security and possibly to (somewhat) protect designs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: openldap and memberof property I'm trying to make auth with LDAP (Zend_Ldap) and using openldap server.
Groups objects implements two classes: posixGroup and top
Users objects implements two classes: inetOrgPerson, posixAccount and top.
User object has no properties like "memberof", where I can see all user groups.
I can get user to groups relaions from groups propertie "memberuid", but it's not so usable, as in case with "memverof" propety.
Wich classes I must implement for users objects to get memberof field or something similar?
A: Well the answer is really 'you don't want to do that'. You want to add the user to the group, not the other way around. You can find the groups the user is a member of with a simple search filter.
Having said that, there are dynamic membership and dynamic lists overlays in OpenLDAP that can do this for you. But it's really just putting the same thing as above under the hood.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to deminify javascript
Possible Duplicate:
Online Tool to Unminify / Decompress JavaScript
Tool to reverse Javascript minify?
Is there a way to convert minified JavaScript code into normal?
A: I use WebStorm by JetBrains for my Javascript IDE, it has auto-format which seems to do the trick pretty well.
A: http://jsbeautifier.org/ works like a charm.
Most software distributed under the GPL license will also provide non-minified code.
A: Chrome's native object inspector will format JS for you, but it won't be able to make sense of the variable names - nothing will.
If you want an online solution, use JSBeautifier. It works well, and is also very handy for making sense of some of the questions you see here on StackOverflow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Convert SQL statement to Ruby on Rails I've got two tables, and I want to compare the data between them, and pick out the data from one table which is not present in the other. I already have a code that works in SQL Server Management, but I need to convert it into Rails or I need to be able to use raw SQL code in my code. Here is the code:
select * from app_servers
where not exists
( select app, environment, server
from stagings
where stagings.server = app_servers.server_id
AND
stagings.environment = app_servers.environment_id
AND
app_servers.app_id = stagings.app
)
Thanks in advance
A: Why do you want to convert it? You might use it as it is
AppServer.where(" not exists
( select app, environment, server
from stagings
where stagings.server = app_servers.server_id
AND
stagings.environment = app_servers.environment_id
AND
app_servers.app_id = stagings.app
)
")
A: If I understand correctly you have two models, AppServer and Staging and both have an environment, server and an application.
You are looking for AppServer's that do not have a corresponding Staging.
So your models would look like:
class AppServer
belongs_to :server
belongs_to :environment
belongs_to :app
end
class Staging
belongs_to :server
belongs_to :environment
belongs_to :app
end
But what you actually would want, is something like
class AppServer
belongs_to :server
belongs_to :environment
belongs_to :app
has_one :staging
end
which would be really easy to test. Something like:
AppServer.where(:staging_id => nil)
So you could consider reforming your datamodel to make this easier.
This would not be too hard: add a single column, and for each app_server find the corresponding staging.
But suppose you do not have any control over your datamodel, you would need to write something like
class AppServer
has_many :stagings, finder_sql => 'select * from stagings where server=#{server_id} and environment=#{environment_id} and app=#{app_id}'
Note: you must use single quotes!!
This would at least allow you to access something like
app_server = AppServer.first
app_server.stagings
Unfortunately, it does not allow you to write something like
AppServer.where(:stagings => nil)
To find all AppServer without staging, and you cant convert the schema, you will need to do something like
AppServer.where(" not exists
( select app, environment, server
from stagings
where stagings.server = app_servers.server_id
AND
stagings.environment = app_servers.environment_id
AND
app_servers.app_id = stagings.app
)"
)
So actually, in the end, I did not find a new and improved way using arel.
But I did show some ways to allow making use of some rails helpers, and secondly it seems a good approach, if possible (even using views), to convert your datamodel to a more rails-friendly model. One good reason is that the rails way of creating data models is actually a pretty good way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatic way of checking what validations failed in Rails Is there a way to retrieve failed validations without checking the error message?
If I have a model with validates :name, :presence => true, :uniqueness => true, how can I check if determine what validation failed(was it uniqueness or was it presence?) without doing stuff like:
if error_message == "can't be blank"
# handle presence validation
elsif error_message = "has already been taken"
# handle uniqueness validation
end
A: There's a relatively new method that let you do just that, it's not documented anywhere as far as I know and I just stumbled on it while reading the source code, it's the #added? method:
person.errors.added? :name, :blank
Here's the original pull request: https://github.com/rails/rails/pull/3369
A: ActiveModel::Errors is nothing more than a dumb hash, mapping attributes names to human-readable error messages. The validations (eg. the presence one) directly add their messages to the errors object without specifying where they came from.
In short, there doesn't seem to be an official way of doing this.
A: You can Haz all your errors in the errors method. Try this on an saved unvalid record :
record.errors.map {|a| "#{a.first} => #{a.last}"}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Spring Security's @PreAuthorize on type level can not be overridden on method level I'm trying to protect a Controller with the @PreAuthorize annotation at type level and try to override that behavior by annotating some methods with a different @PreAuthorize. The Problem is however, that Spring is evaluating the method annotation first (grants access) and is then evaluating the class annotation (denies access).
Is there any way to reverse that order? I couldn't figure it out yet.
Edit:
On the method level, I want to grant access to non-registered Users only:
@PreAuthorize("isAnonymous()")
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String renderCreateEntity(ModelMap model) {
return userService.renderCreateEntity(model);
}
The standard for this Controller however, should be to allow fully authenticated users only:
@Controller
@RequestMapping(value = "/user")
@PreAuthorize("isFullyAuthenticated()")
public class UserController { [...] }
When debug-stepping through the app, I see that isAnonymous() is evaluated first and then isFullyAuthenticated() thus resulting in an grant of access right and immediately denying access again.
A: The problem is not that you need to change the order of grant and deny. The problem is simple that that method level annotations override the class level annotations.
PrePostAnnotationSecurityMetadataSource Java Doc:
Annotations may be specified on classes or methods, and method-specific annotations will take precedence.
The concrete implementation of this logic is done in the method findAnnotation of class PrePostAnnotationSecurityMetadataSource. (Unfortunately this method is private.)
So you can write your own MethodSecurityMetadataSource, if you have a look at the code of PrePostAnnotationSecurityMetadataSource, you will see how easy it is.
But one warning at the end: the end: difficult task is not rewriting the method, the difficult task is to "inject" the new MethodSecurityMetadataSource into the security system. I belive you can not do it with the spring security namespace configuration, so you need to replace spring security namespace by explicit bean declaration.
A: Thanks for all your replys.
The answer however, was something totally different :)
I put this here in case anyone else has the same problems.
I registered a custom validator in an @InitBinder annotated method. This binding method is called AFTER the method call requested on the controller. And since this binding method was not annotated with @PreAuthorize, the request was denied.
The solution was to annotate the binding method like this:
@InitBinder
@PreAuthorize("permitAll")
public void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
And then, the method calls from my OP evaluated like expected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: virtual sub domains has error I create a project that check the sub domain and redirect to the exist subdomain ( username ) but I can't find out why when the username is in database it can't show it and show this error :
Object reference not set to an instance of an object.
My code is this in page load :
Uri MyUrl = new Uri(Request.Url.ToString());
string Url = MyUrl.Host.ToString();
//Uri MyUrl = new Uri("http://Subdomain.Mydomain.com/");
//string Url = MyUrl.Host.ToString();
string St1 = Url.Split('.')[0];
if ((St1.ToLower() == "Mydomain") || (St1.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else if (St1.ToLower() == "www")
{
string St2 = Url.Split('.')[1];
if ((St2.ToLower() == "Mydomain") || (St2.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else
{
object Blogger = ClsPublic.GetBlogger(St2);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = @fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("@fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
}
else
{
object Blogger = ClsPublic.GetBlogger(St1);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = @fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("@fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
and my class :
public static object GetBlogger(string User)
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT fUsername FROM tblMembers WHERE fUsername = @fUsername", scn);
scm.Parameters.AddWithValue("@fUsername", User);
scn.Open();
object Blogger = scm.ExecuteScalar();
if (Blogger != null)
{
SqlCommand sccm = new SqlCommand("SELECT COUNT(fId) AS Exp1 FROM tblImages WHERE (fxSender = @fxSender) AND (fxAccepted = 1)", scn);
sccm.Parameters.AddWithValue("fxSender", Blogger);
object HasQuty = sccm.ExecuteScalar();
scn.Close();
if (HasQuty != null)
{
int Count = Int32.Parse(HasQuty.ToString());
if (Count < 10)
{
Blogger = null;
}
}
}
return Blogger;
}
Which place if my code has problem ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to customize Cocos2D page turn effect with back side texture and shadow? I want to make nicer effect of page turn transition in my Cocos2D based application. There's CCTransitionPageTurn, but I'd like to add custom texture on back side and dynamic shadow, so it would look more realistic. I'd like to get something like this: http://www.youtube.com/watch?v=_vOYvaNhSHw (page turns at 0:08).
There's a good discussion on how to set up solid color for CCTransitionPageTurn
http://www.cocos2d-iphone.org/forum/topic/15523, but there's no answer to my question.
Does anybody know solution for that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Combining consecutive dates in IList into ranges
*
*I have a series of objects with from and to dates.
*Using something like:
IList<DateTime> dates =
this.DateRanges
.SelectMany(r => new [] { r.From, r.To })
.Distinct()
.OrderBy(d => d)
.ToList();
I can get all dates without any of them being duplicated. Ranges may fully overlap, partially overlap (upper or lower overlapping), touch or they may not overlap at all.
*Now I need to convert this list to a different one so that each consecutive date pair forms a new generated DateTime instance right in the middle of pair
D1 D2 D3 D4 D5
G1 G2 G3 G4
Where Dn are my distinct dates from the list and Gm dates are ones I'd like to generate in the middle of them.
Question
How do I convert an ordered list of individual dates to pairs so that I get pairs as shown in the following example? I would like to form these using LINQ instead of for loop which can accomplish the same thing. Using LINQ may result in and more efficient code due to delayed expression tree execution.
Additional explanation using a real-world example
Suppose this is my example of such ranges:
D1 D2 D3 D4 D5 D6 D11 D12
|--------------| |------| |------| |------|
D7 D8
|--------------------------|
D9 D10
|-----------------------------------------------|
First step of getting distinct dates would result in these dates:
D1 D7 D2 D3 D4 D5 D6 D10 D11 D12
D9 and D8 would fall off because they're duplicates.
Next step is to form pairs (I don't know how to do this using LINQ):
D1-D7, D7-D2, D2-D3, D3-D4, D4-D5, D5-D6, D6-D10, (D10-D11), D11-D12
Last step has to calculate a date for each pair using:
Dnew = Dfrom + (Dto - Dfrom)/2
Empty ranges issue
Range D10-D11 should preferably be omitted. But if omitting it results in over-complicates code it can be kept and excluded with a separate check afterwards. But if it can be excluded initially then that's what should be done. So if you also provide information of how to form pairs that exclude empty ranges, you're welcome to add that info as well.
A: You can use Zip():
var middleDates = dates.Zip(dates.Skip(1),
(a, b) => (a.AddTicks((b - a).Ticks / 2)))
.ToList();
A: Final solution
Based on the idea of @DavidB and interesting idea by @AakashM's original answer I've come up with my own solution that extracts ranges from a set of dates (while also omitting empty ranges) and calculating range middle dates.
If you have any improvement suggestions or comments on this solution you're warmly welcome to comment on it. Anyway this is the final code I'm using now (inline comments explain its functionality):
// counts range overlaps
int counter = 0;
// saves previous date to calculate midrange date
DateTime left = DateTime.Now;
// get mid range dates
IList<DateTime> dates = this.DateRanges
// select range starts and ends
.SelectMany(r => new[] {
new {
Date = r.From,
Counter = 1
},
new {
Date = r.To,
Counter = -1
}
})
// order dates because they come out mixed
.OrderBy(o => o.Date)
// convert dates to ranges; when non-empty & non-zero wide get mid date
.Select(o => {
// calculate middle date if range isn't empty and not zero wide
DateTime? result = null;
if ((counter != 0) && (left != o.Date))
{
result = o.Date.AddTicks(new DateTime((o.Date.Ticks - left.Ticks) / 2).Ticks);
}
// prepare for next date range
left = o.Date;
counter += o.Counter;
// return middle date when applicable otherwise null
return result;
})
// exclude empty and zero width ranges
.Where(d => d.HasValue)
// collect non nullable dates
.Select(d => d.Value)
.ToList();
A:
Next step is to form pairs (I don't know how to do this using LINQ):
List<DateTime> edges = bucketOfDates
.Distinct()
.OrderBy(date => date)
.ToList();
DateTime rangeStart = edges.First(); //ps - don't forget to handle empty
List<DateRange> ranges = edges
.Skip(1)
.Select(rangeEnd =>
{
DateRange dr = new DateRange(rangeStart, rangeEnd);
rangeStart = rangeEnd;
return dr;
})
.ToList();
A: OK my previous idea wouldn't work. But this one will. And it's O(n) on the number of inputs.
To solve the D10-D11 problem, we need the process to be aware of how many of the original intervals are 'in effect' at any given date. We can then iterate throw the transition points in order, and emit midpoints whenever we are between two transitions and the current state is ON. Here is complete code.
Data classes:
// The input type
class DateRange
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
// Captures details of a transition point
// along with how many ranges start and end at this point
class TransitionWithCounts
{
public DateTime DateTime { get; set; }
public int Starts { get; set; }
public int Finishes { get; set; }
}
Processing code:
class Program
{
static void Main(string[] args)
{
// Inputs as per question
var d1 = new DateTime(2011, 1, 1);
var d2 = new DateTime(2011, 3, 1);
var d3 = new DateTime(2011, 4, 1);
var d4 = new DateTime(2011, 5, 1);
var d5 = new DateTime(2011, 6, 1);
var d6 = new DateTime(2011, 7, 1);
var d11 = new DateTime(2011, 9, 1);
var d12 = new DateTime(2011, 10, 1);
var d7 = new DateTime(2011, 2, 1);
var d8 = d5;
var d9 = d1;
var d10 = new DateTime(2011, 8, 1);
var input = new[]
{
new DateRange { From = d1, To = d2 },
new DateRange { From = d3, To = d4 },
new DateRange { From = d5, To = d6 },
new DateRange { From = d11, To = d12 },
new DateRange { From = d7, To = d8 },
new DateRange { From = d9, To = d10 },
};
The first step is to capture the starts and finishes of the inputs as transition points. Each original range becomes two transition points, each with a count of 1.
// Transform into transition points
var inputWithBeforeAfter = input.SelectMany(
dateRange => new[]
{
new TransitionWithCounts { DateTime = dateRange.From, Starts = 1 },
new TransitionWithCounts { DateTime = dateRange.To, Finishes = 1 }
});
Now we group these by date, summing up how many of the original ranges started and finished at this date
// De-dupe by date, counting up how many starts and ends happen at each date
var deduped = (from bdta in inputWithBeforeAfter
group bdta by bdta.DateTime
into g
orderby g.Key
select new TransitionWithCounts
{
DateTime = g.Key,
Starts = g.Sum(bdta => bdta.Starts),
Finishes = g.Sum(bdta => bdta.Finishes)
}
);
To process this we could use Aggregate (probably), but it's (for me) far quicker to read and write a manual iteration:
// Iterate manually since we want to keep a current count
// and emit stuff
var output = new List<DateTime>();
var state = 0;
TransitionWithCounts prev = null;
foreach (var current in deduped)
{
// Coming to a new transition point
// If we are ON, we need to emit a new midpoint
if (state > 0)
{
// Emit new midpoint between prev and current
output.Add(prev.DateTime.AddTicks((current.DateTime - prev.DateTime).Ticks / 2));
}
// Update state
state -= current.Finishes;
state += current.Starts;
prev = current;
}
We could assert that state == 0 at the end, if we felt like it.
// And we're done
foreach (var dateTime in output)
{
Console.WriteLine(dateTime);
}
// 16/01/2011 12:00:00
// 15/02/2011 00:00:00
// 16/03/2011 12:00:00
// 16/04/2011 00:00:00
// 16/05/2011 12:00:00
// 16/06/2011 00:00:00
// 16/07/2011 12:00:00
// 16/09/2011 00:00:00
// Note: nothing around 15/08 as that is between D10 and D11,
// the only midpoint where we are OFF
Console.ReadKey();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: JSFL: Detecting when an Element has been flipped I'm writing an exporter in JSFL, to export Flash animations into a format that can be replayed in a custom player. The exporter basically iterates through the timeline and through all the elements at each keyframe, and writes out the element's name, position, rotation, scale and a local offset. These are read into the custom player which feeds the data to a sprite engine to recreate each frame of the animation.
What I want to be able to do is detect whether a given Element has been flipped (i.e. in Flash you Select the element (a symbol), then Modify->Transform->Flip Horizontal) so that the exporter can include that information too, allowing the sprite engine in the player to flip the UVs of the texture to replicate what's happening in Flash. This would be useful for (say) using one symbol for a character's right hand, and just flipping it to be their left hand, rather than having to create a whole new symbol.
Unfortunately I can't see any way of finding this information out. None of the information I have available for the Elements seems to imply that any kind of flipping has occurred. How can I detect flipping? If it can't be done algorithmically, I'd settle for the animator having to manually indicate that a symbol had been flipped (by creating some kind of plugin that gives them a tick-box which writes a value into the Element with setPersistentData(), for example), but I don't know how to make that sort of plugin either. Help!
A: scaleX doesn't work, it always seems to give a positive value. In the end I had to do this to the matrix to get the answer out. This is based on the idea that we know the matrix always contains a 2D rotation, and we know the angle, so we can get rid of the rotation from the matrix elements to just leave us with the scale. It's horrible but it seems to work.
Also, rotation sometimes comes out as NaN, particularly when the element has been flipped. using the value of skewX seems to work for things which you know aren't skewed, but I want my exporter to be able to handle skewed elements, so I think this might be the basis for another question here.
var rotationRadians;
if(isNaN(someElement.rotation)) {
rotationRadians = someElement.skewX * Math.PI / 180;
}
else {
rotationRadians = someElement.rotation * Math.PI / 180;
}
var sinRot = Math.sin(rotationRadians);
var cosRot = Math.cos(rotationRadians);
var SOME_EPSILON = 0.01;
var flipScaleX, flipScaleY;
if(Math.abs(cosRot) < SOME_EPSILON) {
// Avoid divide by zero. We can use sine and the other two elements of the matrix instead.
flipScaleX = (someElement.matrix.b / sinRot);
flipScaleY = (someElement.matrix.c / -sinRot);
}
else {
flipScaleX = someElement.matrix.a / cosRot;
flipScaleY = someElement.matrix.d / cosRot;
}
flipScaleX comes out at ~-1 if it's flipped horizontally, ~1 if not. flipScaleY is ~-1 if it's flipped vertically, ~1 if not.
A: Doesn't scaleX or matrix work? http://help.adobe.com/en_US/flash/cs/extend/WS5b3ccc516d4fbf351e63e3d118a9024f3f-7f6c.html
A: Here's electrodruid's solution packaged in several convenience functions:
function isFlippedHorizontally (element) {
return Math.round(getFlip(element)[0]) == -1;
}
function isFlippedVertically (element) {
return Math.round(getFlip(element)[0]) == -1;
}
function getFlip (element) {
var rotationRadians;
if(isNaN(element.rotation)) {
rotationRadians = element.skewX * Math.PI / 180;
}
else {
rotationRadians = element.rotation * Math.PI / 180;
}
var sinRot = Math.sin(rotationRadians);
var cosRot = Math.cos(rotationRadians);
var SOME_EPSILON = 0.01;
var flipScaleX, flipScaleY;
if(Math.abs(cosRot) < SOME_EPSILON) {
// Avoid divide by zero. We can use sine and the other two elements of the matrix instead.
flipScaleX = (element.matrix.b / sinRot);
flipScaleY = (element.matrix.c / -sinRot);
}
else {
flipScaleX = element.matrix.a / cosRot;
flipScaleY = element.matrix.d / cosRot;
}
return [flipScaleX, flipScaleY];
}
Usage Example:
var element = currentDoc.getTimeline().layers[0].frames[0].elements[0];
trace("Element is flipped:" + isFlippedHorizontally(element));
Thanks for the code electrodruid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hiding Dialog's titlebar in Android Manifest Basically, I created an Activity inside a dialog, everthing is seems working perfectly but the problem is the title bar of a dialog is still there. Is there anyway to hide it?
And also this is the tutorial, here is the link. It is exactly what I am trying to accomplish except witout title bar.
Note: THIS IS NOT JUST AN ALERTDIALOG OR DIALOG, THIS IS AN ACTIVITY INSIDE A DIALOG which only became looks like a dialog by pasting the code below.
<activity android:label="My Dialog (activity)" android:name=".MyActivity" android:theme="@android:style/Theme.Dialog"></activity>
A: You can remove the title bar programatically.
Add this line to your Activity onCreate() method.
requestWindowFeature(Window.FEATURE_NO_TITLE);
Edit:
Create a custom style that extend Theme.Dialog:
<resources>
<style name="NoTitleDialog" parent="android:Theme.Dialog">
<item name="android:windowNoTitle">true</item>
</style>`
</resources>
Then reference this theme in your activity android:theme attribute. :)
A: If ur using appcompat support v4, v7 libraries then try using
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
before setContentView and also before super.Oncreate();
A: I came up with such, easiest solution:
In Manifest
android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
Seems to work.
A: Try this :
style.xml
<style name="NoTitleActivityDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="windowNoTitle">true</item>
</style>
AndroidManifest.xml
<activity
android:name=".DialogActivity"
android:theme="@style/NoTitleActivityDialog"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get alternative info from a routing namespace in rails? Imagine you are working on a f,acebook(to skip the g,f,w) like site, and you need some routes like:
*
*www.mydomain.com/ihome/jim/posts
*www.mydomain.com/ihome/jim/post/3
*www.mydomain.com/ihome/jim/posts/3/edit.
Then how to set the routes to get the 'jim' part? I know I can use the following if there is no account part:
namespace :ihome do
resources :posts
end
A: A quick (untested) answer is : use the scope, it will give you a params[:user]
namespace :ihome do
scope ":user" do
resources :posts
end
end
Have a look at the docs here : http://guides.rubyonrails.org/routing.html#defining-defaults
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I change the font size when printing from Eclipse? Sometimes I'd like to print my code and read it during lunch. In Eclipse I'm using 10pt Helvetica font, but printing at this size is a waste of paper I think. I changed to font size 6pt, and the print was perfect; fully readable and paper saving.
However, coding in 6pt font is very hard and stressing for my eyes, so I cannot keep the setting. Also, changing font size everytime I print is a pain.
Is there a way to keep 10pt for my editor AND have the printer run at 6pt, at the same time?
A: I ended up changing the paper size to A5 and printing to PDF, then printing the PDF to A4.
A: The best workaround I've found is to copy-and-paste the entire program into a text editor where one can tweak the page/font settings (I use gedit) and print from there. A pain, but less so than changing the font size within Eclipse.
A: This question was awhile back but I found a work-around to the original question posted. When I select File-Print then a Print menu options comes up (every print menu options is different depending on the OS. This is on a Macbook) I scaled the size of the printing down. Works great to read and more importantly, save trees!:-) Scaling the printing of source code
A: I tried scaling printout to 50-75% and it works for me also: Large font on screen but small font to fit all in less amount of paper
A: Give this a try:
Go to preferences > appearance > colors and fonts then select 'basic'.
In that drop down select 'text font'. Click 'edit' make your changes and print. When you're done you may want to change it back by clicking reset.
I found this information in two places
1: http://blog.alagad.com/2007/06/15/changing-the-font-size-in-eclipse/
2: http://people.reed.edu/~jerry/121/handouts/04a-eclipse-printing.pdf [PDF]
A: I agree, Eclipse should have a 'Print font' setting.
This solution is late, but works so well, that I'm posting it anyway.
However, I have found a pretty good solution for me: format for Ledger (11x17) but scale to Letter (8.5x11). This is essentially 6 pt, which gets me 116 lines down, 140 cols across, in Portrait mode.
I like this so much, that for personal work, I have tweaked Eclipse to assume a 120 column print margin. Here's how:
*
*Set Editing font to Consolas 10 pt. (This is my preference, however it doesn't make much difference, as you will see. (Window > Preferences > General > Appearance > Colors and Fonts > Basic > Text Font)
*Set Print margin at 120 characters. (Window > Preferences > General > Editors > Text Editors > Show print margin > Print margin column 120)
*Set code style formatter's line wrapping to 120 characters. (Window > Preferences > Java > Code Style > Formatter > Active Profile > [your custom
profile name] Edit > Line Wrapping > Maximum line width > 120).
The details of how you select the Paper size to format for, vary by printer. For me, it is done from File > Print... > Preferences > Basic > Paper Size > Ledger.
Likewise, selecting page scaling is a printer preference. For me, it is File > Print... > Preferences > Advanced > Scaling > Fit to Paper Size > Letter.
A: Using Mars.1 Release (4.5.1) I still see this as a problem. I tried the scaling in the printer dialog as suggested by Allen and Eclipsed, and my Brother printer under Windows used just as much paper, using same page breaks, leaving white space at bottom of each page.
So do an experiment with a small selection before trying this. Your mileage may vary.
I'm almost ashamed to admit it, but, so that I could get colors, and preview before printing, I ended up pasting into Microsoft Word and printing from there.
A: Just print to pdf with A3 paper size then print from your pdf reader. Works for me! Can get about 100 lines of code per sheet.
A: I had a similar problem, and was given the following by a colleague. The following should be entered on the command line:
*
*To check default font: query default.print.font
*To change font temporarily: print.font "Courier New-10"
*To change font permanently: default.print.font "Courier New-8"
Hope it helps
A: The mismatch of screen font size with printed font size is supposed to be fixed in Eclipse version 3.7 (Indigo). Perhaps you need a newer version of eclipse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: What is the origin of this set_Visible exception during shutdown of winforms application? I have wrapped the Application.Run method in try/catch
[STAThread]
private static void Main(string[] args)
{
try {
MyClient client = new MyClient();
client.Run(args);
}
catch (Exception ex) { log.Error("Failed to start client",ex); }
}
Where MyClient is just:
class MyClient : WindowsFormsApplicationBase
and during every shutdown I get this exception
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'MainView'.
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Form.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
at System.Windows.Forms.Control.set_Visible(Boolean value)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at MyProgram.Main(String[] args) in C:\svn\trunk\MyProgram\client\MyProgram\Program.cs:line 54
If I set a breakpoint in the debugger in the catch block my callstack is all empty except for the client.Run(..).
As far as I can understand the stacktrace the problem is somewhere some code is doing MainView.Visible = .... but I can find anything in my code that resembles this.
How can I figure out the origin of the exception?
The MainView is created like this inside MyClient:
protected override void OnCreateMainForm()
{
string[] args = Environment.GetCommandLineArgs();
try {
MainView mainView = new MainView(args);
this.MainForm = mainView;
Application.EnableVisualStyles();
Application.Run(mainView);
}catch(Exception ex){ log.Warn("Exception in OnCreateMainForm",ex); }
}
And closing like this:
public void OnKilled()
{
log.Debug("OnKilled. Exiting");
Application.Exit();
}
MainView is defined like:
public partial class MainView : Form
{
private void InitializeComponent()
{
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainView_FormClosing);
}
private void MainView_FormClosing(object sender, FormClosingEventArgs e)
{
log.DebugFormat("'MainView_FormClosing': {0}",e.CloseReason);
if (e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.ApplicationExitCall)
{
e.Cancel = false;
Application.Exit();
}
}
A: Can you please post the code that you use in order to create the main window, and the code that you use in order to close it?
Without seeing more code, I would guess that somewhere in your code you are calling Dispose on the windows, instead of using Close. But that's just a guess.
By the way, why are you using WindowsFormsApplicationBase if this is a C# program?
A: Aha!
It turns out that Application.Run in OnCreateMainForm is the big No-No. WindowsFormsApplicationBase takes over the ApplicationRun when OnCreateMainForm returns so in my case I only returned from OnCreateMainForm when MainForm already were disposed hence the exception :(
protected override void OnCreateMainForm()
{
string[] args = Environment.GetCommandLineArgs();
try {
MainView mainView = new MainView(args);
this.MainForm = mainView;
Application.EnableVisualStyles();
}...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to debug specific file with gdb? I have to cpp files (main and functions) and I make them to build a exe file (code) and two object files (main.o and functions.o).
How can I debug specific file "functions.cpp" from gdb command line?
A: You need to compile your files with gcc's -g3 option. After this start gdb <exename>. You can then set breakpoint in your file inside gdb by something like b functions.cpp:36 if you want the exe to break on line 36 of functions.cpp. You can set breakpoints to particular function calls as well, such as b func(). Then run the program using r <options that exename takes>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to fire RowCommand for a GridView which is inside a Repeater? I have a Repeater and inside it a GridView. Now I want to to fire GridView's RowCommand. So can any one tell me how can it be?
A: What it sounds like you want to do is handle the RowCommand event in each of your GridViews.
One way to do this would be to create an event handler for the ItemCreated event in the Repeater control. In that event handler, you could then add the RowCommand event handler to each GridView using += syntax. So, if your RowCommand event handler method is called "GridView1_RowCommand", you could do this:
Repeater1_ItemCreated(Object Sender, RepeaterItemEventArgs e)
{
GridView tempGV = (GridView)e.Item.FindControl("GridView1");
tempGV += GridView1_RowComamnd;
}
Then, each time a RowCommand event is fired from one of your GridViews, the GridView_RowCommand event will be called.
A: Refer to this site, where a similar discussion is done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Skype iPhone app URL scheme I've been using the skype:username?call URL scheme to launch the Skype app directly into a call, and was about to implement the skype:username?chat URL scheme to launch it directoy into chat... although the chat scheme is not working at all on the iPhone, and other tests seem to indicate that the call scheme is currently the only one that actually does work out of the many others I've seen documentation for. I conducted a test a few weeks ago and could have sworn that the chat scheme WAS working, then I upgraded to their new app release and it's gone.
Was I just seeing things and it was never there? Or did it really just disappear in this latest release? I posted this to the Skype forums, which has still not recieved a single reply, and barely even any views, for over a week now.
Thanks.
A: Microsoft states in their Skype URI tutorial for iOS:
With the recent redesign of the Skype for iOS client, URIs are not
currently supported on the Skype for iOS 5.x branch.
Unfortunately, the Skype app still registers the skype: URL scheme (but doesn't actually do anything except launching the app) so we can't even check if the problem has been resolved.
A: Have you tried it on a few devices and with different versions of the iOS Skype software?
It seems as though that should be working. I use handleopenurl often for looking up app specific url schemes and they seem to have the chat url you listed under their listing for skype.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Adding a product using Savon to connect to Magento API I have got the code working for listing products in Ruby but am struggling to add a product, here is my code, I’m using the savon gem for HTTP/SOAP requests, based on the code here http://www.polyvision.org/2011/10/02/using-magento-soap-api-with-ruby-and-savon/
# Insert some products ...
newproductdata = [
["name" , “test product"],
["websites" , [1]],
["short_description" , ‘short description’],
["description" , ‘description’],
["status" , 1],
["weight" , 0],
["tax_class_id" , 1],
["categories" , [3]],
["price" , 12.05]
]
begin
response = client.request :call do
soap.body = {:session => session, :method => “product.create”, :arguments => ["simple", 1, “testsku1”, newproductdata]}
end
rescue Savon::SOAP::Fault => fault
puts “*****#{fault.to_s}*****”
end
I think the issue is the passing in of :arguments which perhaps needs to be named correctly, this code generates the error,
(SOAP-ENV:Client) Error cannot find parameter
A: you are mixing array- [] and hash-syntax {}
that's why you get a SYNTAX error (there is no COMPILATION step in ruby)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I delete an embedded doc from Mongoid? I'm having some issues deleting my document using Mongoid...
The code actually does delete the gallery, but I get a browser error which looks like:
Mongoid::Errors::DocumentNotFound at /admin/galleries/delete/4e897ce07df6d15a5e000001
The suspect code is below:
def self.removeGalleryFor(user_session_id, gallery_id)
person = Person.any_in(session_ids: [user_session_id])
return false if person.count != 1
return false if person[0].userContent.nil?
return false if person[0].userContent.galleries.empty?
gallery = person[0].userContent.galleries.find(gallery_id) #ERROR is on this line
gallery.delete if !gallery.nil?
end
My Person class embeds one userContent which embeds many galleries.
Strangely enough I've got a couple of tests around this which work fine...
I'm really not sure what's happening - my gallery seems to be found fine, and is even deleted from Mongo.
Any ideas?
A: find throws an error if it can't find a document with the given id. Instead of checking presence of given gallery and returning nil if it doesn't exist, you directly ask mongodb while querying to remove any such gallery.
def self.remove_gallery_for(user_session_id, gallery_id)
user_session_id = BSON::ObjectId.from_string(user_session_id) if user_session_id.is_a?(String)
gallery_id = BSON::ObjectId.from_string(gallery_id) if gallery_id.is_a?(String)
# dropping to mongo collection object wrapped by mongoid,
# as I don't know how to do it using mongoid's convenience methods
last_error = Person.collection.update(
# only remove gallery for user matching user_session_id
{"session_ids" => user_session_id},
# remove gallery if there exists any
{"$pull" => {:userContent.galleries => {:gallery_id => gallery_id}}},
# [optional] check if successfully removed the gallery
:safe => true
)
return last_error["err"].nil?
end
This way you do not load the Person, you don't even get the data from monogdb to application server. Just get the gallery removed if it exists.
But you should prefer @fl00r's answer if you need to fire callbacks and switch to destroy instead of delete
A: def self.removeGalleryFor(user_session_id, gallery_id)
# person = Person.where(session_ids: user_session_id).first
person = Person.any_in(session_ids: [user_session_id])
if person && person.userContent && person.userContent.galleries.any?
gallery = person.userContent.galleries.where(id: gallery_id).first
gallery.delete if gallery
end
end
ps:
In Ruby usually under_score naming rather then CamelCase is used
A: Kudos to Rubish for pointing me to a solution that at least passes my tests - for some reason fl00r's code didn't work - it looks like it should, but doesn't for some reason...
Person.collection.update(
{"session_ids" => user_session_id},
{"$pull" => {'userContent.galleries' => {:_id => gallery_id}}},
:safe => true
)
=> this code will pass my tests, but then once it's running in sinatra it doesn't work.... so frustrating!
have posted this code with tests on github https://github.com/LouisSayers/bugFixes/tree/master/mongoDelete
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I make my repository remove child entities and not just navigation properties from my aggregate root I'm trying to build a functioning repository using Entity Framework. I feel like I'm missing something really obvious somewhere. Lets say I have IRepository<Person> which has many Address in an ICollection<Address> Addresses.
When I call Person.Addressess.Remove(sameAddress) I understand this will only remove the navigation (in this case will try to set the PersonID column to null in the database).
The issue is I want to delete it somehow from the aggregate root, so I can just send the Person object to my repository like so personRepository.Update(person) and not have to manually delete the address or create a address repository.
Perhaps I'm searching for the wrong thing but I would have thought this was a common issue, yet I can't seem to find anything on line.
A: Looks like a future EF release might allow what you're asking for:
http://blogs.msdn.com/b/dsimmons/archive/2010/01/31/deleting-foreign-key-relationships-in-ef4.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Less.js - strong nested rules? I love the ability of less.js to make nested rules. For example
.A{
.B{
width:50px;
}
}
which results in
.A .B{
width:50px;
}
But is there a way to make it result in this:
.A > .B{
width:50px;
}
I´ve already tried to do this:
.A{
&>.B{
width:50px;
}
}
But it does not work...
Thanks!
A: It's as simple as this:
.A {
> .B {
width: 50px;
}
}
Another related question: Immediate Child selector in LESS
Some documentation: http://lesscss.org/features/#features-overview-feature-nested-rules
(doesn't actually include relevant example)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: split with no argument in perl I'm new to perl, and I wonder what this line of code mean?
($q,$dummy, $d,$v) = split;
I search through google, but i found no explanation of using split without argument, does this kind of use related to the "while" block?
And the full code fragment is:
open(T,"$opt_judgments") || die "can't open judgment file: $opt_judgments\n";
while (<T>) {
if ($opt_trec) {
($q,$dummy, $d,$v) = split;
} else {
($q,$d,$v) = split;
}
$dict{$q ."=".$d} =$v;
if ($v != 0) {
$totalRels{$q} ++;
}
}
A: From perldoc:
The general syntax of split is:
split /PATTERN/,EXPR
If EXPR is omitted, it splits the $_ string.
If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace). Anything matching PATTERN is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.)
Since in your case both PATTERN and EXPR are omitted. A split of $_ on whitespace occurs and the first four pieces of the split are assigned to $q, $dummy, $d and $v respectively.
A: It splits the current line ($_) on whitespace. Quoting the manual:
If EXPR is omitted, splits the $_ string. If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Oracle PL/SQL: syntax error when using a variable within SAMPLE clause The following PL/SQL block works:
DECLARE
r TABLE1%ROWTYPE;
BEGIN
SELECT * INTO r FROM TABLE1 SAMPLE(1) WHERE ROWNUM = 1;
END;
However, when I try to replace the literal with a variable within the SAMPLE clause, Oracle returns a syntax error:
DECLARE
s NUMBER;
r TABLE1%ROWTYPE;
BEGIN
s := 1;
SELECT * INTO r FROM TABLE1 SAMPLE(s) WHERE ROWNUM = 1;
END;
ORA-06550: line 6, column 39:
PL/SQL: ORA-00933: SQL command not properly ended
What am I doing wrong?
I'm using Oracle 10 and SQL Developer.
(These are simplified examples. What I'm actually trying to do in practice is to optimize the selection of random row, where SAMPLE percentage would be calculated dynamically, based on the current number of rows in the table. So I can't use literal, I need a variable to assign the result of the calculation.)
A: The SAMPLE synthax requires a numeral. You could use dynamic SQL to build a dynamic query, for example with a ref cursor:
SQL> CREATE TABLE table1 AS
2 SELECT ROWNUM ID, rpad(ROWNUM, 10, 'x') DATA
3 FROM dual CONNECT BY LEVEL <= 1000;
Table created
SQL> DECLARE
2 l_cur SYS_REFCURSOR;
3 l_row table1%ROWTYPE;
4 l_pct NUMBER := 50;
5 BEGIN
6 OPEN l_cur
7 FOR 'SELECT * FROM table1 SAMPLE('||l_pct||') WHERE rownum = 1';
8 LOOP
9 FETCH l_cur INTO l_row;
10 EXIT WHEN l_cur%NOTFOUND;
11 dbms_output.put_line(l_row.id);
12 END LOOP;
13 END;
14 /
3
PL/SQL procedure successfully completed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP - Fast way to strip all characters not displayable in browser from utf8 string I've got a little messy database containing names of many institutions around the world.
I want to display them including national characters, but without invalid characters - those displayed in firefox as unicode numbers.
How to filter them out?
Database has utf8 encoding, but some strings were inserted with wrong encodings or were a mess already in sources.
I do not want to fix the database - it's too big. I want to just filter it out - "out of sight out of mind"
A:
I want to just filter it out
You have got an unspecified encoding/charset with your data. This is a huge problem.
You can first try to convert it into utf-8 and then strip all non-printable characters:
$str = iconv('utf-8', 'utf-8//ignore', $str);
echo preg_replace('/[^\pL\pN\pP\pS\pZ]/u', '', $str);
The problem is, that the iconv function can only try. It will drop any invalid character sequence. As of php 5.4 it will drop the complete string however, if the input encoding specified is invalid.
You will see a warning since PHP 5.3 already that the input string has an invalid encoding.
You can go around this by removing all invalid utf-8 byte sequences first:
$str = valid_utf8_bytes($str);
echo preg_replace('/[^\pL\pN\pP\pS\pZ]/u', '', $str);
/**
* get valid utf-8 byte squences
*
* take over all matching bytes, drop an invalid sequence until first
* non-matching byte.
*
* @param string $str
* @return string
*/
function valid_utf8_bytes($str)
{
$return = '';
$length = strlen($str);
$invalid = array_flip(array("\xEF\xBF\xBF" /* U-FFFF */, "\xEF\xBF\xBE" /* U-FFFE */));
for ($i=0; $i < $length; $i++)
{
$c = ord($str[$o=$i]);
if ($c < 0x80) $n=0; # 0bbbbbbb
elseif (($c & 0xE0) === 0xC0) $n=1; # 110bbbbb
elseif (($c & 0xF0) === 0xE0) $n=2; # 1110bbbb
elseif (($c & 0xF8) === 0xF0) $n=3; # 11110bbb
elseif (($c & 0xFC) === 0xF8) $n=4; # 111110bb
else continue; # Does not match
for ($j=++$n; --$j;) # n bytes matching 10bbbbbb follow ?
if ((++$i === $length) || ((ord($str[$i]) & 0xC0) != 0x80))
continue 2
;
$match = substr($str, $o, $n);
if ($n === 3 && isset($invalid[$match])) # test invalid sequences
continue;
$return .= $match;
}
return $return;
}
A: The database might not be the problem entirely - if the tables are utf8 encoded the strings in them should have been converted (I think). The issue I've ran into with this has been a matter of correctly ensuring the encoding is consistent. For instance the mysqli connector, by default, reverts to Latin-8859 IIRC so it's quite possible to have the output in utf8, the database in utf8 and still end up with ? characters because they're converted to Latin by the mysqli connector.
To ensure utf8 across the board you need to do something like:
In the database:
ensure the collation is something like utf8_general_ci
At the top of the PHP view file:
<?php header('Content-Type:Text/Plain;charset=utf-8'); ?>
In the HTML meta tag (optional):
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
AND in the database connector (using MySQLi as an example):
mysqli::set_charset('utf8'); #note that for MySQL it isn't hyphenated
You might find that resolves the problem anyway.
A: If the database is the issue which it seems to be in your case (and fixing it is out of the way) then maybe just print out each character from the string using ORD and find the value for the control character that is not well sent.
Then when you know the control character value, pass these values into a function that searches for that control character and try to change the utf-8 encoding (the flawed one) with corresponding UTF8 characters live.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there an equivalent of Sql Server's DateDiff('ms', d1, d2) in Sqlite? I am trying to fathom if it is possible to calculate the number of elapsed milliseconds between dates in Sqlite. ( DateDiff('milliseconds', d1, d2) in SQL Server)
There's a great example on how to do it for seconds here, but not for milliseconds.
A: You can get there.
Given these 2 dates: 12:00:00:000 & 12:05:01:200
( (
(strftime('%M', EndDate) * 60) -
(strftime('%M', StartDate) * 60)
) +
strftime('%f', EndDate) -
strftime('%f', StartDate)
) * 1000
results in a diff off 301200 (milliseconds)
The key is getting your head around the fact that %f yields seconds and milliseconds as a fraction of seconds (1.2), and you need to add that onto the total seconds in the minutes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mocking Windows Installer Is it possible to mock the Windows Installer? I would like to set up tests for various scenarios during install. I don't really care what is stored in the Windows Installer databases, I just want to test the output of the installer packages (what files have changed, etc).
Edit
I suppose I could setup VMWare images and script them. Does anybody know how to script/automate tasks in VMWare instances?
A: Yes, it's possible. You need two things:
*
*A setup authoring tool which can generate the packages. A command line interface or scriptable solution would be great for automation.
*A resource monitor which determines what each installation does. You can use Process Monitor or another tool which monitors files and registry.
As an optional feature I would also suggest a log parser. This way you can create a verbose log for each installation and analyze the log to see what it did to the target machine.
A: There is no way to mock MSI. You either trust that it works and evaluate the data in the MSI to predict what will happen or you use infrastructure automation to spin up machines and execute the installer then run tests to confirm the expected behavior.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: C# RegEx to create string array split on spaces and phrases (in quotes)
Possible Duplicate:
Regular Expression to split on spaces unless in quotes
I am dealing with various strings that I need to split into an array wherever there is a space, except for if that space exists within "quotes".
So for example, I would like this:
this is "a simple" test
..to become:
[0] = this
[1] = is
[2] = "a simple"
[3] = test
Note I would like to retain the quotes surrounding the phrase, not remove them.
A: The regex:
".*?"|[^\s]+
Usage:
String input = @"this is ""a simple"" test";
String[] matches =
Regex.Matches(input, @""".*?""|[^\s]+").Cast<Match>().Select(m => m.Value).ToArray();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML storage in Java I want to download an HTML page, extract some used full text out of this HTML and convert the HTML to PDF then store the useful text and PDF in a noSQL solution.
What is the most efficient way to pass the HTML to the modules which extract useful text and the module which creates the PDF. I don't want to download the same HTML twice.
One way to store the HTML is to download the HTML to a local disk under a unique named folder and pass the path to other modules so that they can process the HTML.
This approach doesn't looks that good to me, as there is implementation overhead.
I would love to see the entire HTML as a single variable so I can give it to other modules so they can traverse the HTML without loading it. One idea that crossed my mind is to download and zip the HTML and related code/pics then store the binary in a byte[].
A: I haven't used these before but a quick Type search on eclipse with the text html gave me this:
Class HTMLDocument
From the docs :
A document that models HTML. The purpose of this model is to support both browsing and editing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simplest way for implementing an extremly simple Server? (C#) I'm currently writing a simple application for some friends of mine.
There is a pretty small part which contains some client-server communication. Protocolls like http are far to overloaded with unnecessary stuff I don't need.
Here is all the communication I need to implement:
(Request -> Response)
* {AccountID} -> {AccountBalance}
* {AccountID,newBalance} -> {AccountBalance}
* {AccountID,ItemID,Amount} -> {AccountBalance}
* {ItemID} -> {ItemValue}
All values are integer. AccountIDs and ItemIDs are distinguished. AccountBalances and ItemValues are always positiv.
Since the application will only be used in a private LAN security is not important.
I already tried using a httpListener for that, but it seems like it wasn't suitable for my needs.
A: You should consider providing these methods over WCF. That is the simplest way to achieve what you want.
See A Simple Sample: WCF Service
A: You could also write your own TCP based server/client - it's quite simple to do in C#.
This makes for a reasonable exmple, then you can customize it to your needs:
http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server
A: As note in the answer from Hasan WCF is the fastest and easiest protocol to implement.
If you want something lower level and parse bits and bytes yourself TcpClient is the way to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Print xml in pdf using itext I want to print xml in pdf using itext in java, as well formatted and displayed in color and indention as well like shown in notepad++,
any api or suggestion regarding this?
A: I have converted XHTML to pdf, via iText, using flying saucer for the rendering (previously xhtml renderer).
http://code.google.com/p/flying-saucer/
You can format using CSS, though I do remember it's slightly temperamental, however you can tweak it to get what you want, and end up with something nicely formatted.
I wasn't sure whet you meant regarding Notepad++ - I don't have PDF support there, just opens as Binary file contents, unless there is a PDF plugin you use?
::Answer updated after comments below.
Thanks for the comment, I understand the question much better now. I thought you wanted to output the data in the XML in the PDF, now I understand you want to see the raw XML itself in the PDF, formatted as you'd see XML formatted in Notepad, colours and all.
XML is a markup language designed to describe data, so you want to get this into a language that can descibe the presentation and style as well as the data. I'd suggest
1) Convert the XML to XHTML - so all the XML (tags, attributes) is your content, and you have classes describing each type (for example, attribute names, attribute values, starter tag, end tag). I don't know if you can use an XSLT library to transform it this way, oterwise you can write something yourself in Java, walking through the DOM and output it in the way you want. This way you can
2) Create CSS to style your classes as you want - e.g. have all attribute names as text color "red"
3) Use iText and flying saucer as above to convert the XHTML and CSS into PDF using Java, as described in original answer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CakePHP route '/*' breaking access to subfolders I'm just starting with CakePHP and I have a question.
The idea is to have URLs like this:
domain.tld/some-title-of-a-page
...and it should open "page" controller with "show" action and some-title-of-a-page as a parameter. What I did in routes.php is:
Router::connect('/*', array('controller' => 'page', 'action' => 'show'));
The problem is that I'm unable to read my /css/layout.css file, because it's being parsed as a page with such a title by CakePHP. So what's the recipe for this cake?
Edit: Wrong location. The CSS folder should be in app/webroot, not in the web root of the host.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use setOptions method of select field with a store I can use the setOptions method to successfully specify the options of a select field as follows:
setOptions(
[ {text: 'First Option', value: 'first'},
{text: 'Second Option', value: 'second'},
{text: 'Third Option', value: 'third'}
])
However, I would instead like setOptions to work with a loaded data store rather than hard coding the text/value array like above.
The store has one item type in it 'vehicle' and the json response from the server which loads it is of the form {'vehicle' :'mercedes'}, {'vehicle' 'jaguar'} (ignore if I have the json syntax wrong, am typing this from memory. And finally, I would be fine with having the value field being the same as the text field for setOptions.
However, I am stumped how to accomplish this. Many thanks to anyone who can help me.
A: Use this:
{ id: 'theSelect',
name: 'vechicleSelect',
xtype: 'selectfield',
store: storeObejct,
displayField: 'vehicle',
valueField: 'vehicle'
}
Read the whole API here Sencha Touch selectfield
A: You could cycle through the store and push the data into an array then use the array as the argument for setOptions.
A: To add to warmachine's answer...
In your view:
{
xtype: 'selectfield',
id: 'NameId',
label: 'Name',
labelWrap: true,
placeHolder: 'name'
},
Controller or initialize function in your view:
initialize: function(){
var me = this;
me.callParent(arguments);
var sto= Ext.getStore('Persons');
sto.load();
var options = [];
sto.each(function(record){
options.push({
value: record.get('displayname'),
text: record.get('displayname')
});
});
var box = Ext.ComponentQuery.query('#NameId')[0];
box.setOptions(options);
},
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Detect CSS3 with JQuery Is there a way to detect whether a browser supports CSS3 transitions (-webkit-, -moz-, etc..) with JQuery?
A: You can use Modernizr css rule:
.csstransitions {
}
You can also use Isotope to achieve full hardware acceleration when possible, falling back to jQuery-based animation otherwise.
A: You can go for Modernizr to detect those as well as many other features you want to detect.
Note: You could also download custom version of Modernizr for the features you want to detect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Unauthorised access exception when Uploading photo to picasa in WP7 I have the following code which tries to upload the picture to picasa website. when I m trying to upload I m getting Unauthorised access exception. I dont know how to get the AuthToken.
Here is my code . Please let me know if you have any clues.
public delegate void UploadPhotoCallback(bool success, string message);
public static void UploadPhoto(string albumId, string originalFileName, byte[] photo, UploadPhotoCallback callback)
{
string Username = "mailmugu";
string AuthToken = "";
try
{
var url = string.Format("http://picasaweb.google.com/data/feed/api/user/{0}/albumid/{1}", Username, albumId);
var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
//request.ContentType = HttpFormPost.ImageJpeg;
//request.Method = HttpMethods.Post;
request.ContentType = "image/jpeg";
request.Method = "POST";
request.Headers[HttpRequestHeader.Authorization] = "GoogleLogin auth=" + AuthToken;
request.BeginGetRequestStream(new AsyncCallback(UploadGetRequestCallback),
new UploadRequestState
{
Request = request,
Callback = callback,
Photo = photo,
FileName = originalFileName
});
}
catch (Exception e)
{
Console.WriteLine(e);
//throw new MyException(MyResources.ErrorUploadingPhotoMessage, e);
}
}
private static void UploadGetRequestCallback(IAsyncResult ar)
{
try
{
var state = (UploadRequestState)ar.AsyncState;
HttpWebRequest request = state.Request;
// End the operation
var stream = request.EndGetRequestStream(ar);
stream.Write(state.Photo, 0, state.Photo.Length);
stream.Close();
request.BeginGetResponse(UploadGetResponseCallback, state);
}
catch (Exception e)
{
//throw new MyException(MyResources.ErrorUploadingPhotoMessage, e);
}
}
private static void UploadGetResponseCallback(IAsyncResult ar)
{
UploadRequestState state = null;
try
{
state = (UploadRequestState)ar.AsyncState;
HttpWebRequest request = state.Request;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
if (response != null)
{
response.Close();
}
if (state.Callback != null)
{
MessageBox.Show("Uploaded Sucessfully");
//state.Callback(true, MyResources.PhotosUploadedMessage);
}
}
catch (Exception e)
{
MessageBox.Show("Error" + e.Message);
Console.Write(e);
//if (state != null && state.Callback != null)
//state.Callback(false, MyResources.ErrorSavingImageMessage);
}
}
public class UploadRequestState
{
public HttpWebRequest Request { get; set; }
public UploadPhotoCallback Callback { get; set; }
public byte[] Photo { get; set; }
public string FileName { get; set; }
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string albumId = "Picasa";
string Filename = "Test";
UploadRequestState _uploadReq = new UploadRequestState();
Uri myuri = new Uri("/Images/Test.jpg", UriKind.RelativeOrAbsolute);
BitmapImage btmMap = new BitmapImage(myuri);
image1.Source=btmMap;
WriteableBitmap bmp = new WriteableBitmap(btmMap.PixelWidth,btmMap.PixelHeight);
MemoryStream ms = new MemoryStream();
// write an image into the stream
Extensions.SaveJpeg(bmp, ms,
btmMap.PixelWidth, btmMap.PixelHeight, 0, 100);
byte[] Photo = ms.ToArray();
UploadPhoto(albumId,Filename,Photo,_uploadReq.Callback);
}
}
}
A: Since your code does not even attempt to get the Authentication Token required to do what you want I suggest looking at http://code.google.com/apis/picasaweb/docs/2.0/developers_guide_protocol.html#Auth and open a new question to address any concerns you might have.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Codeigniter image is not cropping I tried the following code to crop an image in codeigniter but it did not work. Might be I am missing minute thing. Helper is loaded and the image is also exists
The code is
public function cropAndSave(){
$config['image_library'] = 'gd2';
$config['allowed_types'] = 'gif|jpg|png';
$config['source_image'] = './img-lab/xxx.jpg';
$config['create_thumb'] = true;
$config['maintain_ratio'] = false;
$config['width'] = 150;
$config['height'] = 190;
$config['new_image'] = "thumb_shahid.jpg";
$this->load->library('image_lib', $config);
$this->image_lib->resize();
echo '
<script>
window.parent.location="'. base_url().'"
</script>
';
}
A: Call the initialize() function instead of load() because your image library already loaded
public function cropAndSave(){
$config['image_library'] = 'gd2';
$config['allowed_types'] = 'gif|jpg|png';
$config['source_image'] = './img-lab/xxx.jpg';
$config['create_thumb'] = true;
$config['maintain_ratio'] = false;
$config['width'] = 150;
$config['height'] = 190;
$config['new_image'] = "thumb_shahid.jpg";
$this->image_lib->initialize($config);
$this->image_lib->resize();
echo '
<script>
window.parent.location="'. base_url().'"
</script>
';
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save OpenGL Rendering to Video I have an OpenGL game, and I want to save what's shown on the screen to a video.
How can I do that? Is there any library or how-to-do-it?
I don't care about compression, I need the most efficient way so hopefully the FPS won't drop.
EDIT:
It's OpenGL 1.1 and it's working on Mac OSX though I need it to be portable.
A: There most certainly are great video capture software out there you could use to capture your screen, even when running a full screen OpenGL game.
If you are using new versions of OpenGL, as genpfault has mentioned you can use PBOs. If you are using legacy OpenGL (version 1.x), here's how you can capture the screen:
glFinish(); // Make sure everything is drawn
glReadBuffer(GL_FRONT);
glPixelStorei(GL_PACK_ALIGNMENT, 4);
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
glReadPixels(blx, bly, w, h, mode, GL_UNSIGNED_BYTE, GL_BGRA);
where blx and bly are the bottom left coordinates of the part of the screen you want to capture (in your case (0, 0)) and w and h are the width and height of the box to be captured. See the reference for glReadPixels for more info, such as the last parameter.
Writing captured screen (at your desired rate, for example 24 fps) to a video file is a simple matter of choosing the file format you want (for example raw video), write the header of the video and write the images (image by image if raw, or image differences in some other format etc)
A: Use Pixel Buffer Objects (PBOs).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Where can I find a comprehensive Javascript iframe programming reference? There is a part of my web application that might end up making heavy use of iframes (to be able to serve arbritrary content from elsewhere). I know there are many cross-domain and cross-browser quirks I need to worry about so is there any reference out there that has everything I need in one place? Is there an "iframe Bible"?
A: This is certainly not an iframe bible, but it's worth a read:
http://www.dyn-web.com/tutorials/iframes/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Making an unsigned sis - error: No rule to make target `unsigned_sis'. Stop I'm trying to make an unsigned sis package of my application, however I get the aforementioned error from QtCreator.
What am I doing wrong?
Best regards
A: I've got the same problem with Qt 4.6.3. Qt 4.7.3 creates unsigned .sis files without any issues, but 4.6.x doesn't. If the version of Qt isn't important for you, upgrade to 4.7.
I'm looking for another way to solve this, because I want to support old devices that don't work with Qt 4.7
UPD:
I found two ways to create unsigned sis:
*
*Create a signed sis file with QtCreator and remove signature with Syscontents tool
*Copy template .pkg, edit it a bit and create sis with makesis commandline tool.
I used the second way, because I use localized installation file. Localized installations work bad in Qt 4.6.3 out of box, so I had to create custom .pkg file
A: You can't install unsigned application to the phone. Try to sign it and see if it works better
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP abstract properties Is there any way to define abstract class properties in PHP?
abstract class Foo_Abstract {
abstract public $tablename;
}
class Foo extends Foo_Abstract {
//Foo must 'implement' $property
public $tablename = 'users';
}
A: I've asked myself the same question today, and I'd like to add my two cents.
The reason we would like abstract properties is to make sure that subclasses define them and throw exceptions when they don't. In my specific case, I needed something that could work with statically.
Ideally I would like something like this:
abstract class A {
abstract protected static $prop;
}
class B extends A {
protected static $prop = 'B prop'; // $prop defined, B loads successfully
}
class C extends A {
// throws an exception when loading C for the first time because $prop
// is not defined.
}
I ended up with this implementation
abstract class A
{
// no $prop definition in A!
public static final function getProp()
{
return static::$prop;
}
}
class B extends A
{
protected static $prop = 'B prop';
}
class C extends A
{
}
As you can see, in A I don't define $prop, but I use it in a static getter. Therefore, the following code works
B::getProp();
// => 'B prop'
$b = new B();
$b->getProp();
// => 'B prop'
In C, on the other hand, I don't define $prop, so I get exceptions:
C::getProp();
// => Exception!
$c = new C();
$c->getProp();
// => Exception!
I must call the getProp() method to get the exception and I can't get it on class loading, but it is quite close to the desired behavior, at least in my case.
I define getProp() as final to avoid that some smart guy (aka myself in 6 months) is tempted to do
class D extends A {
public static function getProp() {
// really smart
}
}
D::getProp();
// => no exception...
A: No, there is no way to enforce that with the compiler, you'd have to use run-time checks (say, in the constructor) for the $tablename variable, e.g.:
class Foo_Abstract {
public final function __construct(/*whatever*/) {
if(!isset($this->tablename))
throw new LogicException(get_class($this) . ' must have a $tablename');
}
}
To enforce this for all derived classes of Foo_Abstract you would have to make Foo_Abstract's constructor final, preventing overriding.
You could declare an abstract getter instead:
abstract class Foo_Abstract {
abstract public function get_tablename();
}
class Foo extends Foo_Abstract {
protected $tablename = 'tablename';
public function get_tablename() {
return $this->tablename;
}
}
A: As you could have found out by just testing your code:
Fatal error: Properties cannot be declared abstract in ... on line 3
No, there is not. Properties cannot be declared abstract in PHP.
However you can implement a getter/setter function abstract, this might be what you're looking for.
Properties aren't implemented (especially public properties), they just exist (or not):
$foo = new Foo;
$foo->publicProperty = 'Bar';
A: Depending on the context of the property, if I want to force declaration of an abstract class property in an extended class, I like to use a constant with the static keyword for the property in the abstract object constructor or setter/getter methods. You can optionally use final to prevent the method from being overridden in extended classes.
Example: https://3v4l.org/WH5Xl
abstract class AbstractFoo
{
public $bar;
final public function __construct()
{
$this->bar = static::BAR;
}
}
class Foo extends AbstractFoo
{
//const BAR = 'foobar'; //uncomment to prevent exception
}
$foo = new Foo();
//Fatal Error: Undefined class constant 'BAR'
However, the extended class overrides the parent class properties and methods if redefined.
For example; if a property is declared as protected in the parent and redefined as public in the extended class, the resulting property is public. Otherwise, if the property is declared private in the parent it will remain private and not available to the extended class.
http://www.php.net//manual/en/language.oop5.static.php
A: PHP 7 makes it quite a bit easier for making abstract "properties". Just as above, you will make them by creating abstract functions, but with PHP 7 you can define the return type for that function, which makes things a lot easier when you're building a base class that anyone can extend.
<?php
abstract class FooBase {
abstract public function FooProp(): string;
abstract public function BarProp(): BarClass;
public function foo() {
return $this->FooProp();
}
public function bar() {
return $this->BarProp()->name();
}
}
class BarClass {
public function name() {
return 'Bar!';
}
}
class FooClass extends FooBase {
public function FooProp(): string {
return 'Foo!';
}
public function BarProp(): BarClass {
// This would not work:
// return 'not working';
// But this will!
return new BarClass();
}
}
$test = new FooClass();
echo $test->foo() . PHP_EOL;
echo $test->bar() . PHP_EOL;
A: As stated above, there is no such exact definition.
I, however, use this simple workaround to force the child class to define the "abstract" property:
abstract class Father
{
public $name;
abstract protected function setName(); // now every child class must declare this
// function and thus declare the property
public function __construct()
{
$this->setName();
}
}
class Son extends Father
{
protected function setName()
{
$this->name = "son";
}
function __construct(){
parent::__construct();
}
}
A: There is no such thing as defining a property.
You can only declare properties because they are containers of data reserved in memory on initialization.
A function on the other hand can be declared (types, name, parameters) without being defined (function body missing) and thus, can be made abstract.
"Abstract" only indicates that something was declared but not defined and therefore before using it, you need to define it or it becomes useless.
A: The need for abstract properties can indicate design problems. While many of answers implement kind of Template method pattern and it works, it always looks kind of strange.
Let's take a look at the original example:
abstract class Foo_Abstract {
abstract public $tablename;
}
class Foo extends Foo_Abstract {
//Foo must 'implement' $property
public $tablename = 'users';
}
To mark something abstract is to indicate it a must-have thing. Well, a must-have value (in this case) is a required dependency, so it should be passed to the constructor during instantiation:
class Table
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function name(): string
{
return $this->name;
}
}
Then if you actually want a more concrete named class you can inherit like so:
final class UsersTable extends Table
{
public function __construct()
{
parent::__construct('users');
}
}
This can be useful if you use DI container and have to pass different tables for different objects.
A: if tablename value will never change during the object's lifetime, following will be a simple yet safe implementation.
abstract class Foo_Abstract {
abstract protected function getTablename();
public function showTableName()
{
echo 'my table name is '.$this->getTablename();
}
}
class Foo extends Foo_Abstract {
//Foo must 'implement' getTablename()
protected function getTablename()
{
return 'users';
}
}
the key here is that the string value 'users' is specified and returned directly in getTablename() in child class implementation. The function mimics a "readonly" property.
This is fairly similar to a solution posted earlier on which uses an additional variable. I also like Marco's solution though it can be a bit more complicated.
A: Just define the property in the base class without assigning it a (default) value.
Getting the property value without redefining it with a default value or assigning it a value will throw an Error.
<?php
class Base {
protected string $name;
public function i_am() : string {
return $this->name;
}
}
class Wrong extends Base {
...
}
class Good extends Base {
protected string $name = 'Somebody';
}
$test = new Good();
echo $test->i_am(), '<br>'; // Will show "Nobody"
$test = new Wrong();
echo $test->i_am(), '<br>'; // Will throw an Error:
// Error: Typed property Base::$name must not be accessed before initialization in ....
?>
A: You can define a static property in an abstract class.
<?php
abstract class Foo {
private static $bar = "1234";
public static function func() {
echo self::$bar;
}
}
Foo::func(); // It will be printed 1234
A: Too late to answer the question, but you may use the difference between self and static as follows
<?php
class A { // Base Class
protected static $name = 'ClassA';
public static function getSelfName() {
return self::$name;
}
public static function getStaticName() {
return static::$name;
}
}
class B extends A {
protected static $name = 'ClassB';
}
echo A::getSelfName(); // ClassA
echo A::getStaticName(); // ClassA
echo B::getSelfName(); // ClassA
echo B::getStaticName(); // ClassB
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "147"
} |
Q: Resolving a MATLAB class method handle using the method name alone I'm trying to call a method within a class, assuming I only know its name (aka, a char vector with its name)
I tried calling str2func(['obj.' functionName]) - where functionName is the name of that method, without any luck - I can't seem to grab the handle of the method.
A: You can reference it like a field
obj.(functionName)
or using feval
feval(functionName, obj, ...)
I recommend the first option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Filtering one collection to many listboxes I have a ViewModel:
public class VM
{
public ObservableCollction<PersonRole> PersonRoles { get; private set; }
}
public class PersonRole
{
public int RoleID { get; set; }
//..
}
In View I have to display three ListBoxes:
*
*all persons with RoleID == 1
*all persons with RoleID == 2
*all persons with RoleID == 3
How it's better to do?
*
*Create 3 properties in ViewModel with filtering:
Roles1 = CollectionViewSource.GetDefaultView(PersonRoles);
Roles1.Filter = o => ((PersonRole)o).RoleID == 1;
*Some possibilities to do this in XAML? How?
*More options?
A: Depending on how often you expect the data in the list to change, I would probably go with ICollectionView instances as you suggest. You won't be able to use CollectionViewSource.GetDefaultView for 3 separate properties, however, as it will return the same object instance every time. Instead, you'll need to explicitly create new ICollectionViews:
this.Property1 = new ListCollectionView(this.PersonRoles);
this.Property2 = new ListCollectionView(this.PersonRoles);
this.Property3 = new ListCollectionView(this.PersonRoles);
// then set up filters
Alternatively, if the data in the list is only going to change very rarely, it might be better to do the filtering using LINQ when you actually populate the list and actually store 3 collections:
this.Property1 = new ObservableCollection<PersonRole>(dataSource.Where(o => o.RoleID=1);
this.Property2 = new ObservableCollection<PersonRole>(dataSource.Where(o => o.RoleID=2);
//etc
This approach is not particularly good if you expect items to be added to and removed from the overall list with any regularity though, as it will mean that you need to manually keep all 3 lists syncronised all the time.
As a final comment, you can set up collection views in XAML but you will not be able to filter them without some form of code behind.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unable to start webrick in windows xp i got this error while i try to start the webrick server on my windows xp.
←[31mCould not find eventmachine-0.12.10 in any of the sources←[0m
←[33mRun `bundle install` to install missing gems.←[0m
I've already did a 'bundle install'. Also tried to install mongrel but it's not helping!
Gemfile codes:
source 'http://rubygems.org'
gem 'rails', '3.0.10'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
#gem 'sqlite3'
group :production do
gem 'pg'
end
group :development, :test do
gem 'sqlite3'
end
gem 'thin'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
# gem 'ruby-debug19', :require => 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
# gem 'webrat'
# end
A: Try running these commands and then try rails s again.
gem install specific_install
gem specific_install -l http://github.com/eventmachine/eventmachine.git
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Alert after all checkboxes have been checked i have looked everywhere(but maybe i've missed something)
I'm currently creating a website where people have 3 options.
Let's do it easy, 1,2 and 3.
Now the customer wants a technique that after you clicked the third checkbox(doesn't matter in which way, you can go from 1 to 3 and then 2, or 3,1 and then 2) a alert popup comes up.
Now i have looked everywhere but i can't find it.
Hopefully someone inhere could help me.
Thanx already.
A: This should work, I think:
$('input:checkbox').change(
function(){
if ($('input:checkbox:checked').length == $('input:checkbox').length){
alert('All checkboxes are checked!');
}
});
JS Fiddle demo.
Edited in response to mblase75's (accurate) comment (below):
Of course this won't work if there are ANY other checkboxes on the page, but that can easily be solved by adding a class to the three checkboxes being monitored and selecting that instead.
The above can be easily adapted to apply to the children of a single element, regardless of how many of those elements are on the page:
$('input:checkbox').change(
function() {
var $formElement = $(this).closest('form');
if($formElement.find('input:checkbox:checked').length == $formElement.find('input:checkbox').length) {
alert('All checkboxes are checked!');
}
});
JS Fiddle demo.
Amending the $formElement = $(this).closest('form'); variable assignment to select another element, div, fieldset or, well, any other element, would allow you to target only those checkboxes within that given element.
References:
*
*:checkbox selector
*change()
*:checked selector
*length
*closest()
*find()
A: $("#cb1,#cb2,#cb3").change(function() {
if ($("#cb1").prop("checked") && $("#cb2").prop("checked") && $("#cb3").prop("checked")) {
alert("all three checked");
};
});
A: You could do
$('.yourchexkoboxes').click(function(){
var $chkboxs = $('.yourchexkoboxes').length;
var $CheckedChkboxs = $('.yourchexkoboxes:checked').length;
if($chkboxs === $CheckedChkboxs){
//all checkobexes have been checked
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Push Notifications wont work on distribution Ok now I have a problem with the push notifications. I have set them successfully for the developing part and I was receiving them on my device. Now I have the application on app store and I cant receave notifications.
This is step by step what I did:
-I have created a provisioning profile for distribution and connected it to the app id that has push notifications for distribution and development.
-I have built the app for distribution with that provisioning profile.
-I have submitted the app on app store.
-Now I have 2 certificates in keychain access Apple Production IOS Push Service:AppID and iPhone Distribution:CompanyName
-I have made .pem file from both and tested it with both. No notification has arrived
I really have no idea what to try and how to fix this.
A: I have had similar problems, just a few weeks ago. For me the case was that I had several provisioning profiles left in xCode. So what I needed to do was:
*
*Go to Organizer -> Devices -> Provisioning Profiles
*Select my distribution profiles for the app in question, and delete them.
*Go to developer.apple.com/iOS
*Go to the distribution profile, modify it.
*Just clicked "select all" (so I could re-save it with no changes), somehow the profile needed to be re-created AFTER enabling the Push certificate
*Download the new profile and install it to xCode
*Clean project under Product -> Clean
Now I made a new release and tested it and it worked. Maybe this workes for you as well.
Edit
The red-thread in this answer is that when Push notification in the App is enabled, the provisioning profiles need to be re-done (even though, to the eye there are no changes).
A: If using Parse, make sure you have uploaded your iOS Production Certificate. I ran into this issue and discovered a week later that I had only uploaded my iOS Development Certs to the server.
Settings > Push > Apple Push Certificates
You need to see something that has a Certificate Type of iOS Production with a valid expiration date.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: json_decode - malformed JSON from AJAX Request I am building a request in Flash that contains a JSON encoded Array of Objects. This is encoded using as3corelib. The request is then passed to JavaScript via ExternalInterface and a jquery ajax call sends the request off to the server.
In PHP, the incoming data is parsed, but the json_decode returns null, giving a Malformed JSON error. var_dump results in comments:
<?php
(isset($_POST['gdata']) && !empty($_POST['gdata'])) ? $gamedata = $_POST['gdata'] : returnError("game data not specified");
var_dump($gamedata); // (String) = string(37) "[{\"duration\":1,\"id\":\"game2\"}]"
$gamedata = json_decode(utf8_encode(trim($gamedata)),true);
var_dump($gamedata); // null
$gamedata = json_decode("[{\"duration\":1,\"id\":\"game2\"}]",true);
var_dump($gamedata);
/*
array(1) {
[0]=>
object(stdClass)#1 (2) {
["duration"]=>
int(1)
["id"]=>
string(7) "game2"
}
}
*/
?>
What I don't understand is that attempting to decode the variable returns null, but the same text decoded from a literal string works fine. What can I do to clean up the incoming data and make it readable for json_decode?
Edit: php_info() says that magic_quotes_gpc is enabled. Could that be the issue?
A: magic_quotes_gpc could be the issue, yes. And if you re-encode blindly w/o knowing the charset could be an issue as well.
So if you know magic_quotes_gpc is enabled, you need to strip slashes first.
For the charset, take care you know in which charset the incomming data is encoded, not that it's already utf-8 encoded and you assume it's latin-1 and convert it again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7634986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Isn't it redundant to declare the data type of an event object in a listener function's parameters? When you click on the button something happens. However it seems redundant to me that in the declaration of myListenerFunction, the event object e of class MouseEvent, actually has to have its data type MouseEvent mentioned.
mybutton.addEventListener(MouseEvent.CLICK, myListenerFunction);
function myListenerFunction(e:MouseEvent):void
{
// function body
}
Couldn't I get away with this (the .swf works just the same so far as I know...)?
function myListenerFunction(e):void
Since the data type of e should always match the class of the event MouseEvent.CLICK (which is MouseEvent)?
EDIT:
So let's say we go from a mouse event to a keyboard event. By not declaring the data type of e, we can not be prone to errors in not changing the data type of e. e by default is going to be of type KeyboardEvent
mybutton.addEventListener(KeyboardEvent.KEY_DOWN, myListenerFunction);
function myListenerFunction(e):void
{
// function body
}
A: You can keep the event type to the base class Event if you like. But you will not have access to any of the MouseEvent / KeyboardEvent-specific members when you do it like that.
Using it without a type will make it Object, which is dynamic, meaning you can try to access any member by name (even if it does not exist) - this is slower (a lot) and fairly error prone. You will not get compile time checking for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alternative to global variables in app delegate I am developing an application with a speedometer like animation (a meter and an arrow to indicate something on the meter). I store the arrow's position in a global variable declared in my app delegate. I am doing it this way because the arrow position is updated and used by several classes.
However, I am insecure whether this is a good or a bad design decision. My thoughts are that since it is a non-critical piece of information (just a float), no harm is done when storing it globally. But my OOP heart hurts every time I say the word "global" to myself.
Alternatively I have studiet singletons, but as far as I have read, singletons are used when the developer wishes to create one and only one instance of a certain object.
Am I doing it correct or is there a more proper way of doing what I do?
A:
I am doing it this way because the arrow position is updated and used by several classes.
in many cases, you can reduce the scope. this reduces inter-component dependency.
However, I am insecure whether this is a good or a bad design decision. My thoughts are that since it is a non-critical piece of information (just a float), no harm is done when storing it globally. But my OOP heart hurts every time I say the word "global" to myself.
perhaps you can move the state (the float value) to an ivar in your speedometer? example: you likely display just one speedometer view: does it make more sense to add it to what is the view's model? or perhaps to its controller? (yes, it's a bit tough to provide a more specific example without the source)
Alternatively I have studiet singletons, but as far as I have read, singletons are used when the developer wishes to create one and only one instance of a certain object.
not necessary, and a severe pain to maintain. most of the cocoa singletons i have seen should not have been considered singletons, and caused a lot of headaches. better yet, you can write programs which use zero singletons. this is ideal, and easy to test. as is, the programs/types which depend on the app controller's have been compromised wrt testability and reusability.
Am I doing it correct or is there a more proper way of doing what I do?
in the vast majority of cases, you can simply reduce the scope and localize it, while removing global state. with a little more effort, you can remove that value as a global -- that is best.
although it is not a good thing... let's assume you really really really really really must introduce global state:
*
*don't use a singleton. chances are good that you will rewrite it when you want to reuse it. it sugar coats what is ugly. if your app controller is a mess due to too much global state, at least the fact that you have too much global state will be obvious.
*hold your global state in your app controller. your app controller is responsible for its initialization, lifetime, and access.
*provide that state to dependencies, so they do not refer back to (or even know about) the global domain (the app controller). then you may minimize the impact.
there's also a distinct difference between global state and application/execution state. global state should be eliminated. execution state is not global state, but localized execution context. execution state can be reintroduced at the right level, altered, and updated, tested, and reused predictably. a good design will introduce execution state when needed, and at the right level while avoiding global state.
Update
Your sample is pretty close to what i had imagined, based on the description in the OP. It provided some additional specifics. So the sample below (you'll need some additions in obvious areas to piece it all together) demonstrates how you could update the controller interfaces, and there are two free 'elsewhere' methods at the end which further illustrate how to use these:
@interface MONArrowPosition : NSObject
{
float arrowPosition;
}
@end
@implementation MONArrowPosition
- (id)initWithPosition:(float)position
{
self = [super init];
if (nil != self) {
arrowPosition = position;
}
return self;
}
@end
@interface MyViewController1 : UIViewController
{
MONArrowPosition * arrowPosition; // << may actually be held by the model
}
@end
@implementation MyViewController1
- (void)applyRotation
{
[self rotateLayer:arrow from:self.arrowPosition to:callStatus speed:METER_SPEED];
}
@end
@interface MyViewController2 : UIViewController
{
MONArrowPosition * arrowPosition; // << may actually be held by the model
}
@end
@implementation MyViewController2
- (void)viewDidLoad
{
[super viewDidLoad];
/* ... */
[self.slider addTarget:self action:@selector(sliderValueDidChange) forControlEvents:controlEvents];
}
- (void)sliderValueDidChange
{
self.arrowPosition.arrowPosition = self.slider.value;
[self arrowPositionDidChange];
}
@end
/* elsewhere: */
- (void)initializeArrowPosition
{
/* The variable is set to a default of 0.0f */
MONArrowPosition * arrowPosition = [[MONArrowPosition alloc] initWithPosition:0.0f];
/* ... */
}
- (IBAction)someActionWhichPushesMyViewController1
{
// depending on the flow of your app, the body of initializeArrowPosition
// *could* be right here
MyViewController1 * viewController = [[MyViewController1 alloc] initWithNibName:nibName bundle:bundle];
viewController.arrowPosition = self.arrowPosition;
/* push it */
}
and then if MyViewController1 pushes MyViewController2, locating and setting the arrow position will be easy. the view controllers may also be sharing some information in the models. with a global in your sample, you are crossing many implementations, which adds coupling, increases dependency, etc.. so if you can take this approach and localize the execution state, you're off to a good start. then you can use any number of view controllers with any number of MONArrowPositions, and they will not be subject to the effects of global state. again, i can't get too specific using the samples provided, but i think this should illustrate the concepts i originally outlined well enough (i don't think a project-wide review is needed).
A: Well this is something that is keeping a lot of programmers up at night.
I try not to misuse the app delegate as much, I'll create a singleton for storing more or less global information. There is no real other way to do it then either the singleton or the app delegate.
But if only one viewController need the information than, the information will never leave that viewController. That viewcontroller could pass that information on to other viewcontroller is needed.
In you case it might be an idea to have some kind of directionManager which hold the floats and might even hold the CLLocationManager.
A: For this type of thing, I like to use NSNotifications. You have all the view controllers who care about the arrow's position listen for the specific notification, and they can all update the UI at once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Difference between x86, x32, and x64 architectures? Please explain the difference between x86, x32 and x64? Its a bit confusing when it comes to x86 and x32 because most of the time 32-bit programs run on x86...
A: x86 means Intel 80x86 compatible. This used to include the 8086, a 16-bit only processor. Nowadays it roughly means any CPU with a 32-bit Intel compatible instruction set (usually anything from Pentium onwards). Never read x32 being used.
x64 means a CPU that is x86 compatible but has a 64-bit mode as well (most often the 64-bit instruction set as introduced by AMD is meant; Intel's idea of a 64-bit mode was totally stupid and luckily Intel admitted that and is now using AMDs variant).
So most of the time you can simplify it this way: x86 is Intel compatible in 32-bit mode, x64 is Intel compatible in 64-bit mode.
A: Hans and DarkDust answer covered i386/i686 and amd64/x86_64, so there's no sense in revisiting them. This answer will focus on X32, and provide some info learned after a X32 port.
x32 is an ABI for amd64/x86_64 CPUs using 32-bit integers, longs and pointers. The idea is to combine the smaller memory and cache footprint from 32-bit data types with the larger register set of x86_64. (Reference: Debian X32 Port page).
x32 can provide up to about 30% reduction in memory usage and up to about 40% increase in speed. The use cases for the architecture are:
*
*vserver hosting (memory bound)
*netbooks/tablets (low memory, performance)
*scientific tasks (performance)
x32 is a somewhat recent addition. It requires kernel support (3.4 and above), distro support (see below), libc support (2.11 or above), and GCC 4.8 and above (improved address size prefix support).
For distros, it was made available in Ubuntu 13.04 or Fedora 17. Kernel support only required pointer to be in the range from 0x00000000 to 0xffffffff. From the System V Application Binary Interface, AMD64 (With LP64 and ILP32 Programming Models), Section 10.4, p. 132 (its the only sentence):
10.4 Kernel Support
Kernel should limit stack and addresses returned from system calls between 0x00000000 to 0xffffffff.
When booting a kernel with the support, you must use syscall.x32=y option. When building a kernel, you must include the CONFIG_X86_X32=y option. (Reference: Debian X32 Port page and X32 System V Application Binary Interface).
Here is some of what I have learned through a recent port after the Debian folks reported a few bugs on us after testing:
*
*the system is a lot like X86
*the preprocessor defines __x86_64__ (and friends) and __ILP32__, but not __i386__/__i686__ (and friends)
*you cannot use __ILP32__ alone because it shows up unexpectedly under Clang and Sun Studio
*when interacting with the stack, you must use the 64-bit instructions pushq and popq
*once a register is populated/configured from 32-bit data types, you can perform the 64-bit operations on them, like adcq
*be careful of the 0-extension that occurs on the upper 32-bits.
If you are looking for a test platform, then you can use Debian 8 or above. Their wiki page at Debian X32 Port has all the information. The 3-second tour: (1) enable X32 in the kernel at boot; (2) use debootstrap to install the X32 chroot environment, and (3) chroot debian-x32 to enter into the environment and test your software.
A: x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).
x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.
x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.
A: As the 64bit version is an x86 architecture and was accordingly first called x86-64, that would be the most appropriate name, IMO. Also, x32 is a thing (as mentioned before)—‘x64’, however, is not a continuation of that, so is (theoretically) missleading (even though many people will know what you are talking about) and should thus only be recognised as a marketing thing, not an ‘official’ architecture (again, IMO–obviously, others disagree).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "61"
} |
Q: Keep App in Focus I use wscript to launch an application on my machine. I then use this app for 30 seconds before I kill it. I do this using python -
import win32com.client
import time
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("My App")
time.sleep(0.5)
shell.SendKeys('%f')
...
I was wondering if it is possible to ensure that the launched app receives the SendKeys instructions and not another app that I might accidentally give focus to under this 30 second period.
Thanks,
Barry.
A: Problem
*
*how to guarantee a wsh script SendKeys event goes to a specifically targted application
Workaround
*
*in lieu of a straightforward solution to targeting a specific process with SendKeys you can use the "wait" variant of ShellRun
Example
*
*Change "Before" into "After"
Before
WshShell.Run(run_name)
After
WshShell.Run(run_name,1,true)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: enter multiple mail ids and separated by ';' and validation in flex I was creating a form. Certian fields of the form store all of those IDs to a single field separated by a comma or semicolon. how to send the mail id's for email validation which is providing by flex by default.
A: You can split the values in the field (using a standard string split) on comma (or whatever separator you decide to use), and then use the email validator for each of the splitted string (email Ids).
A: This is in addition to the answer marked as correct above:
https://wimdeblauwe.wordpress.com/2011/02/07/validation-of-multiple-email-addresses-in-flex/
For our flex application, I had a ‘cc’ field that could handle
multiple email addresses. When adding validation, I first used the
standard EmailValidator class. However, this would not work as soon as
you want to add multiple email addresss, like:
foo@company.com;bar@company.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Share a bool variable / NSNUmber between two view controllers I have two view controllers and I want to share a bool variable between them.
So I create a bool variable with a @propery (nonatomic, assign) on both sides and on the one side I wrote
newVC.myBool1 = self.myBool2;
On the other view controller I can read the value of the passed bool variable, but I need to change it at the second view controller so I can read the value at the first view controller.
So I know, this is not possible, because `bool* it is a primitive type.
So I used NSNumber, but this also does not work. On the first view controller I set on viewDidLoad
self.myBool1 = [NSNumber numberWithBool:NO];
On the second view controller:
self.myBool2 = [NSNumber numberWithBool:YES];
But on the first view controller the value is 0 - NO... So it seems that creating the new NSNumber is not shared to the first view controller.
What can I do to solve this problem?
Regards Tim
A: An NSNumber object is immutable, so you can't use it like that. If you write [NSNumber initWithxxx], in fact you create a new object.
If you want to share a number or boolean between several classes, you should create your own wrapper class with setters and getters for the bool value (or subclass NSNumber). This class you can share between classes.
A: You have lots of choices, but which you should use depends on whether both viewControllers need notification of when the value changes.
If you don't need notification, the easiest choice is to use a global BOOL variable, although purists will scoff at the suggestion. But really it's two lines of code and you're done. Another option would be to store the value in NSUserDefaults.
If you need change notification in each viewController, perhaps the cleanest design is to write a "set" method in one viewController that sets the value in both itself and the other viewController. Something like:
-(void) setMyBool:(BOOL)newValue
{
myBool = newValue;
otherViewController.myBool = newValue;
}
If you want to change the value from either viewController, it gets a little trickier because you have to have each viewController keep a reference to the other and make sure not to recurse when setting the value. Something like:
-(void) setMyBool:(BOOL)newValue
{
if ( self.busyFlag == YES )
return;
self.busyFlag = YES;
myBool = newValue;
otherViewController.myBool = newValue;
self.busyFlag = NO;
}
Yet another option would be to use NSNotifications to change the value and have each viewController class listen for the change notification. And TheEye's suggestion of writing a wrapper class and keeping a reference to an instance of that class in both viewControllers would work too.
If you don't need change notifications, though, I would just create a global BOOL variable and get on with the rest of the application because it's so easy, reliable and hard to mess up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I want to Deserialize stream as contact in windows phone 7 c# I Serialized Contact and Saved it in text file in The Isolated Store
I want to Deserialize it back as Contact
I tried this Code but I get error :
Error 1 The type 'Microsoft.Phone.UserData.Contact' has no
constructors
using (var reader = new StreamReader(stream))
{
var serializer = new XmlSerializer(typeof(Contact));
return reader.EndOfStream
? new Contact()// error
: (Contact)serializer.Deserialize(reader);
}
is there another solution to get it back ?
A: That looks like it is not intended for this purpose; all the properties are get, and there is no (public) constructor. XmlSerializer will not work on that.
IMO your best option is to create something of your own that looks like that class, but is serialization-friendly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why is the netmask in Net::IP set wrong? I'm trying to get a little script to recognize the SNMP data from a query to store it in a database. But I'm stuck when processing the data with the Net::IP CPAN module. If I define the network string there is no problem, but I have IP and mask in separate strings, and no matter how I join them, the module always set the netmask to /32.
I tried it like this:
my $net = "${$query_snmp->{$tablekey}}{'ipRouteMask'}/${$query_snmp->{$tablekey}}{'ipRouteDest'}";
my $IP = new Net::IP ($net) or die (Net::IP::Error());
But all the IP objects are always created with /32 no matter what I set the netmask to. If i define a string like 192.168.0.0/20 or anything on the same string I find no problem.
What am I missing?
Network -> 192.168.65.64/255.255.255.248
IP : 192.168.65.64
LASTIP : 192.168.65.64
Sho : 192.168.65.64
Bin : 11000000101010000100000101000000
Int : 3232252224
*** Mask: 255.255.255.255 *** wtf ??
Last: 192.168.65.64
Len : 32
Size: 1
Type: PRIVATE
Rev: 64.65.168.192.in-addr.arpa.
A: From the manual: A Net::IP object can be created from a single IP address, or from a Classless Prefix, ...
I think you've chosen to specify a classless network, provided that you insert a valid network specifier, it works for me.
#!/usr/bin/perl -w
use Net::IP;
my $ip = new Net::IP('112.198.64.0/18') or die (Net::IP::Error());
print ("IP : ".$ip->ip()."\n");
print ("Sho : ".$ip->short()."\n");
print ("Bin : ".$ip->binip()."\n");
print ("Int : ".$ip->intip()."\n");
print ("Mask: ".$ip->mask()."\n");
print ("Last: ".$ip->last_ip()."\n");
print ("Len : ".$ip->prefixlen()."\n");
print ("Size: ".$ip->size()."\n");
print ("Type: ".$ip->iptype()."\n");
print ("Rev: ".$ip->reverse_ip()."\n");
will output:
IP : 112.198.64.0
Sho : 112.198.64
Bin : 01110000110001100100000000000000
Int : 1892040704
Mask: 255.255.192.0
Last: 112.198.127.255
Len : 18
Size: 16384
Type: PUBLIC
Rev: 64.198.112.in-addr.arpa.
However, if you've entered "192.168.65.64/255.255.255.248", this is not a format accepted by Net::IP, you've to use instead "192.68.65.64/29", see this table. In this case it will work correctly:
IP : 192.168.65.64
Sho : 192.168.65.64
Bin : 11000000101010000100000101000000
Int : 3232252224
Mask: 255.255.255.248
Last: 192.168.65.71
Len : 29
Size: 8
Type: PRIVATE
Rev: 64.65.168.192.in-addr.arpa.
When you use the format with the full netmask, since it's not recognized, it gets just the IP and will give you the netmask of 255.255.255.255
A: thank you ! I finally used a simillar module, that doest requier to transform the ip mask to dec notation.
Net::Netmask -> https://metacpan.org/pod/Net::Netmask
CONSTRUCTING
Net::Netmask objects are created with an IP address and optionally a mask. There are many forms that are recognized:
'216.240.32.0/24' The preferred form.
'216.240.32.0:255.255.255.0'
'216.240.32.0-255.255.255.0'
'216.240.32.0', '255.255.255.0'
'216.240.32.0', '0xffffff00'
'216.240.32.0 - 216.240.32.255'
'216.240.32.4'
A /32 block.
'216.240.32'
Always a /24 block.
'216.240'
Always a /16 block.
'140'
Always a /8 block.
'216.240.32/24'
'216.240/16'
'default' or 'any'
0.0.0.0/0 (the default route)
'216.240.32.0#0.0.31.255'
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery Webservice in ASP.NET I am working with ASP.NET 4.0 framework. In one web page, I have to call web service using Jquery as
var serviceurl = 'http://www.websitename.com/webservicename';
$.ajax({
type: "POST",
url: serviceurl + 'WebServiceName',
data: "{'Parameters': '" + parameter+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
ShowAfterSuccess(msg);
},
error: AjaxFailed
});
It works fine, if i mention url as "http://www.websiteName.com" but when i put URL as "websitename.com" it doent call webservice.
but it works well only in Google Chrome with "websiteName.com" I dont knw what is the issue with that....whether there is problem in my webservice calling or in URL..
A: You must ensure that you are not violating the same origin policy restriction. The best way to ensure this is to use relative urls:
var serviceurl = '/webservicename';
You must ensure that the domain hosting this javascript matches exactly the domain that you are sending your AJAX call to (including the protocol).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regular expression for parsing string in key value pair in java I have this string:
"{ '_id' : ObjectId('4e85ba250364e5a1857ba2e4'),
'message' : '<user=animesh@strumsoft.com>, <action=create-flock>,
params=[<title=[smile.animesh@gmail.com, ram@strumsoft.com],
attendees=immediate, flockType=immediate, duration=30]>' }";
I tried following regex on it:
private static String REGEXFinal = "<(.*?)>";
private static String REGEX2Final = "<(.*)>";
after applying above two regex final out come is
user=a@a.com
action=create-flock
title=[a@a.com, b@b.com], attendees=immediate, flockType=immediate, duration=30]
but I want O/P in key / value format like
user a@a.com
action create-flock
title [a@a.com, b@b.com], attendees=immediate, flockType=immediate, duration=30]
how to do this?
A: if you got this String
user=a@a.com
action=create-flock
title=[a@a.com, b@b.com], attendees=immediate, flockType=immediate, duration=30]
Then why not try to do this..
String str="user=a@a.com action=create-flock title=[a@a.com, b@b.com], attendees=immediate, flockType=immediate, duration=30]";
str = str.replaceAll("=", " ");
System.out.println(str);
A: You can use the following code for each line:
line.replaceFirst("=", " ");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: do not open pop up on session expires I have a page in asp.net. A button click in the page will open a pop-up.
Now if session is expired, it is opening the pop-up window and in the pop-up it is showing the login screen.
Is there any way in which i can avoid pop-up being opened if the session is expired and directly go back to login page?
A: When you say pop-up, do you mean window.open? If so, then you have to make a AJAX call to verify the session, before opening the new window.
A: I am not sure I understand your requirement clearly. There is no exact way to achive this. But we can do it javascript.
put a timer(duration would be session timeout, use settimeout function) in the parent page. Check this value before open a popup.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you set the style of a textbox (html) I want to change the width of this only:
<input type="text" name="experience"/>
But I have got this:
<input type="checkbox" name="option2" value="2222" />
changing too.. when I set:
input {width:134px;}
A: Give it a class or an id and use a class or id selector:
<input type="text" name="experience" id="experience" />
<input type="text" name="experience" class="experience" />
#experience { width:134px }
.experience { width:134px }
Alternatively, you could use an attribute selector:
input[name='experience'] { width:134px }
Note however that attribute selectors do not work in IE6, so if you want to support that you'll have to go with a class or id selector.
A: If you wish to apply only on a specific textbox, use the style attribute.
<input type="text" name="experience" style="width:134px"/>
If you want to apply it on all textboxes on the page, use the CSS:
.textbox {
width:134px;
}
and then apply it on the text:
<input type="text" name="experience" class="textbox"/>
A: Without changing the HTML, you can set the css using the name attribute:
input[name="experience"]{
width:134px;
}
A: you should give the input box a class/id ,
for example:
/
Then you should set the style parameters in your .css stylesheet:
In order to set class styliing use .name{...}, for id use #name{...}
A: You can set the style by type.
<input type="text" name="email">
<input type="text" name="phone">
input[type="text"]{ background:#ff0000; }
A: Your orginal question mentioned a single text input, however your follow up comment mentions you have many text inputs, to avoid repetition in your css files, you could set the class of the input to something like "short" and then apply the width on that class.
input.short {width : 134px}
If you want to apply the width to inputs in a particular form (or element), you could use:
form input {width : 134px}
This may be more scalable in future if you need to change the widths of all text inputs for a form / site
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Open in 32-bit mode Under MacOS, you can change a little option for 32-bit executables called "Open in 32-bit mode". Wouldn't it work directly? And it works, but for some applications you had to select this option in order to run without problems. This was frequent in Safari, where some add-ons required a 32-bit environment.
I can't understand what makes an 32-bit executable not able to run directly in 64-bit, so what exactly changes in 32-bit mode?
A: This is really only of historical interest. In the transition period from 32 bit to 64 bit many apps were built as universal with 3 or sometimes even 4 architectures combined into one fat binary (aka "Universal Binary"), typically ppc, x86 and x86-64. In a 32 bit x86 environment the 32 bit x86 executable would be used. In a 64 bit x86-64 bit environment the 64 bit executable would be used. However in some cases you might want to use the 32 bit x86 executable even in a 64 bit x86-64 environment, e.g. in the case you mentioned where you have older plug-ins which are 32-bit only and can not be used with a 64 bit executable. Hence the option to launch an app in 32 bit mode.
Obviously a 32 bit app uses 32 bit APIs and has a 32 bit address space, whereas a 64 bit app has a 64 bit address space and uses 64 bit APIs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Links from Spanned text don't work in TexView I have a TextView embedded in a RelativeLayout, embedded in a ScrollView, and I load a Spanned text object in it created from some HTML code.
I have set the android:autoLink attribute of the TextView to true, and I have tested in another part of the application that I can click on links in the text and they will take me to the target website.
The only difference is that this time the TextView is a child of a ScrollView. Does that screw up the android:autoLink process or am I really missing something here?
XML Code:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:padding="10dp" android:background="#FFF">
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/RLNewsItem">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:id="@+id/TVText" android:textColor="#000"
android:layout_below="@+id/TVTitle" android:linksClickable="true"
android:autoLink="web|email|map"></TextView>
</RelativeLayout>
</ScrollView>
Java code:
Spanned newsText = Html.fromHtml(htmlsource, this, null);
text.setText(newsText);
A: Try this
Code in String.xml :
<string-array name="description">
<item> <Data> <![CDATA[ Check this <u>Redirect to Next Activity</u> ]]></Data> </item>
Code in Java class:
ArrayList<String> title_list = new ArrayList<String>();
String[] description_Array = getResources().getStringArray(R.array.description);
String categoryAndDesc = null;
for(String cad : description_Array) {
categoryAndDesc = cad;
title_list.add(categoryAndDesc);
}
CharSequence sequence = Html.fromHtml(categoryAndDesc);
seperator_view.setText(strBuilder);
seperator_view.setMovementMethod(LinkMovementMethod.getInstance());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to clear Activity Stack on Button Click in Android I have a question that I have a logout button in my App on which we have called an App login Screen but at this point when user press the Back Button of Android Phone, he entered in the App again without Authentication, which is not desirable. I want when we click on Logout button All previous Activity Stack being cleared or we can say that All previous onPause Activities have to be cleared.
Please Suggest me the right solution for this problem.
Thanks in advance.
A: As far as I understood the login screen would be the first screen after the splash one so if login screen is in stack you can call again login screen like the below to achieve this
Intent launch = new Intent(context, LoginActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(launch);
A: After logout start login activity like this:
Intent launch = new Intent(context, LoginActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch);
you need to use flag FLAG_ACTIVITY_NEW_TASK.
A: Alternative solution is to end your current activity by callingfinish(); after you start the login activity
// logout button handler
startActivity(new Intent(context, LoginActivity.class));
finish();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to create dynamic textbox using asp.net and C# How to create dynamic textbox using asp.net and C# .how to store in database .please any one help me i am new to this .Thanks in advance
A: I hope this can help you:
For Data access you can take a look here:
1. http://www.asp.net/web-forms
2. Download "Professional Asp.Net 4 (wrox)" or "Microsoft ASP.NET 4 Step by Step"
And the code for add textbox(in this case)dinamically in a gridview is like this
void addTextBoxInGridView()
{
int nr = 0, nc = 0;
nr = this.GridView1.Rows.Count;
if (nr > 0)
{
nc = this.GridView1.HeaderRow.Cells.Count;
int r = 0, c = 0;
for (r = 0; r < nr; r++)
{
for (c = 0; c < nc; c++)
{
string v1 = "";
v1 = HttpUtility.HtmlDecode(this.GridView1.Rows[r].Cells[c].Text.ToString());
TextBox textbox = new TextBox();
textbox.Text = v1;
textbox.EnableViewState = true;
textbox.Style["text-align"] = "center";
textbox.Width = 40;
textbox.ID = "txt" + Convert.ToString(r) + Convert.ToString(c);
this.GridView1.Rows[r].Cells[c].Controls.Add(textbox);
}
}
}
}
Happy code!!
A: Here is some research for you that should get you headed in the right direction.
Adding Controls to page dynamically
Data Access in ASP.Net
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to avoid duplication screen in android I have did a application in android by calling sub activities(B,C,D,E) from main activity(A),again calling that main Activity(A) from other sub Activities(B,C,D,E)by using
Intent in = new Intent();
in.setClass(getApplicationContext(), maindashbord.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
when i move back from main Activity to login page by clicking back button ,the main Activity displays again and again the times of I have called the subactivity. I have made all other activities in manifest.xml Android:noHistory="true"
but I need some static value in mainActivity for next login propose...
how can I replace the duplicate screen display?
thanks in advance..
A: After you call startActivity you can call finish() on the next line to stop the current activity.
To store a value even after the activity is, either use Shared Preferences or Extend the appliation class, which you can access from any activity using the getApplicationContext(). This will return a singleton, so the value will be the same in all activities.
A: try flag FLAG_ACTIVITY_NEW_TASK instead of FLAG_ACTIVITY_CLEAR_TOP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to print the contents of an iFrame using Javascript on iPad? Printing the contents of an iFrame already seemed a challenging problem to solve cross-browser. After testing a lot of approaches (some of which also found on this site), my current approach seems to work quite good cross-browser and looks like this:
function printUrl( elem, url ) {
$( '#' + elem ).append( "<iframe style='border: none; width: 0; height: 0; margin: 0; padding: 0;' src='" + url + "' id='printFrame'></iframe>" );
$( '#printFrame' ).load( function() {
var w = ( this.contentWindow || this.contentDocument.defaultView );
w.focus();
w.print();
} );
}
There is only a slight problem with this code when using an iPad. The iPad prints the page which contains the iFrame, instead of the contents of the iFrame. Safari on Mac correctly prints the contents of the iFrame, though.
Has anyone already solved this problem and been able to print the contents of an iFrame on an iPad?
A: Okay, first of all. I did not solve the problem. I created a work-around that actually fakes what I want to achieve.
Because the iPad / iPhone simple prints the parent page, I wrap the complete body in a new div, then append the iFrame and some stylesheets which make sure that the printed document only contains the iFrame:
function printUrl( url ) {
$newBody = "<div class='do_not_print_this'>"
+ $( 'body' ).html()
+ "</div>"
+ "<iframe style='border: none; 0; width: 100%; margin: 0; padding: 0;' src='" + url + "' class='printFrame'></iframe>"
+ "<style type='text/css' media='all'>.printFrame { position: absolute; top: -9999999px; left: -99999999px; }</style>"
+ "<style type='text/css' media='print'>.do_not_print_this { display: none; } .printFrame { top: 0; left: 0; }</style>";
$( 'body' ).html( $newBody );
$( '.printFrame' ).load( function() {
var w = ( this.contentWindow || this.contentDocument.defaultView );
w.focus();
w.print();
} );
}
Hiding the iframe for the browser in the normal view is done using absolute positioning, using display on none or visibility hidden introduced weird behavior in the final print.
Yes, it's ugly. However, this is currently the only option I can think of which works. If any of you come up with a better solution, please let me know.
A: Here's a function that works cross-cross platform on evergreen browsers and the current versions of iOS:
function printElement(divid, title)
{
var contents = document.getElementById(divid).innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write('<html><head><title>' + title + '</title>');
frameDoc.document.write('</head><body style="font-family: Arial, Helvetica, sans; font-size: 14px; line-height: 20px">');
frameDoc.document.write('<h1>' + title + '</h1>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
}, 500);
//Remove the iframe after a delay of 1.5 seconds
//(the delay is required for this to work on iPads)
setTimeout(function () {
document.body.removeChild(frame1);
}, 1500);
return false;
}
This is based on this answer with minor modifications (Importantly the line document.body.removeChild(frame1); had to be removed to allow for printing on iOS.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to make jQuery's 'filter' function work correctly for SVG nodes? Say I have the following SVG and jQuery:
<g id="test">
<rect>
<text>demo</text>
</g>
$('#test').filter('text').each(function(){
// do something
});
The filter function doesn't work with SVG, probably because jQuery was designed for DOM manipulation, not namespaced SVG.
But how can I adapt jQuery's filter function to accept SVG correctly?
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
A: I don't think you need to alter the jQuery source, you can use other traversal methods that are compatible with XML.
// This works
$("#test").find("text").each(function() {
// do something
});
to keep the current element as well:
var svg = $("#test");
svg.find( "text" ).add( svg ).each(function() {
// do something
});
or:
var svg = $("#test");
svg.find( "text" ).andSelf().each(function() {
// do something
});
hope that helps. cheers!
A: SVG nodes work fine in jQuery selectors. The problem is that $('#test').filter('text') means "give me all nodes with id test that are also text nodes."
As keegan indicated, you're looking for the find() function, not the filter() function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery replace input button onclick event I have HTML loaded with the Jquery .load method and need to dynamically change anchor HREF and input button ONCLICK targets in this HTML on the client as the page loads, (I don't have the option to change the server generated HTML).
The .load works fine and I can change the HREF target OK but I can't find a way of changing the ONCLICK target?
HTML
*
*Anchor HREF
<div style="width:143px;" id="LM_OBJV">
<span title="View Objectives Detail" class="PSHYPERLINK">
<a class="PSHYPERLINK" href="javascript:Action_win0
(document.win0,'LM_OBJV','Relationship Building',false,true);" tabindex="54"
id="LM_OBJV" name="LM_OBJV">Relationship Building</a>
</span>
</div>
*Button ONCLICK
<div id="win0divLM">
<a id="Left" style="background-Color: transparent;border:0;" class="PBUTTON">
<span style="background-Color: transparent;">
<input type="button" onclick="Action_win0(document.win0,'LM_PB', 0, 0, 'Add New',
false, true);" style="width:120px; " class="PBUTTON" value="Add New" tabindex="77"
id="LM_PB" name="LM_PB">
</span>
</a>
</div>
Javascript
$('#result').load('some.php', function() {
$("a.PSHYPERLINK")
.each(function()
{
this.href = this.href.replace("Action_win0", "Action_winx");
});
});
So this JS works fine, loads the HTML into the #results DIV and changes the HREF's from "Action_win0" to "Action_winx".
But how can I also change the input type="button ONCLICK events from "Action_win0" to "Action_winx"? I've tried several Jquery selectors but just can't get it to work :(
A: $('a.PSHYPERLINK').attr('onclick', 'alert("bar")')
Demo: http://jsfiddle.net/kzVSt/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Dropdown menu - z-order I have a dropdown menu:
<div class="buttons">
<div class="dropdown">
<a href="#" class="button"><span class="label">File</span><span class="toggle"></span></a>
<div class="dropdown-slider">
<a href="#" class="ddm"><span class="label">New</span></a>
<a href="#" class="ddm"><span class="label">Save</span></a>
</div> <!-- /.dropdown-slider -->
</div> <!-- /.dropdown -->
</div>
And here is js code:
<script>
$(document).ready(function() {
// Toggle the dropdown menu's
$(".dropdown .button, .dropdown button").click(function () {
$(this).parent().find('.dropdown-slider').slideToggle('fast');
$(this).find('span.toggle').toggleClass('active');
return false;
});
});
// Close open dropdown slider by clicking elsewhwere on page
$(document).bind('click', function (e) {
if (e.target.id != $('.dropdown').attr('class')) {
$('.dropdown-slider').slideUp();
$('span.toggle').removeClass('active');
}
});
</script>
If I put the two menus (one above other) I'll get popup menu below the second menu line.
How can I fix it?
A: Adding z-index:999; to div.dropdown-slider should fix your problem pretty quickly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: BackgroundWorker not firing RunWorkerCompleted The first time I run my backgroundworker it runs correctly - updates a datatable in the background and then RunWorkerCompleted sets the datatable as a datagridview datasource.
If I then run it again, the datagridview clears and doesn't update. I can't work out why.
I've verified that the datatable contains rows when my code hits dgvReadWrites.DataSource.
private void btnGenerateStats_Click(object sender, EventArgs e)
{
dtJobReadWrite.Columns.Clear();
dtJobReadWrite.Rows.Clear();
dgvReadWrites.DataSource = dtJobReadWrite;
List<Tuple<string, string>>jobs = new List<Tuple<string, string>>();
foreach (ListViewItem job in lstJobs.SelectedItems)
{
jobs.Add(new Tuple<string, string>(job.Text, job.SubItems[2].Text));
}
BackgroundWorker bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = true;
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
pbarGenStats.Style = ProgressBarStyle.Marquee;
pbarGenStats.MarqueeAnimationSpeed = 30;
pbarGenStats.Visible = true;
bgw.RunWorkerAsync(jobs);
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgw = sender as BackgroundWorker;
List<Tuple<string, string>> jobs = (List<Tuple<string, string>>)e.Argument;
GetReadWriteStats(jobs);
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BackgroundWorker bgw = sender as BackgroundWorker;
bgw.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.DoWork -= new DoWorkEventHandler(bgw_DoWork);
pbarGenStats.MarqueeAnimationSpeed = 0;
pbarGenStats.Value = 0;
pbarGenStats.Visible = false;
dgvReadWrites.DataSource = dtJobReadWrite;
dgvReadWrites.Visible = true;
dgvReadWrites.Refresh();
}
A: private void btnGenerateStats_Click(object sender, EventArgs e)
{
//...
dgvReadWrites.DataSource = dtJobReadWrite;
// etc...
}
That's a problem, you are updating dtJobReadWrite in the BGW. That causes the bound grid to get updated by the worker thread. Illegal, controls are not thread-safe and may only be updated from the thread that created them. This is normally checked, producing an InvalidOperationException while debugging but this check doesn't work for bound controls.
What goes wrong next is all over the place, you are lucky that you got a highly repeatable deadlock. The more common misbehavior is occasional painting artifacts and a deadlock only when you are not close. Fix:
dgvReadWrites.DataSource = null;
and rebinding the grid in the RunWorkerCompleted event handler, like you already do.
A: Because you unscubscribe from those events
bgw.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.DoWork -= new DoWorkEventHandler(bgw_DoWork);
Remove those lines
A: Why are you creating a new BackgroundWorker every time you want to run it? I would like to see what happens with this code if you use one instance of BackgroundWorker (GetReadWriteWorker or something along those lines), subscribe to the events only once, and then run that worker Async on btnGenerateStats_Click.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to list my EC2 instances and get their private ip's I'm starting to use EC2 with a lot of SPOT instances (>100), I'm trying to find a way to retrieve all my IC2 instances private ip's in order to use them later to deploy binaries and so on.
Can anyone help me to do it?
Thanks in advance.
A: Since you didn't list a framework or language:
*
*Use the AWS Console.
*Use ElasticFox.
*Use the commandline tools.
*Use the .NET SDK.
*Use the Java SDK.
A: Amazon will start and stop spot instances without your involvement but based on your spot instance request parameters. Because of this, the list of spot instance IP addresses you query at time A might not be accurate at time B.
Problem 1: You think IP address A is one of your spot instances, but in the interim Amazon has terminated your spot instance and started somebody else's instance using the same private IP address. You'll want to make sure that an instance you are contacting is really yours before you pass it anything sensitive or trust any answers it gives you.
Problem 2: In the time since you got the query results, Amazon has started new spot instances for you based on the spot price. When you go to "deploy binaries and so on" you could miss some of the instances leaving them in unstable or out-of-date states.
You might consider having the spot instances configure and update themselves when they start up, and perhaps on regular intervals.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Calling objects from dynamic UserControls VB.NET Love these forums, I am a beginner when it comes to VB.NET and have run into some trouble.
Here is my Code snippet
'decleare variables
Dim vmcount As Integer
Dim tabcount As Integer
Dim userControl As Control
Dim UserControlName As String
vmcount = combo_vmcount.SelectedItem
tabcount = 1
tab_con_vm.TabPages.Clear()
While (tabcount <= vmcount)
Dim tabname As New TabPage
'Load variables
userControl = New calc_usercontrol_vm
tabname.Text = "VM" & tabcount
tabname.Name = "VM" & tabcount
UserControlName = "UCVM" & tabcount
userControl.Name = UserControlName
'actions
tab_con_vm.TabPages.Add(tabname)
tabname.Controls.Add(userControl)
'next
tabcount = tabcount + 1
End While
End Sub
The trouble I'm having is working out a way to be able to call the objects in the dynamically created usercontrols. I thought a list maybe an option but I am struggling to get the syntax/get it working. Wondering if anyone has some ideas or different approaches..
Thanks Guys
Richard
A: If you know the index of the tab you wish to work with
Dim calc_usercontrol As calc_usercontrol_vm = TabPages(index).userControl
Or if you don't know the index you can use the IndexOfKey method where the key is the Name of the tabcontrol
Dim index as Integer = TabPages.IndexOfKey("TabControlName")
A: While this is most likely not the best way to solve the problem, I ended up creating an global array and build the user controls off that.
' USERCONTROL ARRAY
Public UCVMARRAY(30) As calc_usercontrol_vm
Dim tabcount As Integer
Dim UCVMARRAYindex As Integer
Dim userControl As Control 'control variable
Dim UserControlName As String
vmcount = combo_vmcount.SelectedItem
tabcount = 1
UCVMARRAYindex = 0
tab_con_vm.TabPages.Clear()
While (tabcount <= vmcount)
Dim tabname As New TabPage ' Relook at this to improve the method used. Issue was that new page was not generated on loop.
'Load variables
userControl = New calc_usercontrol_vm
' loads UC
tabname.Text = "VM" & tabcount
tabname.Name = "VM" & tabcount
UserControlName = "UCVM" & tabcount
userControl.Name = UserControlName
UCVMARRAY(UCVMARRAYindex) = userControl 'places it back
'actions
tab_con_vm.TabPages.Add(tabname)
tabname.Controls.Add(userControl)
'next
tabcount = tabcount + 1
UCVMARRAYindex = UCVMARRAYindex + 1
End While
End Sub
It's very basic but I got it working, the answers above are most likely a good solution but I my knowledge of vb.net were not up to scratch.
A: Call the Page.LoadControl method and then add it to your page, preferrebly in the Init portion of the Page lifecycle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: An URI relativization in XQuery How to relativize an URI to another URI?
uri1
file:/folder1/file2.txt
uri2
file:/folder1/folder2/file1.txt
needed result
relativize-method($uri1, $uri2) == '../file2.txt'
A: Something like this (will rewrite it in XQuery):
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:my="my:my">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<xsl:sequence select="my:RelativeUrl(url[1], url[2])"/>
</xsl:template>
<xsl:function name="my:RelativeUrl" as="xs:string">
<xsl:param name="pUrl" as="xs:string"/>
<xsl:param name="pBase" as="xs:string"/>
<xsl:variable name="vurlSegments" select="tokenize($pUrl, '/')"/>
<xsl:variable name="vbaseSegments" select="tokenize($pBase, '/')"/>
<xsl:variable name="vCommonPrefixLength" select=
"(for $i in 1 to count($vbaseSegments)
return
if($vbaseSegments[$i] ne $vurlSegments[$i])
then $i -1
else ()
)[1]
"/>
<xsl:variable name="vUpSteps" select=
"count($vbaseSegments) -$vCommonPrefixLength "/>
<xsl:sequence select=
"string-join
(
(
(for $i in 1 to $vUpSteps
return
'..'
),
(for $k in 1 to count($vurlSegments) - $vCommonPrefixLength
return
$vurlSegments[$vCommonPrefixLength + $k]
)
),
'/'
)
"/>
</xsl:function>
</xsl:stylesheet>
when applied on this XML document:
<t>
<url>file:/folder1/file2.txt</url>
<url>file:/folder1/folder2/file1.txt</url>
</t>
the wanted, correct result is produced:
../../file2.txt
Update:
Below is a pure XPath 3.0 solution:
let $pUrl := "file:/folder1/file2.txt",
$pBase := "file:/folder1/folder2/folder3/file1.txt",
$urlSegments := tokenize($pUrl, '/'),
$baseSegments := tokenize($pBase, '/'),
$idiff := (for $ind in 1 to max((count($urlSegments), count($baseSegments)))
return $ind[$urlSegments[$ind] ne $baseSegments[$ind]]
) [1]
return
string-join(
((1 to count($baseSegments) - count($urlSegments)) ! '..',
$urlSegments[position() ge $idiff])
, '/')
A: You could tokenize to get the directories, and then use a recursive function to compute the desired result. Something like the following (tested on try.zorba-xquery.com):
declare function local:compute-relative-uri($absolute as xs:string,
$current as xs:string)
{
local:compute-relative-uri-aux(tokenize($absolute, "/"),
tokenize($current, "/"))
};
declare function local:compute-relative-uri-aux($absolute as xs:string*,
$current as xs:string*)
{
if (head($absolute) eq head($current))
then
local:compute-relative-uri-aux(tail($absolute), tail($current))
else
let $steps := (for $dir in 1 to count($current) - 1 return "..", $absolute)
return string-join($steps, "/")
};
let $absolute := "file:/folder1/file2.txt"
let $current := "file:/folder1/folder2/file1.txt"
return
local:compute-relative-uri($absolute, $current)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Radix-Sort Implementation for Dictionary/KeyValuePair Collection I'm looking for a fast and efficient Radix-Sort Implementation for Dictionary/KeyValuePair Collection if possible in C# (but not mandatory). The key is an Integer between 1 000 000 and 9 999 999 999. The number of values are varying between 5 to several thousand.
At the moment I'm using LINQ-OrderBy, which is I think QuickSort. For me performance is really important and I would like to test whether a Radix-Sort would be faster.
I found only Array implementations. Of course I could try it by myself but because I'm new to this topic I believe it wouldn't be the fastest and most efficient algorithm. ;-)
Thank you.
Rene
A: Have you tested your code to determine that the LINQ-based sort is the bottleneck in your program? LINQ's sort is pretty darned quick. For example, the code below times the sorting of a dictionary that contains from 1,000 to 10,000 items. The average, over 1,000 runs, is on the order of 3.5 milliseconds.
static void DoIt()
{
int NumberOfTests = 1000;
Random rnd = new Random();
TimeSpan totalTime = TimeSpan.Zero;
for (int i = 0; i < NumberOfTests; ++i)
{
// fill the dictionary
int DictionarySize = rnd.Next(1000, 10000);
var dict = new Dictionary<int, string>();
while (dict.Count < DictionarySize)
{
int key = rnd.Next(1000000, 9999999);
if (!dict.ContainsKey(key))
{
dict.Add(key, "x");
}
}
// Okay, sort
var sw = Stopwatch.StartNew();
var sorted = (from kvp in dict
orderby kvp.Key
select kvp).ToList();
sw.Stop();
totalTime += sw.Elapsed;
Console.WriteLine("{0:N0} items in {1:N6} ms", dict.Count, sw.Elapsed.TotalMilliseconds);
}
Console.WriteLine("Total time = {0:N6} ms", totalTime.TotalMilliseconds);
Console.WriteLine("Average time = {0:N6} ms", totalTime.TotalMilliseconds / NumberOfTests);
Note that the reported average includes the JIT time (the first time through the loop, which takes approximately 35 ms).
Whereas it's possible that a good radix sort implementation will improve your sorting performance, I suspect your optimization efforts would be better spent somewhere else.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Making a class to keep track of related strings It is kind of funny, With the follwing class I know how my output should like but I could not figure it out how to hold the data for it.
Please see the code below:
public class QuickFailureReportText
{
public string[] device { get; set; }
public string[] group { get; set; }
public string[] pin { get; set; }
public override string ToString()
{
TextWriter tw;
StringBuilder sb = new StringBuilder();
tw = new StringWriter(sb);
tw.WriteLine("Quick Failure Report");
foreach (string dev in device)
{
tw.WriteLine("Failures in " + dev);
foreach (string grp in group)
{
tw.Write("Group " + grp + " : ");
foreach(string p in pin)
{
tw.Write(p + ", ");
}
tw.WriteLine(); //new line
}
tw.WriteLine(); //new line
}
return tw.ToString();
}
}
So what I want to do, is I want be able to somohe relate the three different string "device, group, pin" somhow that a PIN belongs to a GROUP and a GROUP belongs to a DEVICE. how that can be possible?
Please let me know if I am not clear enough.
UPDATE
Ok, I have a XML file that I can read data from it with no problem. the xml file looks like something like this:
<?xml version="1.0" encoding="utf-8"?>
<DEVICES>
<device>
<name>device 1</name>
<groups>
<group>
<group_name>group 1</group_name>
<pins>
<pin result="fail">A1</pin>
<pin result="pass">A2</pin>
</pins>
</group>
<group>
<group_name>group 2</group_name>
<pins>
<pin result="fail">B1</pin>
<pin result="pass">B2</pin>
</pins>
</group>
</groups>
</device>
</DEVICES>
So I want to gather the data from this XML(which may have a lot of devices) and using the class I wrote above, filter the failed pins.
A: Something like that?
public class Device
{
public string Name;
public List<Group> Groups = new List<Group>();
}
public class Group
{
public string Name;
public List<Pin> Pins = new List<Pin>();
}
public class Pin
{
public string Name;
public string Result;
}
A: I would implement an object data model, using three classes:
DEVICE HAS GROUP
GROUP HAS PIN
UPDATE
Class 1: DEVICE, with member field list_of_groups (you can use a different name)
Class 2: GROUP, with member field list_of_pins
Class 3: PIN, with member field result (boolean)
A: I think it's better if you change the xml in this way:
<?xml version="1.0" encoding="utf-8"?>
<DEVICES>
<device>
<name>device 1</name>
<groups>
<group>
<group_name>group 1</group_name>
<pins>
<pin result="fail">A1</pin>
<pin result="pass">A2</pin>
</pins>
</group>
<group>
<group_name>group 2</group_name>
<pins>
<pin result="fail">B1</pin>
<pin result="pass">B2</pin>
</pins>
</group>
</groups>
</device>
</DEVICES>
So you can define the object Device tha contains a List of Group that contains a list of object Pin.
A: I've written some code you can use to read required information from xml file, store in devices variable
public class Device
{
public string Name;
public Dictionary<string, Group> Groups = new Dictionary<string, Group>();
}
public class Group
{
public string Name;
public List<string> Pins = new List<string>();
}
public class QuickFailureReportText
{
public Dictionary<string, Device> devices = new Dictionary<string, Device>();
public void AddLog(string deviceName, string groupName, string pin)
{
if (!devices.ContainsKey(deviceName))
devices.Add(deviceName, new Device()
{ Name = deviceName, Groups = new Dictionary<string, Group>() });
if (!devices[deviceName].Groups.ContainsKey(groupName))
devices[deviceName].Groups.Add(groupName, new Group()
{ Name = groupName, Pins = new List<string>() });
devices[deviceName].Groups[groupName].Pins.Add(pin);
}
public override string ToString()
{
TextWriter tw;
StringBuilder sb = new StringBuilder();
tw = new StringWriter(sb);
tw.WriteLine("Quick Failure Report");
XDocument xDoc = XDocument.Load(@"devices.xml");
foreach (XElement device in xDoc.XPathSelectElements("DEVICES/device"))
{
foreach (XElement group in device.XPathSelectElements("groups/group"))
{
foreach (XElement pin in group.XPathSelectElements("pins/pin"))
{
if (pin.Attribute("result").Value == "fail")
{
AddLog(device.XPathSelectElement("name").Value,
group.XPathSelectElement("group_name").Value, pin.Value);
}
}
}
}
foreach (var device in devices.Values)
{
tw.WriteLine("Failures in " + device.Name);
foreach (var grp in device.Groups.Values)
{
tw.Write("Group " + grp.Name + " : ");
foreach (string p in grp.Pins)
{
tw.Write(p + ", ");
}
tw.WriteLine(); //new line
}
tw.WriteLine(); //new line
}
return tw.ToString();
}
}
class Program
{
static void Main(string[] args)
{
string s = new QuickFailureReportText().ToString();
}
}
Below is value of 's' string for your example file:
Quick Failure Report
Failures in device 1
Group group 1 : A1,
Group group 2 : B1,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting a List of 5 recent items filled in UITextField Getting a List of 5 recent items filled in Text Field, from where if i select any item will get populated in the Text Field. Open for any suggestions/solution.
Thanks in Advance.
A: Create a NSMutableArray and listen to the UITextField's delegate. Whenever the user presses "Return" or the field is resigned, add the current value to the NSMutableArray ([myArray addObject:textField.text];)
When you want to show the data in the array:
for (NSString *value in myArray)
{
NSLog(@"String value: %@", value);
}
A: I agree with Paul Peelen but his solution is incomplete. You want to have five different items, so the code is the following:
#define CAPACITY 5
[...]
self.recents = [NSMutableArray arrayWithCapacity:CAPACITY + 1];
[...]
- (void)addItem:(NSString*)addItem {
//item won't be twice in the list
[self.recents removeObject:item];
//recently used items are at the beginning of the list
[self.recents insertObject:item atIndex:0];
//remove the sixth item
if ([self.recents count] == CAPACITY + 1) {
[self.recents removeLastObject];
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find latitude and longitude faster in android? I am using LocationManager to get the values of Latitude and Longitude of a user. These values are updated regularly to a database and find out the distance between two users basing on the stored Latitude and Longitude values.
Now,onLocationchanged() called very slow,some times get fast.while i'm waiting long time to proceed next process.When i 'm in indoor the Location search is very slow..
Is there any solution to this prob.pls give me a guide and example.
Please Accept My question as soon as give me a solution.
A: If you use network location provider, you will get location faster, but it will be less accurate (100-500m).
OTOH, GPS provider will be more accurate (10-20m) but it will take more time to acquire location as device needs to acquire GPS satellite signals. Sometimes it's not even possible to acquire signals, especially if indoor or beneath thick trees.
A: Well there are there types of GPS starts :
COLD start: takes a lot of time. The old GPS (satellite/time) data is practically useless.
WARM start : is when the GPS device remembers its last calculated position, almanac used, and UTC Time, but not which satellites were in view. You get the fix fairly fast.
HOT start : is when the GPS device remembers its last calculated position and the satellites in view, the almanac used (information about all the satellites in the constellation), the UTC Time and makes an attempt to lock onto the same satellites and calculate a new position based upon the previous information.
To emulate the warm start case all you have to do is connect to the SUPL network, which provides assistance data. Even cold starts can be converted to a warm start. To make sure that SUPL networks are available, make sure you are connected to the internet. In indoor cases no satellites are visible so getting an exact fix is tough without any assistance data. At least 3 satellites should be visible. Again SUPL networks come to the rescue.
Note that, various GPS chipset have different performances/algorithms and the triangulation time depends on the SUPL networks provided by your Network provider.
You can here more about this here
A: Good starting point is blog/project by Reto Meier:
http://code.google.com/p/android-protips-location/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cyclic reference error in EF code first This is my abstract base class:
public abstract class ServiceStation
{
#region '----- Member(s) -----'
public int Id { get; set; }
public int CompanyId { get; set; }
[ForeignKey("CompanyId")]
public virtual Company Company { get; set; }
public int GasolineBrandId { get; set; }
[ForeignKey("GasolineBrandId")]
public virtual GasolineBrand GasolineBrand { get; set; }
[ForeignKey("LastUpdatedByUserId")]
public virtual User LastUpdatedBy { get; set; }
public int LastUpdatedByUserId { get; set; }
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
public int CreatedByUserId { get; set; }
#endregion
}
I've inherited this class into CompanyStation:
public class CompanyStation : ServiceStation
{
#region '----- Member(s) -----'
[InverseProperty("CompanyStation")]
public virtual SapphirePosSystem SapphirePosSystem { get; set; }
[ForeignKey("StoreManagerId")]
public virtual User StoreManager { get; set; }
public int StoreManagerId { get; set; }
[ForeignKey("OfficeManagerId")]
public virtual User OfficeManager { get; set; }
public int OfficeManagerId { get; set; }
#endregion
}
When I do that I keep getting error of foreign key cyclic error for StoreManager. If I remove that property then I get error for OfficeManager. Likewise if I remove that I get error for CreatedBy and so on. All foreign keys throw this kind of cyclic reference error. I have no birectional relationship. Don't know why Code First thinks it is cyclic. By trial and error I found that if I put this piece of code in my EntityConfiguration it works fine:
public class CompanyStationConfiguration : EntityTypeConfiguration<CompanyStation>
{
#region '----- Methods -----'
public CompanyStationConfiguration()
: base()
{
HasRequired(e => e.StoreManager).
WithMany().
HasForeignKey(e => e.StoreManagerId).
WillCascadeOnDelete(false);
HasRequired(e => e.OfficeManager).
WithMany().
HasForeignKey(e => e.OfficeManagerId).
WillCascadeOnDelete(false);
HasRequired(e => e.Company).
WithMany().
HasForeignKey(e => e.CompanyId).
WillCascadeOnDelete(false);
HasRequired(e => e.LastUpdatedBy).
WithMany().
HasForeignKey(e => e.LastUpdatedByUserId).
WillCascadeOnDelete(false);
HasRequired(e => e.CreatedBy).
WithMany().
HasForeignKey(e => e.CreatedByUserId).
WillCascadeOnDelete(false);
Map(e => { e.MapInheritedProperties(); e.ToTable("CompanyStations"); });
}
Can anybody tell me why is this happening and have I solved the problem correctly or it is a bit of patch work?
Thanks in advance :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: External database changes -> Hibernate -> Client An existing external system makes regular (every few seconds) updates to several database tables. We want to build a dashboard type user interface which allows the user to view additional records and important updates in near real-time. The user interface would also allow some transactions which would result in database changes.
Our thoughts are to use a stack with Hibernate and Flex (see http://dl.dropbox.com/u/1431390/overview.jpg) but we are open to using any free/open source technology. There are a few issues we are unsure about should we use our proposed stack:
1) How to automatically update the POJOs with database changes? As far as I understand it, there is no way of hibernate knowing about any changes made outside its own session. Therefore, some sort of polling would have to be done to pick up new and changed records.
2) We were planning to push the data to datagrids within a flex UI (using BlazeDS or WebORB). This seems to rely on identifying the changes and pushing these as updates down the channel. However, if we use the Hibernate->POJO approach identifying these changes could be fairly complex as we have refreshed the data. Is there a better solution which will push the changes on the fly? I would have thought this was a common requirement but I can't find much information online.
Any advice would be gratefully appreciated on either the architecture or the specific issues.
Many thanks,
Ken
A: For 1) - Use polling or if you have enough budget use a database that supports pushing JMS messages from triggers (DB2, Oracle, MSSql server).
For 2) - There is a commercial product built by Adobe which can solve this problem easier (it has this feature that you are looking for). It has a steep learning curve and is targeted for enterprise. Otherwise you will have to implement your own solution - refresh only the changed data etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SharePoint 2010,SandBox Solution,uploaded .STP files to _catalogs/lt using Feature not coming in GetCustomListTemplates I have sandbox solution which has 2 features (both are sitecollection level features)
I am activating both feature using same USER.
feature 1 : that uploads .stp files to _catalogs/lt folder via module file
feature 2 (is dependent on feature 1) : it will get all .stp file via .GetCustomListTemplates(spweb) method from _catalogs/lt, but there are no files coming in
here is my code
using (SPSite mySite = properties.Feature.Parent as SPSite)
{
using (SPWeb spWeb = mySite.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;
SPListTemplateCollection listTemplates = mySite.GetCustomListTemplates(spWeb);
}
}
listTemplates has no .stp files.it is coming out empty.
pls help me ...
A: Does your list template derive from one of the default list templates like "Discussion Board"? I noticed that when I tried to do the following I encountered the same problem as you:
*
*Save a SharePoint 2007 "Discussion Board" list as a list template
*Use the method in this blog to convert the template to SharePoint 2010
*Upload the template to my SharePoint 2010 site
I noticed that the default "Discussion Board" list template was not even an option for creating a new list in SharePoint 2010. Therefore I went to the site features and and turned on the "Team Collaboration Lists" just to enable the default "Discussion Board" list template.
After doing that both the default "Discussion Board" list template and my custom "Bulletin Board" template showed up when I went to create a new list. Then I went to my powershell script and noticed that GetCustomListTemplates returned my custom template. I'm assuming that means the C# should work as well.
Here is the list from the old SharePoint 2007 website:
Here is the collaboration feature that enables the "Discussion Board" list template in the new SharePoint 2010 website:
Here is the menu for creating a new list in the new SharePoint 2010 website AFTER enabling the team collaboration lists feature:
As you can see the "BulletinBoard" image is the same as the "Discussion Board" image so SharePoint probably couldn't use the "BulletinBoard" template because the "Discussion Board" template was not yet installed.
A: If you use the Record Center as the template for your root website in SharePoint 2010, GetCustomListTemplates() will always return 0 (zero).
There is some weird bug that makes this happen.
Here is code that you can try running in the SharePoint PowerShell. The return value for GetCustomListTemplates($web).Count will be zero if you have the root web made from the Record Center template.
$site = get-spsite("http://localhost")
$web = $site.RootWeb
$list = $web.Lists["TestDocLibrary"]
$list.SaveAsTemplate("MyListTemplate.stp", "MyListTemplate", "My List Template", $false)
$site.GetCustomListTemplates($web).Count
More information can be found at the following web pages:
*
*http://social.msdn.microsoft.com/Forums/ar/sharepoint2010general/thread/c5455a27-360a-465c-91d5-f81beeac6789
*http://sharepointrecordsmanagement.com/2011/02/
Good luck!
- Jason
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: facebook connect fails on IE9 when a port is used My facebook Website app is configured for a site url using a port number
ie www.example.com:900
Fconnect functionality works in Firefox (all versions) however ie9 gives an error stating
"An error occurred with xxxAppname. Please try again later."
Any help is appreciated.
A: Ensure that the URL for the app is exactly how it is shown in the browser.
Http://www.example.com is different to http://example.com
Also I don't think that you need to include your port number for it to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Opening documents after checkout from SharePoint Why won't my document that i'm checking out from SharePoint not open after the checkout?
The status of the document after the check on SharePoint shows that I checked out the document but it won't open automatically.
What's even more annoying is that I don't know where the file has been checked out to.
Is there any way to find out where the document is being checked out to and how to get it to open automatically after the checkout?
I tried it both on Chrome and IE.
A: Check Out in short means "Reserve the file for me so that no one else makes any changes to it. It does not mean "Open the document"
SharePoint also shows the Checkout status and to whom it is checked out. I will be able to explain more if you tell me "what exactly you see" and why you think these details are missing.
A: In Sharepoint the checkout prevents other user to modify the document.
You can then open the document clicking on the title.
Your client application (Word for example) will open the document directly from the Sharepoint site.
When you will save the document after changes, it will be saved on the site.
You don't need to save a local copy because the document library works like as a shared folder.
You can even connect the document library on a drive letter if you want.
Try this from a command prompt:
net use k: http://YourSite/YourDocumentLibrary
This will create a network drive that point on the library.
(it works only with WebClient service running on client machine).
A: The best way to "checkout and edit" is to open the document using its sharepoint url.
For example, if you have a Word file to edit, you can copy its sharepoint url and go to MS Word and paste it in Open dialog box.
You will be asked for credentials and then it shows the checkout button on top of the document.
Later, you can checkin the edited doc using checkin option in file menu.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Centering text in the middle of the parent element <div id="wrapper" style="height:400px;width:400px;">
<div id="example">
Text
</div>
</div>
I'm looking for a way to get #example into the center (left, right, top, and bottom) of #wrapper.
A: I think there are multiple ways to achieve what you want. One would be:
#wrapper{
display:table-cell;
width:400px;
height:400px;
vertical-align:middle;
border:1px solid red;
}
#example{
width:200px;
margin:auto;
text-align:center;
background:blue;
}
Demo: http://jsfiddle.net/SsD4Q/3/
I hope that helped somehow!
A: Try giving #example margin: 0 auto;
The second property is the left/right margin. Auto should center it.
Edit: Sorry that this does not center vertically. I misunderstood. Please see http://www.jakpsatweb.cz/css/css-vertical-center-solution.html for vertical centering.
A: Vertical alignment is a tricky one unless your using tables.
I suggest you read this aritcle on centering elements.
http://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/
Aligning horizontally however is easy...
Assign a width and use margin:auto
#example {width:100px; margin: 0 auto;}
A: <div id="wrapper" style="height:400px;weight:400px;">
<div id="vertical" style="height: 50%; width: 100%; margin-top: -25px"></div>
<div id="example" style="margin: 0 auto; height: 50px">
Text
</div>
</div>
Set the margin-top minus half the height of the example div
A: I don't like the current proposed solutions... as they rely on either displaying as table-cells, or using static heights on #example and negative margins.
Here is my proposal, considering #wrapper has fixed height:
*
*Set #wrapper's line-height equal to its height;
*Set #wrapper's text-align to center and vertical-align to center;
*Set #example's display to inline-block, so it is centered vertically and horizontally but still works as a block;
*Make #example a span instead, so IE8- allows it to be inline-block.
http://jsfiddle.net/aneves_sw/yse9w/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot build XCode project from command line but can from XCode I've created in XCode a simple navigation-based iPhone app. The app builds and runs properly from under XCode but I cannot get it to build from command line.
From terminal I execute:
xcodebuild -project George.xcodeproj -alltargets -parallelizeTargets -configuration Debug build
but I get that error:
=== BUILD NATIVE TARGET George OF PROJECT George WITH CONFIGURATION Debug ===
Check dependencies
[BEROR]Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain
** BUILD FAILED **
The following build commands failed:
Check dependencies
(1 failure)
Is there something wrong with the way I try to handle it?
A: You can build from the command-line a build targeted at the simulator without signing issues.
This solved the signing issue for me:
xcodebuild -sdk iphonesimulator
Source:
xcodebuild Code Sign error: No matching codesigning identity found:
That's particularly useful if the command line build is there only to sanity check the source code in a continuous integration setup.
A: Most probably your keychain is locked. Try unlocking it before executing the script, you can do it from command line (right before building):
security unlock -p YourPasswordToKeychain ~/Library/Keychains/login.keychain
Note, I'm using "login" keychain which could be different in your case
Also, if that doesn't help, try removing all other parameters and just leave smth like this:
xcodebuild -configuration Debug and clean beforehand xcodebuild -configuration Debug clean
A: I'm using shenzhen, it shows this error too.
Turns out, it happens when I plug in my iPad but it is not in the provision profile. By passing --verbose to shenzhen. it shows:
Check dependencies
Code Sign error: No matching provisioning profiles found: None of the valid provisioning profiles include the devices:
XXXX’s iPad
CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 8.3'
unplug the device, everything works just fine...
A: In addition to unlocking the keychain, you might also specify the codesign identity (or set it in your target). Development certs take the form 'iPhone Developer: Company Inc', distribution certs like this 'iPhone Distribution: Company Inc'.
xcodebuild -project George.xcodeproj -alltargets -parallelizeTargets -configuration Debug build CODE_SIGN_IDENTITY='iPhone Developer: Company Inc'
A: Depending on the purpose of your script, it may also be sufficient to just turn off code signing in the script, which you can do by setting CODE_SIGN_IDENTITY=''
xcodebuild -project George.xcodeproj -alltargets -parallelizeTargets -configuration Debug build CODE_SIGN_IDENTITY=''
Obviously that's no good if you are trying to do a final build from a script, but it may be fine if you're just trying to do a test build for continuous integration (eg from Jenkins, to make sure that nobody has broken anything).
A: I had an archiving error similar but not quite the same as the original post:
** ARCHIVE FAILED **
The following build commands failed:
Check dependencies
(1 failure)
This turned out to be a missing Application Service (in my case, the HealthKit service/entitlement), which I had enabled in my development App ID but not my production App ID.
You enable services in the Apple Member Center: https://developer.apple.com/account/ios/identifiers/bundle/bundleList.action
A: This can be fixed in XCode 8.0 by changing from "iOS Distribution" to "iOS Development" in XCode. It doesn't seem like it should work, but it does for some reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: .NET programs don't run at logon screen - windows 7 I'm using Windows 7 Pro (32bit) and have .NET 3.5 and 4 installed...
I have written a .NET screensaver and have enabled it to run on the Windows logon screen.
My problem is that it errors:
.NET framework initialisation error
BUT when I'm logged in the screensaver works...
So it isn't a faulty installation of the .NET framework, or else it wouldn't work fullstop.
Any ideas?
A: That is not possible on login screen. The core services needed to be able to run a windows program(.Net or not) have not yet been loaded/initialized.
Unless your trying to develop a program outside of windows' jurisdiction (such as bootable, console programs)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple file upload in playframework I'm having some problems with getting multiple file upload to work. When I select x files, it goes through successfully, but the first file is being uploaded x times, and the others are not being uploaded at all. Anyone able to point out what I am doing wrong?
Form:
#{form @Projects.uploadPictures(project.id), enctype:'multipart/form-data'}
<p>
<label>&{'title'}</label>
<input type="text" name="title"/>
<strong>(&{'addPicture.chooseTitle'})</strong>
</p>
<p>
<label>&{'Pictures'}</label>
<input type="file" multiple name="files" id="files"/>
</p>
<p>
<input type="submit" value="&{'publish'}" />
</p>
#{/form}
Handling the files:
public static void uploadPictures(long id, String title, List<Blob> files) {
String error = "";
if(files != null && !title.trim().equals("")) {
Project project = Project.findById(id);
// Save uploaded files
Picture picture;
for(int i = 0; i<files.size(); i++) {
if(files.get(i) != null) {
System.out.println("i: "+i+"\nFiltype: "+files.get(i).type());
if(files.get(i).type().equals("image/jpeg") || files.get(i).type().equals("image/png")) {
picture = new Picture(project, title+"_bilde_"+(i+1), files.get(i));
project.addPicture(picture);
} else {
error += "Fil nummer "+(i+1)+" er av typen "+files.get(i).type()+" og ikke av typen .JPG eller .PNG og ble dermed ikke lagt til. \n";
}
} else {
error = "Ingen filer funnet";
}
}
} else {
error = "Velg en tittel for bildene";
}
if(error.equals("")) {
flash.success("Picture(s) added");
} else {
flash.error(error);
}
addPicture(id);
}
A: Got it to work like this if anyone is ever interested:
public static void uploadPictures(long id, String title, File fake) {
List<Upload> files = (List<Upload>) request.args.get("__UPLOADS");
if(files != null) {
Project project = Project.findById(id);
Picture picture;
Blob image;
InputStream inStream;
for(Upload file: files) {
if(file != null) {
try {
inStream = new java.io.FileInputStream(file.asFile());
image = new Blob();
image.set(inStream, new MimetypesFileTypeMap().getContentType(file.asFile()));
picture = new Picture(project, file.getFileName(), image);
project.addPicture(picture); // stores the picture
} catch (FileNotFoundException e) {
System.out.println(e.toString());
}
}
}
}
addPicture(id); //renders the image upload view
}
Would be happy to get a working solution with an array of Blob objects instead of having to request.args.get("__UPLOADS") if possible.
A: So you can use @As to bind the processing of a param to an specific Play TypeBinder
So with this:
public static void chargedMultiUpload(@As(binder = FileArrayBinder.class) Object xxx) throws IOException{ ... }
And this html
<input type="file" multiple name="files" id="files"/>
So, you have to make a cast with something like File[] doo = (File[])xxx;
A: Should <input type="file" multiple name="files" id="files"/> not be: <input type="file multiple" name="files" id="files"/>?
Second of all, where do you actually save your image? I think you should save it in your loop, where you put project.addPicture(picture);, but actually it looks like the images are saved to the system in your last line: addPicture(id); This kinda explains why it saves the same image (last one or first one (not sure how they are parsed)) multiple times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Strange ClassNotMappedError with sqlalchemy and Python I'm building a rather simple model using sqlalchemy, using a many-to-many relationship defined by an association table and two classes that are to be associated using the declarative syntax.
When generating instances elsewhere in my code, however, I keep on getting ClassNotMappedError.
The model is defined as follows:
from database import Base
immature_product = Table('immature_products', Base.metadata,
Column("immature_id", Integer,
ForeignKey("immature_mirna.id"),
primary_key=True),
Column("mature_id", Integer,
ForeignKey("mature_mirna.id"),
primary_key=True))
class ImmatureMirna(Base):
"""A class representing an immature miRNA."""
__tablename__ = "immature_mirna"
id = Column(Integer, primary_key=True, nullable=False)
name = Column(String, unique=True, nullable=False)
mature_products = relationship("mature_mirna", secondary=immature_product,
backref="precursor")
def __init__(self, name):
self.name = name
class MirnaProduct(Base):
"""A class representing a mature miRNA."""
__tablename__ = "mature_mirna"
id = Column(Integer, primary_key=True, nullable=False)
mature_id = Column(String, unique=True, nullable=False)
def __init__(self, mature_id):
self.mature_id = mature_id
def __repr__(self):
display = "<miRNA product {0} of precursor {1}"
display = display.format(self.mature_id, self.precursor)
return display
Base is a product of declarative_base defined in database.py as follows:
engine = create_engine(DB_URL, convert_unicode=True)
db_session = scoped_session(sessionmaker(bind=engine, autocommit=False,
autoflush=False))
Base = declarative_base()
Base.query = db_session.query_property()
These are in the top level part of the module, without any function wrappers. The same module provides a function to generate the metadata:
def init_db():
"Initializes the database."
import models
Base.metadata.create_all(bind=engine)
A third module, utils generates the instances. The relevant bit of code is:
for key in sorted(result):
entry = ImmatureMirna(key)
db_session.add(entry)
for mature_product in result[key]:
entry.mature_products.append(MirnaProduct(mature_product))
db_session.commit()
The error happens the moment ImmatureMirna is called:
UnmappedClassError: Class 'Table('mature_mirna', MetaData(None), Column('id', Integer(), table=<mature_mirna>, primary_key=True, nullable=False), Column('mature_id', String(), table=<mature_mirna>, nullable=False), schema=None)' is not mapped
A typical use of the code would be:
>>> from mymodule.database import init_db
>>> init_db()
>>> from mymodule.utils import myfunction
>>> myfunction()
However, I'm not sure where the hiccup is.
A: immature_product is not mapped, so the relationship within class ImmatureMirna can't be formed. Change immature_product to be a subclass of Base and I predict it will work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No redraw of QML view in 64bit Win7 (update() in QDeclarativeItem is ignored) I work on a QML-based UI where some elements are implemented in C++ plugin.
Everything worked fine so far in WinXP 32bit and Win7 32bit. Last week I got new laptop with Win7 64bit on board, and my code does not work properly there. Several seconds after start-up application behaves nicely, but then suddenly view stops redrawing. Neither QML-initiated events, nor plug-in calls to QDeclarativeItem::update() work. In plugin I am 100% sure that update() is called, but then I know, that calls to overriden QGraphicsItem::paint() do not happen as expected. The view only gets redrawn when window gets/looses focus.
I have quickly verified my application on a desktop running Win7 and had no problems there. This leads my to suspect that there is something different about how Windows 7 requests window update on my laptop and on other computers, however I am unable to figure out the difference right now.
Can someone help me out to understand what is going on there?
Thanks in advance!
p.s. Unfortunately my primitive mock-ups did not exhibit same problem, and I cannot share production code. If I will find a way to reproduce this problem in a prototype before actual solution will be found, I will post it.
A: Add a qapp->processEvents() after your update() call, it will probably work.
(I've come across a similar problem, but it happens on all platforms, hopefully this solution will work for you)
A: The answer to my question lays in something I overlooked initially in my problem description. The QDeclarativeItem::update() function was called from a non-Qt thread (certainly not GUI thread). I re-routed the call through Qt event loop and the problem was gone.
I was on Qt 4.7/4.8 at that time and cannot say how it'd behave in Qt 5.x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Entity Framework - Eager loading of subclass related objects I wonder if there is a possibility to eager load related entities for certain subclass of given class.
Class structure is below
Order has relation to many base suborder classes (SuborderBase). MySubOrder class inherits from SuborderBase. I want to specify path for Include() to load MySubOrder related entities (Customer) when loading Order, but I got an error claiming that there is no relation between SuborderBase and Customer. But relation exists between MySubOrder and Customer.
Below is query that fails
Context.Orders.Include("SubOrderBases").Include("SubOrderBases.Customers")
How can I specify that explicitly?
Update. Entity scheme is below
A: This is a solution which requires only a single roundtrip:
var orders = Context.Orders
.Select(o => new
{
Order = o,
SubOrderBases = o.SubOrderBases.Where(s => !(s is MyOrder)),
MyOrdersWithCustomers = o.SubOrderBases.OfType<MyOrder>()
.Select(m => new
{
MyOrder = m,
Customers = m.Customers
})
})
.ToList() // <- query is executed here, the rest happens in memory
.Select(a =>
{
a.Order.SubOrderBases = new List<SubOrderBase>(
a.SubOrderBases.Concat(
a.MyOrdersWithCustomers.Select(m =>
{
m.MyOrder.Customers = m.Customers;
return m.MyOrder;
})));
return a.Order;
})
.ToList();
It is basically a projection into an anonymous type collection. Afterwards the query result is transformed into entities and navigation properties in memory. (It also works with disabled tracking.)
If you don't need entities you can omit the whole part after the first ToList() and work directly with the result in the anonymous objects.
If you must modify this object graph and need change tracking, I am not sure if this approach is safe because the navigation properties are not completely set when the data are loaded - for example MyOrder.Customers is null after the projection and then setting relationship properties in memory could be detected as a modification which it isn't and cause trouble when you call SaveChanges.
Projections are made for readonly scenarios, not for modifications. If you need change tracking the probably safer way is to load full entities in multiple roundtrips as there is no way to use Include in a single roundtrip to load the whole object graph in your situation.
A: Suppose u loaded the orders list as lstOrders, try this:
foreach (Orders order in lstOrders)
order.SubOrderBases.Load();
and the same for the customers..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: In what way and in which cases we have to use the NSFastEnumeration in iphone In what way and in which cases we have to use the NSFastEnumeration in iphone can anyone tell me the sample codes to how to use these fast enumeration in iphone
A: NSFastEnumeration is a protocol that your classes can adopt that allows you to use the fast enumeration construct for iterating over a collection of objects managed by your class. That is you will be able to write:
for (Object * obj in MYAwesomeObject) {
//do awesome stuff here.
}
The built-in collection classes in Foundation already implement this (NSArray, NSSet, NSDictionary) which cover many many needs for collection objects. If, say, you wanted to implement a particular tree structure, you can have your class adopt NSFastEnumeration to allow you to iterate over all the objects in the tree without having to handle traversing directly. In this case, your class has to implement -countByEnumeratingWithState:objects:count: to conform to the protocol which returns (through reference) a C array of objects to iterate over.
A: NSFastEnumeration is here to speed op loops.
So dont use:
for (in i =0; i < [myArray count]; i++){
id object [myArray objectAtIndex:i];
}
but use:
for (id object in myArray)
This will make the looping thru the array much faster.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adobe AIR SQLite Async Events Not Dispatching Working on an application that has very heavy use of the local sqlite db. Initially it was setup for synchronous database communication, but with such heavy usage we were seeing the application "freeze" for brief periods fairly often.
After doing a refactor to asynchronous communication we are seeing a different issue. The application seems to be far less reliable. Jobs seem to simply not complete. After much debugging and tweaking the problem seems to be the database event handles not always being caught. I'm seeing this specifically when beginning a transaction or closing the connection.
Here is an example:
con.addEventListener(SQLErrorEvent.ERROR, tran_ErrorHandler);
con.addEventListener(SQLEvent.BEGIN, con_beginHandler);
con.begin(SQLTransactionLockType.IMMEDIATE);
Most of the time this works just fine. But every now and then con_beginHandler isn't hit after con.begin is called. This makes it so we have an open transaction that never gets committed and can really hang up future requests. When investigating this same issue with the connection close handler, one of the solutions was to simply delay it. In that context it was OK to wait even several seconds.
setTimeout(function():void{ con.begin(SQLTransactionLockType.IMMEDIATE); }, 1000);
Changing to something like this does seem to make the transaction more reliable, however, that really stretches out the time it takes for the application to complete actions. This is a very db heavy application, so even adding 200ms has a noticeable affect. But something as short as 200ms also doesn't seem to fully solve the issue. It has to be 500-1000ms or higher in order for me to stop seeing this issue.
I've written a separate AIR application to try and stress test our code and the transactions, but am unable to reproduce this in that environment. I even have it try to do something that will "freeze" the application (long loops that do some math or other processing) to see if application strain is what makes them misfire, but everything seems reliable.
I'm at a loss for how to resolve this at this point. I even tried running con.begin off of a binding event, just to add more time. The only thing that seems to work is excessively long timers/timeouts, which I don't think is an acceptable solution.
Has anybody else run into this? Is there some trick to async that I'm missing?
A: I had a few more ideas to try after the refreshing weekend, none of which panned out; however, during these attempts and more investigations I finally found a pattern to the issue. Even though it doesn’t happen consistently, when it does happen it is fairly consistent on where it happens. There are 1 or 2 spots during the problematic processes that try to compact the DB after doing data clearing, in order to help keep the file sizes smaller. I think the issue here is compact wasn’t worked into the async flow properly. So while we are trying to compact the db, we are also trying to start up the new transaction. So if the compact takes a bit of time every once in a while, then we get a hang up. I think the assumed behavior was for async event handling to dispatch when the transaction is finally started instead of just never happening at all, but this does make some amount of sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where to set the Converter for items of a collection in XAML I just made my first converter to convert from int to string. I have a combobox fill with integers(years) but if the value is 0 I want the combobox to show 'All'.
This is my converter:
public class IntToString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
int intY = (int)value;
if (intY == 0)
{
String strY = "All";
return strY;
}
else
{
return intY.ToString();
}
}
return String.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
}
}
In XAML where should I set the converter ? I tried in the ItemsSource of the combobox:
ItemsSource="{Binding YearsCollection, Converter={StaticResource intToStringYearConverter}}"
But I always get InvalidcastException on this line:
int intY = (int)value;
A: The problem is that you are trying to convert the entire collection rather than just one item from the collection.
You would want to do something like this:
<ListBox ItemsSource="{Binding YearsCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border DataContext="{Binding Converter={StaticResource intToStringYearConverter}">
...
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
A: You can't use the converter like this, converter in ItemsSource is supposed to convert whole collection, not individual items. The collection object can't be cast to integer, so you get the exception.
You have to use DataTemplate and apply the converter on individual items.
Or - if all you need is cast to int - you could use ItemStringFormat.
Also, for setting the default message when the source is null, you can use TargetNullValue property of a Binding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cakephp REST integration with iPhone app I'm developing backend system for iPhone app providing JSON data for each request for iPhone app. This is Cakephp based backend system and I was wondering if there was a good Cake way to receive POST request?
I understand using Router::mapResources(), Router::parseExtensions(), requestHandler component, Xml and Javascript helper is the correct way of creating RESTful application? If so, I was wondering how we could set them up to accept POST requests and potentially XML and/or JSON aswell.
Thank you
A:
I was wondering if there was a good Cake way to receive POST request?
send a POST request to the correct url, and you can process it as normal. The POST data is in $this->data in the controller.
If so, I was wondering how we could set them up to accept POST requests and potentially XML and/or JSON aswell.
XML and JSON are not in the same category as POST. Read about REST setup here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stored Procedure Tuning I have a big stored procedure, which runs for 2-3 secs at 100% CPU. Its not a big deal, if the SP runs once for a while, however this particular SP runs every second. so you can understand the total processor usage in a minute and through-out the day.
This stored procedure contains lots of queries, temporary tables, one or two cursors and some dynamic queries.
what will the best possible solution to tune-up my SP, and different ways to do that.
What are the points we need to remember while writing an SP in general?
Please Help...
A: To tune up your stored procedure you need to address each query and process contained within it individually. Make sure that your indexes are set correctly and check whether your approach with the temp tables and dynamic SQL is appropriate. Also make sure that you're not abusing other stored procs and views that may have been designed to be used directly rather than as cogs in a larger process.
It is difficult to make more suggestions but, from your description on what is entailed in the stored procedure and how often it runs, it sounds like this is a key process in your system and the data involved a likely candidate for denormalization. If you denormalize the data then you would rewrite the stored proc to query that part of the database to get better performance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multi-threading Code stuck with Form.ShowDialog() statement I am new to C# and was trying to write a form a test a network connection. The idea is that put the connection part in a thread and show a progress dialog during the connection. The following is my code:
Form_TestingConnection testingConnection = new Form_TestingConnection();
Thread t1 = new Thread(TestConnection);
try
{
testingConnection.ShowDialog();
t1.Start();
}
catch (Exception ex)
{
Logger.Error(ex);
if (MessageBox.Show(
Resources.message_connection_issue,
Resources.title_connection_issue,
MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
{
loginSuccessful = false;
}
}
TestConnection is a method to test the connection and set a static member loginSuccessful based on result. The issue I am having now is that the code stuck with testingConnection.ShowDialog(). Whenever it executes to this place, it never goes forward. Any suggestions? Thanks a lot.
A: ShowDialog shows the form modally. This means that the form will show, all other forms will be disabled, and the ShowDialog function will not return until the modal dialog is closed.
Use Show instead. This shows the form modeless. When you do that the Show function returns immediately and the form stays open.
You can think of ShowDialog as being synchronous and Show as being asynchronous.
Make sure that any methods in the thread which need to update progress on the form are called using Invoke or BeginInvoke to ensure that they run in the context of the main UI thread.
Finally, your code as it stands does not wait until the thread has done its work. The try/catch block only wraps the form show and the beginning of the thread's execution (t1.Start()). When you call Start on a thread that call returns asynchronously and the thread continues to do its work. I'm not quite sure what your code is trying to do, but I suspect that the catch block should be inside the thread.
A: If you are trying to access any GUI component which belongs to a thread from another thread you should use InvokeRequired to avoid the cross thread exceptions
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to convert a System.IO.Packaging.Package to HTML? Microsoft Word interoperability classes will let you get at a property called WordOpenXML. This represents a package that will be stored - zipped up - in a .docx file and can be opened by Microsoft Word. However, is there a way to convert this Package to other formats, notably HTML?
I read in an answer to an old question that "Word 2007 has an API that you can use to convert to HTML. [...] You can find documentation around the API, but I remember that there is a convert to HTML function in the API." I'm not 100% sure which API that guy is talking about but perhaps it's System.IO.Packaging.Package or something similar. I can't seem to find any "convert to HTML function"; does anyone know how you can convert a Package format Word document into HTML?
A: The API in question is probably the Save method on the document; when a file type of HTML is chosen, Word transforms the document into HTML, and applies the appropriate styling.
Chances are, given that the docx format is XML, there is an XSLT transformation of some sort going on; this is just speculation, but it's not far-fetched, as XSLT is commonly used to create HTML from XML.
That said, what you are looking for probably does not reside in the Package class, nor should it. The Package class is used for creating packages of content, not with the transformation of that content.
However, there's nothing stopping you from providing the transformation of that content; you can get the XML that is the basis of the Word document and then apply your own XSLT which would produce the HTML that you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7635180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |