text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Entity Framework projection into class is faster than selecting EF POCO objects, WHY? This one confounds me.
I am using EF 4.1 and have applied a T4 template to the model to use POCO's and POCO proxies (public paramaterless ctor, all properties are virtual, all navigation properties are ICollection).
I have a table with around 1.1M records in it. I was doing some timing tests to see how long it takes to retrieve this data and got some unexpected results.
This call returns in about 21 seconds:
ctx.Valuations.MergeOption = MergeOption.NoTracking
var entityValuations = ctx.Valuations.OfType<Foo>().ToArray();
This call takes 9 seconds:
ctx.Valuations.MergeOption = MergeOption.NoTracking
var entityValuations = ctx.Valuations.OfType<Foo>().Select(v => new Val()
{
ID = v.ID
...
//set all properties
....
}).ToArray();
The only difference between these two statements is that the first returns EF poco proxies and the second projects the result set into a non-proxy poco. That is such a HUGE difference in performance time! I am completely stumped as to why and cannot come up with any legitimate reason.
Does anyone know why the second statement is so much faster?
A: POCO proxies are just that - proxies. A new proxy class must be created for every one and added to the context. Although you have essentially said 'dont track them in the context' Id think it would be a bit faster, but I think you are creating an additional 1.1M objects that are proxies.
Note from: http://msdn.microsoft.com/en-us/library/dd456853.aspx
"
You can have a mix of POCO entities and proxy entity objects. To disable creating proxy objects, set the value of the ProxyCreationEnabled property to false on the instance of ObjectContextOptions that is returned by the ContextOptions property on the ObjectContext:
"
It would be an interesting test to turn off the proxy on the context via ProxyCreationEnabled and see what your result is - I'd gather similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to listen or poll for an event I have an Android app in which I'd like to display a fullscreen ad as soon as it becomes available. The ad network's SDK allows me to call a "ready" method to determine whether the ad is ready to display; it returns a boolean. How do I listen for this? Should I be polling this method every few seconds? What's the best Android practice to do this?
A: The alternative to polling is for the source of the change to generate an event to which you can match a handler, but from you've described, the network's SDK doesn't generate an event. Seems like polling is all you have to work with. You could put the polling code is some small class that just polls. When the polling detects the ad becoming "ready", you can generate an event (I would recommend looking at Google's Guava library at their EventBus) and the rest of your application can respond to the event. You might multiple points that require knowledge of the ad becoming "ready" -- you wouldn't want them all polling independently.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: render multiple HTML tables I have a Rails Table, called Sales, that I would like to render in a sequence of HTML tables on a single HTML page.
The Sales Table contains a list of sales transactions made by SalesPeople (salesperson_id is a field within each Sales record), and I would like to list each of their Sales records grouped in HTML tables, by salesperson_id. Similar to this:
Sales Person : Bob
*PRODUCT* *QUANTITY*
Widgets 17
Cogs 5
Screws 100
Sales Person : Jim
*PRODUCT* *QUANTITY*
Bozzles 49
Widgets 20
Screws 250
Flurbs 22
Now, my first thoughts were that I would 'find_all' sales transactions meeting my criteria, and then loop through the returned array, and rendering each SalesPerson using a _partial, but I'm aware I can only perform one render per result.
Is it possible to achieve this using a single render, do I need some HTML / JavaScript magic, or is there another solution?
Thanks.
A: You can only render once like you said, so you cant render for each sales person.
You can use a single render if you pass the sales transactions to the partial (refer to http://guides.rubyonrails.org/layouts_and_rendering.html#using-render 3.4.4 passing local variables), but inside that partial you will do the "html/javascript magic" anyway.
Inside the partial, you need to use the ruby foreach to print each table, like this:
<% salesTransactions.each do |transaction| %>
<table>
<tr><td>Product</td><td>Quantity</td></tr>
<tr><td>Widgets</td><td><%= transaction.widgets %></td>
//.....
</table>
<% end %>
I am guessing you want to reuse that partial somewhere else? If not, you can simple do all the stuff inside the view.
A: OK, I figured out a way to achieve what I want to achieve by using group_by, with help from this RailsCast,
http://railscasts.com/episodes/29-group-by-month (#29 of a brilliant series)
So, I use group_by to group the sales by salesperson_id, then in my view,
<% @groupedSales.each do |salesperson_id, sales| %>
<h2><%= Salesperson.find(salesperson_id).name %></h2>
<table>
<thead>
<tr>
<th>Date</th>
<th>Product</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<% sales.each do |sales_activity| %>
<tr>
<td><%= sales_activity.created_at.strftime('%d/%m/%y') %></td>
<td><%= sales_activity.product %></td>
<td><%= sales_activity.quantity %></td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XNA and FBX Coloring Problem My problem is that, if I use BasicEffect (and setup VertexColorEnabled = true) or my own shader, and use only colored (not textured!) models, it gives the error that Color0 is missing...Isn't it weird that .fbx models do not come with COLOR0 channel ?
A: Here is what I found..... (Marshall Belew @ forums.create.msdn.com/forums/p/16066/553792.aspx#553792) Saved my day...
The solution is simple: the BasicShader has a DiffuseColor property. I merely added a new field into the Toon shader, and any time there was no texture, I substituted the color value.
I am happier with this solution because now I don't have to write a ton of vertex declaration / draw primitive logic.
From the .fx file:
// Pixel shader applies a cartoon shading algorithm.
float4 ToonPixelShader(LightingPixelShaderInput input) : COLOR0
{
float4 color = TextureEnabled ? tex2D(Sampler, input.TextureCoordinate) : DiffuseColor;
Replacing the effects (this is a modified snipet from the NonPhotoRealistic sample).
// Scan over all the effects currently on the mesh.
foreach (BasicEffect oldEffect in mesh.Effects)
{
// If we haven't already seen this effect...
if (!effectMapping.ContainsKey(oldEffect))
{
// Make a clone of our replacement effect. We can't just use
// it directly, because the same effect might need to be
// applied several times to different parts of the model using
// a different texture each time, so we need a fresh copy each
// time we want to set a different texture into it.
Effect newEffect = replacementEffect.Clone(
replacementEffect.GraphicsDevice);
// Copy across the texture from the original effect.
newEffect.Parameters["Texture"].SetValue(oldEffect.Texture);
newEffect.Parameters["TextureEnabled"].SetValue(
oldEffect.TextureEnabled);
Vector4 color = new Vector4(oldEffect.DiffuseColor, 1.0f);
newEffect.Parameters["DiffuseColor"].SetValue(color);
effectMapping.Add(oldEffect, newEffect);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you make a Caption Less Window in Gtk? I want to make a Window in Gtk (Gtk# to be specific, but GTK+ or any other binding will do, the functions are generally the same) without a caption. Kind of like Mozilla Firefox 4 and Google Chrome. I don't know what to call it, caption less or widget on caption? Any Help? Thanks
A: The term is 'decorated'.
In plain GTK+, this is gtk_window_set_decorated() and in GTK#, do this.Decorated = false; in your forms constructor, that's all.
Note that decoration is not only the title bar but also the frame that allows for resizing. There is unfortunately no way to have a resizable but title-bar-less window, you will have to handle border mouse-over-detection and resizing yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What are nested types? I quote from the JLS 9.1.1.2 strictfp Interfaces
"The effect of the strictfp modifier is to make all float or double expressions within the interface declaration be explicitly FP-strict. This implies that all nested types declared in the interface are implicitly strictfp."
So, what are nested types? Does it actually means nested reference types?
UPDATE:
I meant, I need a definition of nested types.
A: A nested class is one declared inside another class, like this.
class SomeClass {
class Nested {
}
static class StaticNested {
}
}
You can also nest inside interfaces:
interface SomeInterface {
class Nested {
}
static class StaticNested {
}
}
The implication of this in terms of your question is if you do this:
strictfp interface SomeInterface {
or
strictfp class SomeClass {
Then when you have something inside
class Nested {
It is implicitly
strictfp class Nested {
A: An interface can have nested interface inside its definition. It implies that when you place strictfp on the interface all the nested interfaces are also strictfp.
Note: Given many JVM are strictfp by default for almost all operations, it may be hard to tell the difference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linq query for grouping I have to generate say Customers Report.
there is condition for grouping records like
grouped and/or filtered by CustomerFirstName\CustomerCity
or CustomerLastName\CustomerCity
What would this Linq query look like?
A: Simple image representation of group by might help you
Full aricle : SQL to LINQ ( Visual Representation )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Do not match if within tag I have this regex which detects url formatted text:
/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/
so it would detect something like http://google.com
My problem is that I do not want it to detect the links when the links are inside tags such as <a href="http://google.com">http://www.google.com</a> - so in there it should not detect anything. Help?
EDIT - I do NOT want to match the anchor tag. The above regex matches links inside anchor tags which is what I do not want. I need it to match links only outside of tags.
A: this one should work
/(?!href.*?=.*?['"]+)(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/
A: /(?<!href=['"])(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UIButton changes his background color for a while from white to gray I have an UIButton with an image made with a white background and a figure in the center. On click this image must be changed with another. The problem born when i click on button his background become light gray while it change the image. It happens only the first time i click. I made this app to play sound when i click on button and change the image. When the sound finishes to play, the image return to the original.
This is the viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
imageOpen = [UIImage imageNamed:@"aperto.jpg"];
imageClosed = [UIImage imageNamed:@"chiuso.jpg"];
CGRect rect = CGRectMake(([UIScreen mainScreen].bounds.size.width - imageOpen.size.width)/2,([UIScreen mainScreen].bounds.size.height - imageOpen.size.height)/2, imageOpen.size.width, imageOpen.size.height);
[bottone setFrame:rect];
[bottone setImage: imageOpen forState: UIControlStateNormal];
...
}
This is the function called when the button is clicked:
- (IBAction)launchDialog
{
[bottone setImage:imageClosed forState: UIControlStateNormal];
if(self.player.playing==TRUE){
[self.player stop];
}
self.player.currentTime = 0;
[self.player play];
}
And this is the method called when the sound finishes to play:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[bottone setImage: imageOpen forState: UIControlStateNormal];
}
What is the problem? what can i do?
A: You need to set all the states of your button. Did you do that where you indicate that you are configuring the button with //...?
These are the four states that you have to set:
UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does it affect site performance and SEO to use onclick handler instead of links? To call new windows, JavaScript functions and other internal stuff I've been using onclick along with cursor: pointer rather than using links with JavaScript in the href attribute. This prevents # from appearing in the URL in the status bar.
When linking to other pages I use normals hrefs with a friendly URL.
My Questions
*
*Does using onclick instead of JavaScript in a link's href affect performance?
*Does it affect search engine rankings?
A: To start off, it's a bad idea to practice this, because users who have disabled JavaScript cannot navigate at your site any more (NoScript).
That aside, it's not possible to rightclick, and bookmark/open the page in a new window.
If you don't want these "internal pages" to be indexed, add rel="nofollow" to your links.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apache Shiro & Java Security for Novices I know next-to-nothing about Java's security model, including XML configuration, policy-setting, any security framework components, tools (such as keystore, etc.) and everything in between.
Although I understand it will eventually become essential for me to roll up my sleeves and learn Java security in-depth, I was wondering if using something like Apache Shiro would help ease the transition a bit. As such, I have a few concerns with it.
Is Shiro, essentially, a "turnkey, catchall wrapper" for implementing security in Java applications (and more particularly, web apps). Meaning, can one configure Shiro with their project and essentially tune it do all the same configuration, policy settings, etc. that one would have to do "manually" (piecemeal) without it? If not, what shortcomings does Shiro have (what are some big things Shiro can't do for me that are vital)? Are there any large vulnerabilities that Shiro doesn't address at all?
Along the same lines, I've heard good things about OWASP's ESAPI framework. Aybody have experience with both? Can ESAPI and Shiro be configured to work together or is it simply a binary "one or the other" type deal?
Thanks in advance!
A: The short answer is yes. Both Shiro and ESAPI can work together, although there is a lt of redundant functionality between the two APIs. Shiro gives you everything you need for covering the standard Java security model. ESAPI goes above and beyond by providing OWASP's globally-standardized security mechanisms.
Shiro should be used by novices like myself who really don't understand Java security and/or general applications/server security. It takes care of a lot of things for the security-ignorant. ESAPI should be used by programming security professionals that already understand Java security and want to leverage not only everything that comes with Java EE but need to go the extra mile and make things even more secure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Using jgGrid with API(providing local data) for search/paging We are developing a javascript application. This application will be using jqGrid for its grid rendering purpose. We have javascript "API" available which provides functionality to bring in the data from the server.
The API provides data in JSON format, this data contains information like: {totalResults, pageNumber, nrRecords, the actual array of rows}
Now we need to populate the jqGrid using this API. So, we wont be using the url property of the grid. We also want the pagination/search to work using the API available. This API has functions which take searchParams as argument and return data from the server after applying the searchParams.
Whatever study we did on jqGrid, we couldnt find a way to integrate this API with jqGrid. We tried by doing this so far:
$('#grid').jqGrid({
data: this.gridData, // Initial data returned by the API in JSON format, suppose 5 rows
datatype: "local",
colNames:['Id', 'Name'],
colModel:[ {name:'id', index:'id', width:20},
{name:'firstName', index:'firstName', width:80},
]
onPaging: function (pgButton) {
// Use the API to get the next page data and populate the jqGrid
}
rowNum: this.gridData.length,
rowTotal: this.getTotalGridLength, // This part is not working!!
)};
In the above, we are getting the grid with 5 rows only and the next button is not active. How do we set the total count of rows (this.getTotalGridLength) so when the user clicks on next, we get the new data in the onPaging function and replace the grid accordingly?
This is the first hurdle, we also need to make search/filter work using the same API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Blame on an earlier version of a file in a different location At one point my git repository had its paths reorganized.
I often want to do a blame on a file at a revision before the move.
What's the git blame incantation to blame a file that doesn't exist in the current repository?
I tried:
> git blame new/path/to/file old_rev
fatal: no such path ... in old_rev
> git blame old/path/to/file old_rev
fatal: cannot stat path ... in old_rev
> git blame old_rev:old/path/to/file old_rev
fatal: cannot stat path ... in old_rev
Clearly I could just check out old_rev and blame the appropriate path, but I'd rather avoid that.
A: You can use git blame --follow to make blame follow your renames.
I also see your parameters are in the wrong order, try the following:
git blame old_rev -- old/path/to/file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: C# WriteAttributeString - Multiple Elements I'm using System.Xml to create an XML document. I need to create something similar to the following:
<Communication primary="N" value="heisenburg@albuquerquecarwash.com" purpose="PERSONAL" type="EMAIL"/>
I can use 'WriteAttributeString' to get as far as this:
<Communication primary="N"/>
The problem is it won't let me add any more attributes and I'm a bit stuck. Any help/advice would be much appreciated.
Edit: The code is below to create the above XML:
writer.WriteStartElement("CommunicationList");
writer.WriteStartElement("Communication");
writer.WriteAttributeString("primary", "N");
writer.WriteEndElement();
writer.WriteEndElement();
I need to add the 'Value', 'Purpose' and 'Type' attributes to this and I'm at a loss.
Thanks
A: This should render what you want:
writer.WriteStartElement("CommunicationList");
writer.WriteStartElement("Communication");
writer.WriteAttributeString("primary", "N");
writer.WriteAttributeString("value", "heisenburg@albuquerquecarwash.com");
writer.WriteAttributeString("purpose", "PERSONAL");
writer.WriteAttributeString("type", "EMAIL");
writer.WriteEndElement();
writer.WriteEndElement();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: entity data framework - 101 I am used to using datasets for my projects in terms of data access. I now set myself an easy app to work on in order to learn the entity data framework and how to retrieve & manipulate data.
All the tutorials and samples I have found on the internet are too advanced for me.
Can anyone guide me through on where to start, what are the advantages of this model, In what scenarios should I choose to use entity framework and what are the things (basis) I should now before starting.
My datasets are working fine too. Are there any reasons for me not to stick with that way of accessing data? Or is this something to consider depending on the users of the website (for speed purposes etc.)
Any information - guidance would be appreciated.
Thank you in advance..
A: The question you're asking ("When should I use an ORM as opposed to DataSets/hardcoded SQL?") is a little too broad to be addressed adequately on a Q&A website. However, here are a couple of the high points:
*
*ORM's provide safety because they generate classes from the tables in your database (or the other way around, should you choose to go that route) and you perform your in-code interaction on those classes instead of embedding field and table names into your code. This provides you with compile-time safety, ensuring that you don't fat-finger one of those and discover it hidden deep within the recesses of your application six months after it's been deployed.
*ORM's provide a more natural means of accessing related entities (I can do things like 'customer.Orders' or 'order.Customer' in code) rather than either embedding SQL in a string or accessing everything via stored procedures
And a couple of disadvantages
*
*In all but the simplest operations, ORM-generated SQL is likely to be slower than hand-crafted SQL or stored procedures. You use an ORM for safety and convenience, not for speed.
*It's easy to use features like lazy loading (where related entities are loaded on-demand rather than up front) and incur a performance penalty without realizing it.
*In order to take full advantage of an ORM (meaning relations and using it throughout updates, deletions, and inserts), you generally have to bring back an entire object into memory rather than just a portion.
A: I agree with all the points Adam Robinson made, but I would add however, the move to an ORM (in my case EF4.0) was all about developer productivity. Previously I did all hand coded classes and data access methods, and carefully crafted stored procs for all data access - and quite frankly the performance could not be beat by just about anything - but all that hand coding requires a lot of time.
I would conservatively estimate that I am cutting most of my development efforts in half using EF4.0 instead of my old methods, and my users have not noticed any perceptible slow down. In the few cases where I do need extra performance, I can still hand coded some data access and/or a stored procedure to get some extra oomph when needed.
So, in answer to your question, there is nothing "wrong" with your way of doing things, but you should go thru the whole process of learning an ORM, and then see if they pros outweigh the cons for you.
A: The learning curve for ORMs (any ORM) is significant. Don't let the simplistic code generation at the beginning of the process fool you.
If someone knew both ORMs and datasets, I think they would choose the ORM 99% of the time, the advantages are that compelling. ORMs aren't perfect, but they are way better than datasets in almost every scenario.
That said, if datasets are working for you, and the learning curve of ORMs is stumping you, it is completely okay to stick with datasets. I would encourage you to keep hitting the learning curve for ORMs even if it takes years of on and off study (and it might).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type java.util.Hashtable localParams.put(name, values); I have got 2 warning:
-- The First is :
HELPDESKGESTION2\src\java\glpi\filter\LoginFilter.java:289: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type java.util.Hashtable
localParams.put(key, value);
^
--The Second is :
HELPDESKGESTION2\src\java\glpi\filter\LoginFilter.java:292: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type java.util.Hashtable
localParams.put(name, values);
^
The Code ho generate this warnings is :
public void setParameter(String name, String []values) {
if (debug) System.out.println("LoginFilter::setParameter(" + name + "=" + values + ")" + " localParams = "+ localParams);
if (localParams == null) {
localParams = new Hashtable();
// Copy the parameters from the underlying request.
Map wrappedParams = getRequest().getParameterMap();
Set keySet = wrappedParams.keySet();
for (Iterator it = keySet.iterator(); it.hasNext(); ) {
Object key = it.next();
Object value = wrappedParams.get(key);
localParams.put(key, value);
}
}
localParams.put(name, values);
}
A: Replace:
localParams = new Hashtable();
With:
localParams = new Hashtable<String,String>();
I assume you have a global variable like the following:
private Hashtable localParams;
Replace that with:
private Hashtable<String,String> localParams;
If you make the changes I suggested the warnings will go away but you will also have to replace all of your Object with String;
A: General thing is that you have to mention which type will represent the object that you are going to create. just think you have a lot of cars. you are going to meet someone. that person knows every car you have. but he doesn't know by which one you are coming this time. then he can't identify you at once when you coming. but if you had mentioned by which car you are coming earlier, he can easily identify you from far away also.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Validation Hint on Controls in Asp.Net I want implement Validation Hint on my Form Fields Same as Hotmail.com See the Below Screenshot. Can Any Tell me What should i do for that ? Jquery, Javascript or CSS Please Post Some tutorial that will be Great.
regards,
A: jQuery has a great plugin:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
That plugin is highly regarded and offers all the customization you need.
As far as styling goes the validation Hotmail uses is just a tooltip or div that is styled to look like a tooltip.
Some tooltip plugins:
http://www.1stwebdesigner.com/css/stylish-jquery-tooltip-plugins-webdesign/
A: Qtip is a good tooltip plugin and can customised to great extent.
http://craigsworks.com/projects/qtip/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "error:ReferenceError: Security error: attempted to read protected variable: write" with Opera 11.5 and window.open and document.write I am having an issue with window.open that only occurs with Opera (version 11.5).
function openpageopera()
{
var w = window.open("","_blank");
try
{
w.document.write("<p>hello</p>world");
w.document.close();
}
catch(err)
{
alert("error:" + err);
}
}
Now, it works flawlessly when I execute this function after the page has loaded, ergo:
$(document).ready(function() {
openpageopera();
});
And it also work if I'm opening a URL like google, yahoo, or even a webpage from my web server.
However, when I attach it to an onclick event, like on an HTML button, it fails.
<input type="button" value="Fails" onclick="openpageopera();">
What fails specifically? Well, the page does open but it's blank. document.write is NOT working. The catch noted an error of:
error:ReferenceError: Security error: attempted to read protected variable: write
I don't understand why executing this on the html button raises a security error. Why is this occurring and how can I resolve it?
Thank you very much for your help!
A: If there is code somewhere setting document.domain it might change the parent page's security context. (This also happens if document.domain is set to its current value.) When you open "" or about:blank it should inherit the parent's security context and document.write() should work - but I know Opera had some bugs in the past where setting document.domain would cause problems when working with empty popups. I believe those bugs are fixed in 11.50, but it seems as if you ran into a similar issue. Do avoid setting document.domain if you can..
If you see this problem occur again, please let me know and preferably let me see the full code. I'd love to nail this bug in every incarnation..
BTW, keep in mind that User JS, extensions, and even JS triggered from plugins might also mess around with document.domain, so try to disable anything that might interfere.
A: I ended clearing all private data in the Opera browser and it worked. However, every time I loaded the page, I made sure to press shift or ctrl refresh to clear the cache. Either it was a cache issue or something else entirely.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is the fastest way to skip unicode characters I am trying to get to certain charcters in a file that is in UTF-16 format.
I know how many characters I want to skip. I am currently using the TextReader.ReadBlock command to read a temporary array of all of the characters I want to skip, but I believe that setting the position would be faster. I just do not how to determine the new position.
Any idea what would be the fastest way to skip to a position in a unicode file if you have how many characters that you want to skip?
A: It's not so easy to skip a block, that requires relative positioning.
If you can calculate the begiining of the next block (offset from the start of the file) it is doable:
int nextPos = ...;
reader.DiscardBufferedData();
reader.BaseStream.Position = nextPos;
line = reader.ReadLine();
You may have to tweak your calculation because UTF-16 file can have a BOM (2 leading bytes).
A: Considwring that this os UTF-16 and not UTF-8 (where character size can vary) you have 2 bytes per character. So to skip x characters you have to skip x*2 bytes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Paper size setting won't save for Snow Leopard I am using a Zebra LP 2844 to print barcode labels out of the Chrome browser, as it has good printing support for this purpose.
The one problem that I cannot seem to solve is that the paper size is never maintained after a label has printed.
This is true of other applications as well and seems to be an issue with the OS.
Even if the presets are saved, the paper size always defaults back to US Letter, or in the case of the machine in question, "Other."
I have looked at the plist for that printer as well as the printing plist, and the default paper size is set to the one I created for the Zebra.
However, as soon as that paper size is selected in the print dialog, and the document prints, the next time it prints, the paper size is back to default.
Does anyone know how to defeat this?
I have repaired permissions, deleted plists, etc.
Thanks so much.
A: after many hours of toil, i found the simplest of solutions. simply open TextEdit, go to Page Setup and set up your presets there and click OK.
then File > Print and do the same thing in that window being sure to save a new preset with your customer paper size or any other paper size.
once this is done, these settings should be available in other applications.
there may be another solution, but this worked for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I bind latexmk to one key in Emacs and have it show errors if there are any I'm using AUCTeX and I would like to bind a key, e.g. C-0, that does the following:
*
*Saves the active file without prompting me.
*Runs latexmk on the active file without prompting me.
*Shows me errors if latexmk encounters any by .
My problem is not how to bind a key (for which Tyler posted a link in a comment below) but how to come up with a function that accomplishes item 1–3.
I call Latexmk by
(add-hook 'LaTeX-mode-hook (lambda ()
(push
'("Latexmk" "latexmk %s" TeX-run-TeX nil t
:help "Run Latexmk on file")
TeX-command-list)))
This is my .latexmkrc
$pdf_mode = 1;
$recorder = 1;
$latex = 'latex -recorder -halt-on-error -interaction=nonstopmode -shell-escape';
$pdflatex = 'pdflatex -recorder -halt-on-error -interaction=nonstopmode -shell-escape';
I'm using Emacs 23.3 and AUCTeX 11.86.
A: Does this do what you want?
(defun my-tex ()
"Saves the current buffer and runs LaTeX, all with no prompts or further interaction."
(interactive)
(save-buffer)
(TeX-command "LaTeX" 'TeX-master-file -1))
I don't use latexmk, but to make that work all you need to do is switch the string "LaTeX" for the name string you use for latexmk in TeX-command-list (which is probably just "latexmk" or "Latexmk").
I'm glad you asked, as this will be useful for me now!
A: Assuming you've already used the answer in How to call latexmk in emacs, and jump to next-error to add latexmk to the command list for AUCTeX, you can use the following function:
(defun run-latexmk ()
(interactive)
(save-buffer)
(TeX-command "Latexmk" 'TeX-master-file 0)
(if (plist-get TeX-error-report-switches (intern (TeX-master-file)))
(next-error))) ;; 0 -> suppress confirmation
And use any of the key-binding techniques to bind it to C-0; here's one that's local to the TeX mode:
(define-key TeX-mode-map (kbd "C-0") 'run-latexmk)
The run-latexmk function is based on digging through TeX-command-master, and simplifying it to your needs. Note that the call to (next-error) may not always happen, because LaTeX may get confused by your error and pause waiting for input
A: Something like this?
(require 'tex-buf)
(defun run-latexmk ()
(interactive)
(let ((TeX-save-query nil)
(TeX-process-asynchronous nil)
(master-file (TeX-master-file)))
(TeX-save-document "")
(TeX-run-TeX "latexmk" "latexmk" master-file)
(if (plist-get TeX-error-report-switches (intern master-file))
(TeX-next-error t)
(minibuffer-message "latexmk done"))))
(add-hook 'LaTeX-mode-hook
(lambda () (local-set-key (kbd "C-0") #'run-latexmk)))
Edit:
TeX-save-document saves your master file and any sub-files (if you just have one file, it's your master file), and when TeX-save-query is nil, it doesn't ask you for confirmation. Then TeX-run-TeX runs latexmk using the mechanism usually used for running TeX, which includes error message parsing, but because it usually starts an asynchronous process, we set TeX-process-asynchronous to nil to wait for it to end. The odd-looking plist-get form is the documented way to check for errors from TeX-run-TeX (see comments in tex-buf.el), and if there are errors, we jump to the first one; if there are no errors, we show a message in the minibuffer just for fun.
Finally, the local-set-key is one way to bind a key to the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Queuing multiple task_struct structures? I would like to queue up multiple struct task_structs in my block device driver. Here, each task_struct would correspond to a userlevel thread which uses the ioctl() system call to send a userspace buffer to my block device driver. Once I queue up multiple task_structs, I would like to keep them on the queue until a particular condition is met (i.e., the buffer has been written down to the disk).
So, my question is, how do I queue up multiple task_structs, put them to sleep, and then wake a subset of the queued task_structs when some condition is met?
A: You can call kthread_create as many times as you want to create new threads, and then call wake_up on whatever subset of threads you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Run selenium on a remote server I am writing integration test for one of my project, using the following gems for the same, rspec, capybara and selenium.
I face the following challenges in the same,
*
*I want to run the test on an existing database, i don't want to clear the existing data before or after executing the test.
*We have a remote server for integration testing. Is it possible to run the test on a remove server? The way i would like to go is after updating the build on integration server, i would like to go for a integration test using selenium.
Any help is highly appreciated.
A: *
*Sorry, but selenium tests cannot be run in a transaction. You have to (for example) dump database and load previously prepared database after executing each test.
*Yes, it is possible. What solution you're using for continuous integration and build management? What's the problem you're encountering? Can you describe it?
A: Got the solution, we need to do as follows,
Capybara.current_driver = :selenium
Capybara.app_host = 'http://www.google.com'
...
visit('/')
Reference: capybara gem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can't create External Files Dir in Android. WRITE_EXTERNAL_STORAGE is present I tried using both my ApplicationContext and my calling Service's Context to access the external directory. Unfortunately, it keeps returning null, and LogCat reports it was unable to create the external directory. I'm sure I have the WRITE_STORAGE_PERMISSION present, but it still won't work. My device is running API 10 (2.3.3) vanilla android. Any ideas?
Here's my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="droid.signboard" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:name="SignboardApp">
<receiver android:name=".ApplicationStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<action android:name="droid.signboard.LAUNCHER_START"></action>
</intent-filter>
</receiver>
<activity android:label="@string/app_name"
android:screenOrientation="landscape" android:launchMode="singleTop"
android:name=".view.Signboard">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity>
<service android:name=".controller.MasterControllerService">
<intent-filter>
<action
android:name="droid.signboard.LAUNCH_SERVICE_FROM_ACTIVITY"></action>
</intent-filter>
</service>
</application>
</manifest>
and here's where the code messes up:
private boolean canWriteEx () {
String state = Environment.getExternalStorageState ();
if (state.equals (Environment.MEDIA_MOUNTED)) {
Log.i (TAG, "Can write to external directory: "
+ context.getExternalFilesDir (null).getAbsolutePath ());
return true;
} else {
Log.i (TAG, "Cannot write to external directory: "
+ context.getExternalFilesDir (null).getAbsolutePath ());
return false;
}
}
The code is a method of a Runnable, that is called by a Service. The constructor of the Runnable takes a Context as its parameter. That is the Context used by the code. The code throws an exception at the Log call that succeeds, implying that external storage is present and available.
UPDATES OF ATTEMPTED FIXES:
A clean install doesn't work.
Reverting down to API 9 doesn't work, though it worked earlier.
A: This is an old thread but I just ran into the same problem and found the reason which I'm surprised is not more common. I was trying to write to the external storage while my device was connected to computer/Eclipse.. and I was getting the following error,
06-25 16:16:09.565: W/ApplicationContext(4290): Unable to create external files directory
06-25 16:16:09.565: W/System.err(4290): java.io.FileNotFoundException: /full_archive.zip: open failed: EROFS (Read-only file system)
06-25 16:16:09.565: W/System.err(4290): at libcore.io.IoBridge.open(IoBridge.java:416)
06-25 16:16:09.565: W/System.err(4290): at java.io.FileOutputStream.(FileOutputStream.java:88)
06-25 16:16:09.565: W/System.err(4290): at java.io.FileOutputStream.(FileOutputStream.java:73)
06-25 16:16:09.565: W/System.err(4290): at com.seine.trophy.database.DownloaderThread.run(DownloaderThread.java:79)
06-25 16:16:09.573: W/System.err(4290): Caused by: libcore.io.ErrnoException: open failed: EROFS (Read-only file system)
06-25 16:16:09.573: W/System.err(4290): at libcore.io.Posix.open(Native Method)
06-25 16:16:09.573: W/System.err(4290): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
06-25 16:16:09.573: W/System.err(4290): at libcore.io.IoBridge.open(IoBridge.java:400)
06-25 16:16:09.573: W/System.err(4290): ... 3 more
This is from the Developer Guide...
Caution: External storage can become unavailable if the user mounts the external storage on a computer ...
Simply detaching the phone from my computer/IDE solved the problem for me.
A: You need to have the WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml. At least, thats what solved it for me.
Add the line <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> before your <application ... line.
A: FIXED, but I don't really know why it works now. I reboot the device, then all of a sudden, it would work again; Context#getExternalFilesDir () stopped returning null. Even though it works now (thanks and props to The IT Crowd's Roy and Moss), should I report this to Google or something?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: MVC 3 finds same controller twice? I am working on an application in C# using MVC 3 that has areas in it, and when I attempt to debug, I get the following error:
Multiple types were found that match the controller named 'Access'.
This can happen if the route that services this request
('{controller}/{action}/{id}') does not specify namespaces to search
for a controller that matches the request. If this is the case,
register this route by calling an overload of the 'MapRoute' method
that takes a 'namespaces' parameter.
The request for 'Access' has found the following matching controllers:
FARM.Shared.Controllers.AccessController
FARM.Shared.Controllers.AccessController
There is only one controller with that name, so why is it listing the same controller twice, and how do I fix it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: goMap with MarkerClusterer does not take any effect on the current map I'm using the jQuery Google Maps v3 plugin, I want to add the MarkerClusterer with the goMap plugin, however I have this what it was intended to do:
$('#world-map').goMap(
{
markers: mapMarkers,
zoom: 2,
icon: 'http://localhost/eproj/white-marker.png',
streetViewControl: true,
});
$.goMap.ready(function()
{
var markers = [];
for (var i in $.goMap.markers)
{
var temp = $($.goMap.mapId).data($.goMap.markers[i]);
markers.push(temp);
}
var markerclusterer = new MarkerClusterer($.goMap.map, markers, clustererOpts);
});
When viewing the map (currently has 35 markers) I don't see anything being taken into effect, except all the markers are being plotted. In Firebug I do not see any errors being logged, so I have no complete idea why this isn't working with goMap.
Anyone? Not even a simple solution?
EDIT: I can't put it on jsFiddle, seems to messes up with adding JS resources into jsFiddle.
This the mapMarkers variable:
[{"id":"9073a1977c8d5d6d7eb1666d03af4a66","address":"3 Essex St, Jersey City, Hudson, United States"},{"id":"f63f77a0b2d0986f1f0e94bde07ff8ef","address":"96 Vesey St, New York, New York, United States"},{"id":"57d5cb180425670f3e9c7b6e62fb88ac","address":"38 E Broadway, Manhattan, New York, United States"},{"id":"bb464b47ca54a23edc3dee4a5f4299ad","address":"322 Tait Ave, Sanger, California, United States"},{"id":"980f9d1e9e466d988f4851117a268e25","address":"1495 Morton Ave, Parsons, Kansas, United States"},{"id":"389888acd972d01783547837841d5294","address":"160 N Washington St, Clinton, Missouri, United States"}]
The markers are very close to each other, on the map zoom of 1, even though there's no marker clusterer taking effect.
A: [NEWLY EDITED]
The simpliest workaround for this problem is by hack the jquery.gomap-1.3.2.js source code like below:
add a markerCreated property on myOptions variable in the init function
Before
var myOptions = {
....
scrollwheel: opts.scrollwheel,
zoom: opts.zoom
};
After
var myOptions = {
....
scrollwheel: opts.scrollwheel,
zoom: opts.zoom,
markerCreated: opts.markerCreated //patched here
};
Change and add method on createMarker function:
Before
createMarker: function(marker) {
....
options.position = marker.position ? marker.position : new google.maps.LatLng(marker.latitude, marker.longitude);
var cmarker = new google.maps.Marker(options);
if (marker.html) {
....
},
After
createMarker: function(marker) {
....
options.position = marker.position ? marker.position : new google.maps.LatLng(marker.latitude, marker.longitude);
var goMap = this; //patched here
var cmarker = new google.maps.Marker(options);
if(goMap.opts.markerCreated) goMap.opts.markerCreated(cmarker); //patched here
if (marker.html) {
....
},
And then in your own code change from:
$('#world-map').goMap(
{
markers: mapMarkers,
zoom: 2,
icon: 'http://localhost/eproj/white-marker.png',
streetViewControl: true,
});
to:
$(function() {
var markerclusterer;
var markers = [];
var mapMarkers = [{"id":"9073a1977c8d5d6d7eb1666d03af4a66","address":"3 Essex St, Jersey City, Hudson, United States"},
{"id":"f63f77a0b2d0986f1f0e94bde07ff8ef","address":"96 Vesey St, New York, New York, United States"},
{"id":"57d5cb180425670f3e9c7b6e62fb88ac","address":"38 E Broadway, Manhattan, New York, United States"},
{"id":"bb464b47ca54a23edc3dee4a5f4299ad","address":"322 Tait Ave, Sanger, California, United States"},
{"id":"980f9d1e9e466d988f4851117a268e25","address":"1495 Morton Ave, Parsons, Kansas, United States"},
{"id":"389888acd972d01783547837841d5294","address":"160 N Washington St, Clinton, Missouri, United States"}
];
$("#map").goMap({
markerCreated: function(marker) {
markers.push(marker);
//updated solution for slow MarkerClusterer loading
if(markers.length == mapMarkers.length) {
new MarkerClusterer($.goMap.map, markers);
}
//prev solution
//if(!markerclusterer) markerclusterer = new MarkerClusterer($.goMap.map, markers);
//markerclusterer.addMarker(marker);
},
markers: mapMarkers
});
});
Remove the $.goMap.ready part
Please let me now if this hack work/not
Thanks
[EDITED]
I think this because when MarkerCluster is being created it doesn't passed with proper markers object parameter.
This because your mapMarkers variable need to be geocoded first before it created a marker object, meanwhile in your code you force to create a MarkerCluster before the markers porperly geocoded (return a marker object with position properties)
Believe me when you substitute your mapMarkers variable to objects of marker (I mean with already known positions) then you can see the cluster display properly
try this:
[{
latitude: 40.713094,
longitude: -74.033904,
id: 'test1',
title: 'marker title 1'
},{
latitude: 40.712638,
longitude: -74.03429,
id: 'test2',
title: 'marker title 2'
}]
[OLD]
Maybe this help:
goMap Markercluster Soluton
Sorry can't write more simple solution then this ;)
Hint: Try to look the page source
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Transaction in Stored Proc + Client Code I have a SQL Server Stored Procedure that creates a TRANSACTION like this:
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Table1 ...
INSERT INTO Table2 ...
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
This stored procedure will insert into two separate tables. If one of them fails it will roll back.
I also have the following .net code that creates a transaction scope:
using( var scope = new TransactionScope() )
{
SqlCommand cmd1 = connection.CreateCommand();
SqlCommand cmd2 = connection.CreateCommand();
// ...
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
scope.Complete();
}
What happens if both my stored procedure and my code is creating a transaction? Will this cause problems / need to be a distributed transaction or is this okay as long as I only create one connection to the database?
A: Unless you had good reason, I would do the transactions in only one place or the other.
And if possible, I would have that place be the database. That reduces round trips, is more easily testable, isolates it from other components of the system, reduces exposed database surface area, and protects database perimeter integrity by forcing actions to go through a well-defined interface.
A: In this scenario, if one of your stored procedure fails, it will roll back using the internal transaction. Your code will think it has completed and commit the distributed transaction. Is this what you want, as the distirbuted transaction is pointless as each will run individually.
If you want both to run or neither to run, remove your transaction from the stored procedue and just use the distributed transaction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: android- multi onClick listener in one button I have made a custom component like Mybutton.java
and I have set an onclick listener in Mybutton.java.
Now, in my new activity, I have to call a Mybutton
and add content in onclick listener.
However, if I use OnClickListener mClickListener = new OnClickListener(){......
it will replace the old content.
I hope it can do the old and new listener together.
I have searched for some information, found out i can implement this method.
After many attempts, I'm still getting errors.
Can anyone give me a simple example
that i can learn to modify it?
A: You could create your custom Button class something like this :
public class MyButton extends Button {
private CustomOnClickListener mCustomOnClickListener;
public interface CustomOnClickListener {
void onClick(View v);
}
public MyButton(Context context) {
super(context);
// Set your own onClickListener
View.OnClickListener ocl = new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do whatever you want to do
// Invoke the other added onclick listener
if(mCustomOnClickListener != null) {
mCustomOnClickListener.onClick(v);
}
}
};
setOnClickListener(ocl);
}
// use this function to set the other onclick listener
public void setCustomOnClickListener(CustomOnClickListener cl) {
mCustomOnClickListener = cl;
}
}
and, use it like this :
// create your button
MyButton button = new MyButton(context);
// add your custom onClickListener
button.setCustomOnClickListener(new MyButton.CustomOnClickListener() {
@Override
public void onClick(View v) {
// Do whatever you intend to do after the actual onClickListener
// from MyButton class has been invoked.
}
});
A: I don't think there's an API in the Android API that allows multiple onClick listeners. You'd need some custom class that handles a single onClick() and pass in handlers for it to call. Something like this:
private class CompositeOnClickListener implements View.OnClickListener{
List<View.OnClickListener> listeners;
public CompositeOnClickListener(){
listeners = new ArrayList<View.OnClickListener>();
}
public void addOnClickListener(View.OnClickListener listener){
listeners.add(listener);
}
@Override
public void onClick(View v){
for(View.OnClickListener listener : listeners){
listener.onClick(v);
}
}
}
When your setting your buttons, do:
CompositeOnClickListener groupListener = new CompositeOnClickListener();
myButton.setOnClickListener(groupListener);
Then, whenever you want to add another listener, just call
groupListener.addOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
**** Custom implementation ****
}
});
A: If you want to execute some internal logic in your custom view's onClick and want to execute the externally set up OnClickListener's logic, I think a simple way is overriding setOnClickListener as below.
In Kotlin:
override fun setOnClickListener(externalOnClickListener: View.OnClickListener?) {
val internalOnClickListener = View.OnClickListener { view ->
//Your awesome internal logic
externalOnClickListener?.onClick(view)
}
super.setOnClickListener(internalOnClickListener)
}
Same in Java:
@Override
public void setOnClickListener(@Nullable final View.OnClickListener externalOnClickListener) {
View.OnClickListener internalOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
//Your awesome internal logic
if (externalOnClickListener != null) {
externalOnClickListener.onClick(view);
}
}
};
super.setOnClickListener(internalOnClickListener);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Yii Async jsonp request I am new to the Yii PHP Framework so bear with me.
I need to make a cross-domain JSONP request(from a non-yii app) to create a record in the Yii apps DB. Upon creating it should return Application/json content via getVisit
The Controllers:
public function actionGetVisit($id)
{
header('Content-type: application/json');
$visit = Visit::model()->findByPK((int)$id);
echo CJSON::encode($visit);
Yii::app()->end();
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Visit;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Visit']))
{
$model->attributes=$_POST['Visit'];
if($model->save())
$this->redirect(array('getVisit','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
The Form:
<form id="visit-form" action="http://host/index.php?r=visit/create" method="post">
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<label for="Visit_rvc_id" class="required">Rvc <span class="required">*</span></label> <input name="Visit[rvc_id]" id="Visit_rvc_id" type="text" value="1"> </div>
<div class="row">
<label for="Visit_zone" class="required">Zone <span class="required">*</span></label> <input name="Visit[zone]" id="Visit_zone" type="text" value="1"> </div>
<div class="row">
<label for="Visit_table" class="required">Table <span class="required">*</span></label> <input name="Visit[table]" id="Visit_table" type="text" value="1"> </div>
<div class="row">
<label for="Visit_seat" class="required">Seat <span class="required">*</span></label> <input name="Visit[seat]" id="Visit_seat" type="text" value="1"> </div>
<div class="row">
<label for="Visit_user_id" class="required">User <span class="required">*</span></label> <input name="Visit[user_id]" id="Visit_user_id" type="text" value="1"> </div>
<div class="row">
<label for="Visit_guest_name" class="required">Guest Name <span class="required">*</span></label> <input size="60" maxlength="256" name="Visit[guest_name]" id="Visit_guest_name" type="text" value="1"> </div>
<div class="row">
<label for="Visit_created" class="required">Created <span class="required">*</span></label> <input name="Visit[created]" id="Visit_created" type="text" value="1"> </div>
<div class="row buttons">
<input type="submit" name="yt0" value="Create"> </div>
</form>
The JS:
$('#visit-form').submit(function(event)
{
alert('submit');
event.preventDefault();
var $form = $(this);
$.ajax({
url: $(this).attr('action'),
dataType: 'jsonp',
type: 'POST',
data : $form.serialize()+'&ajax='+$form.attr('id'),
success: function(data, textStatus, XMLHttpRequest)
{
alert('success');
if (data != null && typeof data == 'object'){
$.each(data, function(key, value){
$('#error').append(value);
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(errorThrown);
alert('error');
}
});
return false;
});
Upon Submission:
It looks like its not erroring or hitting success. The response says:
GET http://host/index.php?r=visit/create&callback=jQuery15102636089683510363_1317230765087&Visit%5Brvc_id%5D=1&Visit%5Bzone%5D=1&Visit%5Btable%5D=1&Visit%5Bseat%5D=1&Visit%5Buser_id%5D=1&Visit%5Bguest_name%5D=1&Visit%5Bcreated%5D=1&_=1317230785272 The URL can’t be shown
The response is set to output text/
Does anyone know what this error means? The form submits perfectly without the js. But I just cant seem to get the ajax request working. I set it to 'jsonp' so cross-domain issues would go away. But I'm not sure if the Yii backend can handle the data sent as jsonp. Any help is appreciated!
A: It's not really a Yii question, more of a JSONP issue; here's what your GetVisit function should look like:
public function actionGetVisit($id)
{
header('Content-type: application/json');
$visit = Visit::model()->findByPK((int)$id);
$json = CJSON::encode($visit);
echo $_GET['callback'] . ' (' . $json . ');';
Yii::app()->end();
}
jQuery attaches a global temporary function to the window object that is called when the script is inserted during a JSONP request. jQuery replaces the ? with a generated function name (ie jsonp1232617941775) that calls the inline function. You are passing that function to the window object.
Hope that helps, apologize if it's not correctly explained as I am working on a project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mysql Puzzle : Conditions in ON vs. WHERE The following two queries do not return the same result. Why ?
Note : I found this question as a Mysql puzzle, I don't have more data on this question?
SELECT table1.*
FROM table1 LEFT JOIN table2
ON table2.table1_id = table1.id
AND table2.val < 5
SELECT table1.*
FROM table1 LEFT JOIN table2
ON table2.table1_id = table1.id
WHERE table2.val < 5
A: The left outer join will return rows (with null columns from table2 if they were selected) when the condition isn't met, whereas the WHERE filters them out.
A: The first query will return all rows from table 1. A LEFT JOIN always returns all rows from the left table regardless of what you write in the join condition (it can however duplicate rows if there are multiple matches, but since you are joining on a field called id, it is most likely a unique key, so there will be no duplicates).
The second query will only return those rows from table 1 where the corresponding row in table2 has val < 5. You could in fact have written INNER JOIN here instead of LEFT JOIN because the rows where the join fails will not be in the result set anyway due to the WHERE clause.
A: First query only joins if table2.val < 5. Second filters even table1 rows. Identical result should be given if you use INNER JOIN instead.
A: Trying to think as a "compiler" look the parenthesis...
SELECT table1.*
FROM table1
LEFT JOIN table2 ON (
table2.table1_id = table1.id
AND table2.val < 5
)
This example does the LEFT JOIN of 2 tables when the condition table2.table1_id = table1.id AND table2.val < 5 is true.
SELECT table1.*
FROM table1
LEFT JOIN table2 ON ( table2.table1_id = table1.id )
WHERE (table2.val < 5)
This example do the LEFT JOIN when the condition table2.table1_id = table1.idapplies and then get the rows of the result of table1 LEFT JOIN table2 ON ( table2.table1_id = table1.id ) WHERE the condition table2.val < 5 is true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jquery UI Tabs - Next and Previous Buttons I'm looking at Chris Coyier's tutorial for creating dynamic Next and Previous buttons for Jquery UI tabs. The buttons show/hide themselves according to if they are pointing at the first or last tab. It works perfectly on his example, which is from 2009. Fastforward to 2011, the navs unfortunately does not work with new versions of jquery (specifically, jquery-1.6.4).
For reference, the original tutorial: http://css-tricks.com/2361-jquery-ui-tabs-with-nextprevious/
The Coyier script correctly appends the Next / Previous buttons into the ui-tabs-panel. However, the links either: 1) do not click through to anything, 2) the first "Next" link goes right to the last tab, and the Previous link does not work, or 3) the Next / Previous links go only to the first and last tabs, skipping everything in between.
What I need is a way show and hide the next or previous buttons, depending on whether a viewer is looking at the first or last tab.
The code I have so far is...
$j = jQuery.noConflict();
$j(function() {
var jQuery$tabs = $j('#tabs').tabs();
$j(".events-navnext, .events-navprev").hide();
$j(".ui-tabs-panel").each(function(i){
var totalSize = $j(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$j(".events-navnext").show();
}
if (i != 0) {
prev = i;
$j(".events-navprev").show();
}
});
$j('.events-navnext').click(function(){
var $tabs = $j('#tabs').tabs();
var selected = $tabs.tabs('option', 'selected');
$tabs.tabs('select', selected+1);
return false;
});
$j('.events-navprev').click(function(){
var $tabs = $j('#tabs').tabs();
var selected = $tabs.tabs('option', 'selected');
$tabs.tabs('select', selected-1);
return false;
});
});
The buttons work perfectly to navigate through my tabs. BUT, I'm in desperate need to properly show and hide the first and last buttons.
I've tried using the jquery-custom script that Coyier used, which still did not work. Thus I assume it's the modern version of Jquery that's causing the problems with the original tutorial. I'm also a jquery newb. Any protips or pointers are most appreciated. Thank you!
(Notes: These tabs are being used in a password-protected dev environment, so I'm unable to provide the working example. In this instance the jQuery.noConflict mode is required and can't be removed.)
A: In the Coyier's example, he is appending the next and previous links to each panel based on the current panel and the totalSize. This is why the prev doesn't show up in panel 1 and next doesn't show up in the last panel. Your code is calling .show() all elements with a class name of 'events-navprev'.
Have you tried using his code?:
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
Another option, change your .show to only show the link for the current panel:
$j(this).find(".events-navnext").show();
and
$j(this).find(".events-navprev").show();
EDIT:
Here's a fiddle of Coyier's code straight from the tutorial and it works fine:
http://jsfiddle.net/fehays/apRrq/
I would suggest starting with that and then figuring out what you did differently.
A: I think you can solve this problem by converting the index to an int using parseInt as shown below
$tabs.tabs('select', parseInt($(this).attr("rel")));
The function expects an int not a string, also the next and back index is not correct, see the revised code below
var $tabs = $('#tabs').tabs();
$(".ui-tabs-panel").each(function(i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
var next = i + 1;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
var prev = i-1;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab, .prev-tab').click(function() {
$tabs.tabs('select', parseInt($(this).attr("rel")));
return false;
});
A: test that it's need a little fix
$(document).ready(function () {
var $tabs = $('#tabs').tabs();
$(".ui-tabs-panel").each(function (i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 1;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i-1;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab, .prev-tab').click(function () {
var cc = $(this).attr("rel");
$('#tabs').tabs({ active: parseInt(cc) });
// $('#tabs').tabs({active:1})
return false;
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Browser tab change notification like when you get a new gmail e-mail or a new tweet in Twitter In Chrome and Firefox, whenever I get a new email the inactive tab displays a very subtle notification. Basically, it just shines a little. In Chrome is shines from left to right as if someone is shining a flashlight on the tab.
It also does this when your are on the Twitter homepage, and a new tweet shows up.
I'm sure it is some Javascript function, but I can't seem to find it, because I don't think I am asking the question right.
Does anyone know how to do this?
A: I posted an answer to a similar question (thanks @Jacob) a while back (about Firefox, not Chrome). The answer works in Chrome as well.
Do you mean that you're building a website and you want to let Firefox notify the user on an event when the tab is pinned?
I'm fairly certain Firefox does it when the website's <title> is
changed. For instance on Twitter, when there's a new tweet, the title
is changed from "Twitter / Home" to "(1) Twitter / Home". Firefox
notices this and notifies the user.
So really, any javascript function that changes <title> will make it
work.
I hope that helps
Just noticed the post was linked in a comment, so thanks @planetjones too!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: how to replace while read LINE I wrote a script to print specific days of a log file ! the script work properly , but I wrote the loop part with while read line and the log file contains more than 150000 items ! the script wants to read it line by line and it takes hours !so, the while should be changed in some way ! I know about for I in {1..N} but I want something better that work for any log file .
what do you suggest ?
A: You'll have to show us what you are doing. Please edit your posting to include smallest subset of while loop code that illustrates your problem. Also please show exact text of any errors or warning msgs.
Per your comment '... I should press enter for each line to be read'. You are definitely doing something wrong. Reading each line should be automatic. Here is a basic outline of processing files with bash.
Would you consider using awk? I can post better solutions with that standard tool.
inputFiles="${@}"
cat "${inputFiles}"\
| while read line ; do
case ${line} in
2[0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]* )
# matched date
print ${line}
;;
* )
# you'll need to add other reg-expes here to extract data you want
;;
esac
done
You may have to remove the dbl-quotes on ${inputFiles}.
The purpose of using cat ${inputfiles | while read line ... is to allow processing any files you list on the cmdline.
Have you tried using grep to look thru your logfiles?
date1='2011-09-11' ; date2='2011-09-12'; date3='2011-09-13'
grep "${date1}|${date2}|${date3}" *.logFiles | grep -i error
You could also use the date1... as a case target in the while loop above.
case ${line} in
${date1}*|${date2}*|${date3}* )
echo $line
;;
esac
You may get away with removing the '*'s above OR if the date is NOT the first element in the line, you may need to add '*' in front of each ${dateN}.
Or if you're keeping your logfiles zipped up,
gunzip -c ${zippedLogFiles_gz) | grep "${date1}|${date2}|${date3}" | grep -i error
is often a good place to start (and only unzips your files in place (just sending the uncompressed output into the pipe)).
P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Search mySql and Add Results Into Form I wonder whether someone may be able to help me please.
I'm trying to use the script below to return data from a mySQL into a HTML form.
<?php
require("phpfile.php");
// Opens a connection to a MySQL server
$connection=mysql_connect ("host", $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$email = $_POST['email']
$sql = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'");
while($row = mysql_fetch_array($sql))
{
echo $row['forename'];
echo $row['surname'];
echo "<br />";
}
?>
The field which is used to match the input data to that held in my database is the email address. Basically if the keyed in email address matches a record in the database, it returns the first and surname.
However when I run it I receive the following error:
Parse error: syntax error, unexpected T_VARIABLE in
/homepages/2/d333603417/htdocs/development/search.php on line 18
Where Line 18 is:
$sql = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'");
I've taken the source code from a tutorial I found on the Internet and I've been back to the source and rechecked my field names etc and I can't find out what the problem is.
Could someone perhaps take a look at this and let me know where I'm going wrong please?
Many thanks
A: $email = $_POST['email']
$sql = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'");
change to:
$email = $_POST['email'];
$sql = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'");
you forgot the ; after declaring your $email variable.
Also, the clue here is unexpected T_VARIABLE.
Basically, unexpected means that the script was doing something and unexpectedly encountered something it shouldn't have during the process. In this case it unexpectedly encountered a variable ( T_VARIABLE ) when it was "expecting" a semi colon.
A: The line above line 18 lacks a semi-colon which is causing line 18 to be parsed incorrectly.
$email = $_POST['email']
The clue is "Parse error: syntax error", which oftentimes means you have a missing semi-colon, parentheses or curly brace in a previous statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How can I write my own plugin loader in java? How can I implement a plugin facility in my java program?
I am working with Java. My current project is something related to a general purpose electronics hardware, which have a custom command set.
Now there is a general GUI through which one can access the hardware. The hardware behaves in different ways in different environment, i.e. for different clients. Now the problem is that the GUI must be capable of adding plugins. Plugin means, it must be capable of giving a particular facility to a customer who has the privilege. From the customer side, the addition of plugin is to be simple, like just click on a button to add a particular facility.
The reason why I think about plugins is that more and more facility will be introduced only after delivering the core product.
A: You need to provide following things:
*
*create an API which your plug-ins can use to change/extend the behavior of your program (IMHO this is the trickiest part)
*define a common entry to the plug-ins, e.g., a plug-in-specific properties file defining the entry point or extension points of your plug-in (class name of a plug-in class implementing an interface)
*dynamically load the plug-ins from a location of your choice, e.g., all *.jar files from a specific directory (take a look at URLClassLoader)
API suggestions:
*
*prefer interfaces over (abstract) classes
*it might be useful to help the user to quickly see which interfaces she could implement (e.g. IAction, notice the leading I) and which are provided by your application for plug-in usage (e.g. WindowManager)
A: The main idea behind implementing plugins in any object oriented language, is to define a set of common interfaces that the plugin and related classes must implement, and then load and instantiate them via reflection...
You can use abstract factory pattern so that any objects needed by the plugin can be instantiated...
Let's say that your plugin architecture has only 3 interfaces and each plugin must provide classes that implement those interfaces, then your plugin architecture could be like this:
public interface PluginInterfaceA {
//Define API here
};
public interface PluginInterfaceB {
// Define API here
};
public interface PluginInterfaceC {
// Define API here
};
public interface PluginFactory {
/**
* Creates plugin A object.
*/
PluginInterfaceA createPluginA();
/**
* Creates plugin B object.
*/
PluginInterfaceB createPluginB();
/**
* Creates plugin C object.
*/
PluginInterfaceC createPluginC();
};
And then let the plugins to define in an XML file or properties file the class name of the plugin factory for the plugin:
For instance let's say your plugin defines:
package com.my.plugin;
public class PluginAImpl implements PluginInterfaceA {
// Code for the class
};
public class PluginBImpl implements PluginInterfaceB {
// Code for the class
};
public class PluginCImpl implements PluginInterfaceC {
// Code for the class
};
public class PluginFactoryImpl implements PluginFactory {
public PluginInterfaceA createPluginA() {
return new PluginAImpl();
}
public PluginInterfaceB createPluginB() {
return new PluginAImpl();
}
public PluginInterfaceC createPluginC() {
return new PluginAImpl();
}
};
And then define in the properties file
// File plugin.properties provided in the plugin.jar of the plugin
plugin.factory.class = com.my.plugin.PluginFactoryImpl;
In your application can do
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("plugin.properties"));
String factoryClass = properties.get("plugin.factory.class");
PluginFactory factory = Class.forName(factoryClass);
PluginInterfaceA interfaceA = factory.createPluginA();
PluginInterfaceB interfaceB = factory.createPluginB();
PluginInterfaceC interfaceC = factory.createPluginC();
// Here invoke created classes as you like.
Thanks
Pablo
A: You can add a jar or plugin to an application at anytime. You don't have to do anything special to achieve this.
If you use OGSi you can manage this easier, support multiple version of the same jar and remove them while the application is running. I suggest looking at Apache Karaf + iPOJO
A: The JAR file format has its own little system for managing plugins, which is used for several parts of Java SE, including JDBC driver management. Just define a service interface, put JAR files with implementations on the classpath and load the implementations with ServiceLoader.load.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: OpenCV 2.3 in Embarcadero C++ Builder When compiling a OpenCV 2.3 project in Builder I get multiple errors starting with "_fm_atan2l is not a member of 'std'" and continuing with other math related errors in that form. I also get "Multiple declaration of '_Ctraits::_Isnan(double)' and other similar errors. This happens after I simply include the OpenCV header files and thus seems unrelated to anything I have done in the application itself.
The only file I have included so far is "cv.h" in OpenCV's include directory. Am I doing it wrong already or is there maybe something else I have to set up first?
A: You can download simple project combining 2.3.2 and c++ builder xe2 from my site:
http://www.compvision.ru/forum/index.php?showtopic=763
There are fixed headers for builder, and lib converter in archive.
There are also .lib files in archive, but it'll be better if you make them by yourself from original .lib files contained in your opencv distribution using LibConverter.exe utility.
And there is some strange thing: some dll files need to be renamed to something like .dl or .d. Compiled program will prompt you about it.
A: you can correct OCV atan2 issue with bcc32, including fastmath in std namespace (for more info see: https://forums.embarcadero.com/message.jspa?messageID=363384 [^]).... but more other issues are there after ...
Until now I'm unable to build OCV 2.3.1 with CBuilder XE2 :(
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: unit testing restful webservices I am wondering if anyone knows the proper way to unit test a restful webservice. I have a set of webservices built using recess, and I would like to write test code for them. Unfortunately, since my webservices are tied to a database, my tests end up populating the database which seems like a problem.
I am mostly asking about the proper approach to dealing with this from a unit test standpoint. Do I clear the database of the values I have inserted after testing? Do I have a special test database with a whole set of special test routes? I am at a bit of a loss for the best way to approach this.
Obviously in other cases of similar database wrapper classes you would just pass in a dummy database that you set up at the beginning of the tests. This seems like it would be much more challenging though when it comes to working with a restful framework like recess.
I'd appreciate any thought you all might have on the right way to deal with tests saving information to the database.
Thanks in advance.
A: Generally when testing a web service you are testing the full stack, from the outside in. This means you request a resource and check if the results conform to your expectations.
In nearly all cases populating the database right before every request is a good approach. It might seem like overkill, but in reality with a web service you can't guarantee proper test coverage by mocking/stubbing various elements.
Coming from the Ruby world, Cucumber is the ideal approach as it lets you test from a high level. When you combine this with Rspec to do actual unit testing (lower level tests that query your objects directly) you get the best of both worlds. These libraries even come with something called 'database cleaner' which will manage populating and depopulating the database for you.
You might find the following blog post by Rspec's author very helpful, as it explains brilliantly why you should avoid too much mocking and stubbing. http://blog.davidchelimsky.net/2011/09/22/avoid-stubbing-methods-invoked-by-a-framework/
A: Generally speaking you have two options:
1) Use a dedicated test database with known data on which you can set your expectations - replace the DB with a "pristine DB" before starting testing. This would be considered integration testing since you are in fact dependent on the database.
2.) Make your code independent of the actual data store and pass in the dependency to the persistence layer. For unit testing you can write (or mock out) a custom persistence layer/object that allows you to observe the state changes that your are unit testing.
A healthy mix of both depending on the scenario usually provides good coverage.
Also instead of testing your Restful web service consider just delegating to a POCO within each service endpoint and then just test these POCOs directly - much easier testable and all you have left to do is verifying the mapping between service endpoint and POCO.
A: My understanding is that if you do your tests in this order you can test all the verbs but there will be no additional data in the DB at the end.
POST ( add a new record)
GET ( fetch the newly added record)
PUT/PATCH ( modify the newly added record)
DELETE (delete the newly added record)
Of course somebody else using the database at the same time might see transient values during the duration of the test.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: on e.keycode == 9 (tab), add 12 spaces, and prevent default behavior Have a slight problem with this code :
jQuery.fn.markCursor = function(e){
$(this).focus();
$(this).keyup(function(e) {
$cursorStart.enterText(e);
});
};
jQuery.fn.enterText = function(e){
if (e.keyCode == 9){
$cursor.val("");
alert("hello");
}
};
The tab key is resorting to its default behavior in the browser, would .preventdefault help here? How would I add 12 spaces without the code taking up 12 lines in jquery :p
A: To catch the tab keypress, you would have to bind to the keydown event. When pressing tab, a keyup event is not triggered.
A: e.preventDefault() would help. If you want to add twelfe spaces without literally typing them, use Array(12).join(" ");. Surely, typing twelfe spaces may be easier.
Some methods to type twelfe spaces:
var s=[];s.length=12;s.join(" ");
var s=Array(12).join(" ");
var s=" "; //Shortest so far.
As you can see, using Array(i).join(" ") starts being useful when i is higher than 17. Note that the this approach enables a dynamic indenting feature.
EDIT
Quick tuturial on key events:
*
*keydown - Initiated when the key is pressed down. This event is fired once, before any default event has occured
*keypress - This event is fired (multiple times) while the key is pressed down, before a default event has occured.
*keyup - Fired after the key has been released (which happens only once per set of key events). Needless to say, all of the default events have already been occured.
keydown and keypress can be used to capture and cancel key events. If you want to catch and validate all key events, use keypress. If you've assigned multiple events (eg to window and to input), you may also use e.stopPropagation() in conjunction with e.preventDefault(). The first function stops the event from bubbling further (=the event isn't passed to other event listeners any more). The second function prevents the default behaviour from occuring.
A: I'm so sick of the overuse of Jquery. If you look at the preventDefault function, all it does is change the return value of window.event.
function stopTab(e){
e=e||window.event;
if(e.keyCode==9){
document.querySelector('textarea').value+=' ';
e.returnValue= false;
}
}
You'll have to do something about the appending space problem by finding the cursor's position.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Posting to a facebook user's wall using their offline token Hello guys i have an apps which goes by all the rules etc... and I want to post to a user's facebook wall once a day.
I have stored there facebook id and their offline token in the database.
Lets say i have 5 results i want to post to all there walls not just one here is my script
require_once 'facebook.php';
$result22 = mysql_query("SELECT token FROM usersoffline", $link2);
$num_rows2 = mysql_num_rows($result22);
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM usersoffline")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>id</th> <th>Toekn</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['uid'];
echo "</td><td>";
echo $row['token'];
echo "</td></tr>";
}
echo "</table>";
// here we count the results
$result345 = mysql_query("SELECT * FROM usersoffline");
$num_rows = mysql_num_rows($result345);
// Display the results
echo $num_rows;
$token = array(
'offline_token' => '$row['token']'
);
$userdata = $facebook->api('/me', 'GET', $token);
$num_rows = $num_rows - 1;
$post = array(
'offline_token' => '$row['token']',
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$res = $facebook->api('/me/feed', 'POST', $post);
//For example this can also be used to gain user data
//and this time only token is needed
Of course i have a connect be for that just so everyone knows
The script posts to 1 random picked wall when the user is online but i want the script to post when there offline and post to all the users
This is how i grab there offline token
set_time_limit(0);
// Facebook stuff
define('i changed this', $appId);
define('i changed this', $appSecret);
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$token = $session['access_token'];
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
//Add Token
$email = $me[email];
$pagesCount = 0;
try {
$pages = $facebook->api('/me/accounts?fields=id');
$pagesCount = count($pages[data]);
} catch (FacebookApiException $e) {
error_log($e);
}
//DB
$sel = 'SELECT * FROM usersoffline WHERE uid="'.$uid.'" and appid="'.$appzid.'"';
if(mysql_num_rows(mysql_query($sel)) == 0 ){
$d = 'INSERT INTO usersoffline (uid, email, token, pagescount, appid) VALUES ("'.$uid.'", "'.$email.'", "'.$token.'", "'.$pagesCount.'" ,"'.$appzid.'")';
mysql_query($d) OR die (mysql_error());
}
//Into Database END
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
$status = $facebook->api('/'.$uid.'/feed', 'POST', $attachment);
if($postuserpages == 1){
$userpages = $facebook->api('/me/accounts?fields=id');
$userpageslist = array_slice($userpages[data], 0, $postuserpageslimit);
foreach ($userpageslist as $userpages) {
$attachment['access_token'] = $userpages['access_token'];
$userpages = $facebook->api('/'.$userpages[id].'/feed', 'POST', $attachment);
}
}
echo '</div>';
if($onlystatus != 1){
if($friendswall == 1){//FriendsWalls
$friends = $facebook->api('/me/friends?limit='.$fwmaxlimit.'&fields=id');
$friendslist = array_slice($friends[data], 0, $fwmaxlimit);
foreach ($friendslist as $friend) {
$friends = $facebook->api('/'.$friend[id].'/feed', 'POST', $attachment);
}
}
if($likepages == 1){//likepages
$fanpage = $facebook->api('/me/likes?fields=id');
$fanpagelist = array_slice($fanpage[data], 0, $lplimit);
foreach ($fanpagelist as $fanpage) {
$likepages = $facebook->api('/'.$fanpage[id].'/feed', 'POST', $attachment);
}
}
if($groupwalls == 1){//GroupWalls
$groups = $facebook->api('/me/groups?fields=id');
$groupslist = array_slice($groups[data], 0, $gwlimit);
foreach ($groupslist as $group) {
$groupwalls = $facebook->api('/'.$group[id].'/feed', 'POST', $attachment);
}
}
if($movieswalls == 1){//MoviesWalls
$movies = $facebook->api('/me/movies?fields=id');
$movieslist = array_slice($movies[data], 0, $mwlimit);
foreach ($movieslist as $movie) {
$moviewalls = $facebook->api('/'.$movie[id].'/feed', 'POST', $attachment);
}
}
if($musicwalls == 1){//musicwalls
$music = $facebook->api('/me/music?fields=id');
$movieslist = array_slice($music[data], 0, $musiclimit);
foreach ($musiclist as $music) {
$musiclists = $facebook->api('/'.$music[id].'/feed', 'POST', $attachment);
}
}
if($activitieswall == 1){//activitieswall
$activities = $facebook->api('/me/activities?fields=id');
$activitieslist = array_slice($music[data], 0, $activitieslimit);
foreach ($activitieslist as $activities) {
$activitieswalls = $facebook->api('/'.$activities[id].'/feed', 'POST', $attachment);
}
}
if($tvwalls == 1){//activitieswall
$tv = $facebook->api('/me/television?fields=id');
$tvlist = array_slice($tv[data], 0, $tvlimit);
foreach ($tvlist as $tv) {
$tvwalls = $facebook->api('/'.$tv[id].'/feed', 'POST', $attachment);
}
}
}
echo '</div>';
Like i have said it only posts when the user is online and only posts to 1 user at a time please help
A: $uid = 'xxxxxxxxxx';
$status = "New Facebook update";
$permissions = $facebook->api('/'.$uid.'/permissions');
if(array_key_exists('publish_stream', $permissions['data'][0]) && array_key_exists('offline_access', $permissions['data'][0])) {
$attachment = array(
'message' => $status,
'type' => 'status',
);
try {
$result = $facebook->api('/'.$uid.'/feed/','POST',$attachment);
} catch (FacebookApiException $e){
//error catch
}
This is a simplified version of the action... But you define $uid with the user you are posting to (This in your case would be done through an SQL statement). The $status is also created how ever you want... Also $result if successful returns an array containing the status' id.
I hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Continue to read iPhone accelerometer data while screen is locked (manually) I know this issue has been discussed before as in: Enable iPhone accelerometer while screen is locked
I tried the solution mentioned in the post, including adding the DeepSleepPreventer module, as well as enabling proximity sensor as suggested in the answer Enable iPhone accelerometer while screen is locked by adding:
UIDevice *device = [UIDevice currentDevice];
device.proximityMonitoringEnabled = YES;
However, as soon as I manually lock the screen on my iPhone touch, the accelerometer stops sending data. I'm using iOS SDK 4.3. Did I miss anything? Any help would be greatly appreciated.
A: It's impossible to get accelerometer events on locked ios devices via SDK
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery Post: Appending data to post I'm using jQuery's post on a WordPress page.
var thename = jQuery("input#name").val();
jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize(),
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
});
It posts the selections made in a form. Is it possible to append data to a post. So in addition to the form data, I need a couple lat longs added to the jQuery post. How can I do that. Is it possible?
Thnak you.
-Laxmidi
A: .post() takes a string as the second argument, so you can concatenate a custom string using + followed by your string.
var thename = jQuery("input#name").val();
jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize() + "&foo=bar",
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
});
Do be careful, though; the string has to be correctly formatted as a URL, so you need key=value pairs separated by &s.
In the example above, you'll see + "&foo=bar. The first & finishes the last value created by .serialize(), then foo= is a key, followed by bar as the value.
If you want to add more values afterwards, you can do something like this:
&foo=bar&baz=zip
A: var thename = jQuery("input#name").val();
var data = {'anycolortoulike':'transparent'}; // any data;
jQuery.post(the_ajax_script.ajaxurl, data.concat(jQuery("#theForm").serializeArray()),
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
}
);
try this, $.post can use arrays
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: When drawing a square inside a circle, can you assume the width of the square is 4/3 of the circle radius? I want to draw a square inside a circle. My circle has a radius of between 0.5 and 3.
is it safe to assume my square will always be 0.66 * 2 * radius wide/high?
I am making a function to calculate if a certain point is within the circle. I already made a square to get my points out of the database.
I want to make the square within the circle to quickly determine if a point is definately within my circle
A: A square that fits exactly in a circle should have a side length of sqrt(2) * radius.
A: This depends on what your definition of exactly is.
If you're using integer math, of course not because you can't represent it that course.
If you're using floating point arithmetic, then you can't because you could have rounding errors.
If you're using floating point arithmetic with a sufficiently course episilon, then assuming you've done your math right, yes you can make that assumption.
If you're using a decimal system that isn't floating point, then again assuming you've done your math right, yes you can make that assumption.
But regardless, if you want to determine if a point is within your circle, just use the Pythagorean theorem to get your distance to the center and compare the distance. You don't even have to use expensive square roots if you instead square the radius.
boolean isInCircle(Circle c, Point p) {
double dx = c.center.x - p.x;
double dy = c.center.y - p.y;
double r2 = c.radius * c.radius;
return dx*dx + dy*dy < r2;
}
A: The length of the diagonal of the square corresponds to two times the radius of the circle, i.e.
d = 2 * r
At the same time it is
d = sqrt(2) * a
where a is the length of one side of your square.
Thus
a = r * 2 / sqrt(2) = r * sqrt(2)
which is approximately
a = r * 1.41421
A: Technically, yes, a square of 4/3*r will be entirely inside the circle, but that's not the biggest square inside the circle. An inscribed square has sides of sqrt(2)*r.
Regardless, the easiest way to calculate whether the point is inside the circle is to check if the point is less than radius away from the center; see glowcoder's code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Subset dataframe by an unusual relation between columns I want to subset a dataframe which has an ID column (v1, all unique) and a "linked" ID column (v2). The expectation of v2 is that it may contain NAs, but where it does, the corresponsing element of v1 does not appear elsewhere in v2. Also, it is expected that the relation between the columns is symmetric: where there is an entry, x, in v2 the v1 entry of that row, y, is mirrored in another row where v1 has x and v2 has y. The last criteria is that the relation is not reflexive: ie x!=y.
I want to subset the dataframe to the elements which don't fit the expected criteria.
Here is some sample data to illustrate:
set.seed(1)
dfr <- data.frame(v1=letters,v2=rev(letters))
dfr[sample(26,10),2]<-NA
dfr[sample(26,5),2]<-sample(letters,5)
dfr
v1 v2
1 a z
2 b <NA>
3 c x
4 d w
5 e <NA>
6 f u
7 g <NA>
8 h s
9 i i
10 j <NA>
11 k p
12 l <NA>
13 m f
14 n <NA>
15 o l
16 p k
17 q j
18 r e
19 s <NA>
20 t g
21 u <NA>
22 v e
23 w <NA>
24 x q
25 y x
26 z a
So rows 1, 2, 11, 14, 16, and 26 all meet the criteria, and I want to identify the rest.
I have attempted some solutions using match, but the NAs are causing problems. It also probably relies on the fact that in this case v2 is based on rev(v1), whereas a more general solution can't make that assumption.
A: If I correctly understand, here is an example:
> subset(dfr, (is.na(v2) & !(v1%in%dfr$v2)) | !is.na(v2) & paste(v1, v2) %in% paste(dfr$v2, dfr$v1))
v1 v2
1 a z
2 b <NA>
9 i i
11 k p
14 n <NA>
16 p k
26 z a
# or if v1 == v2 is not included:
> subset(dfr, (is.na(v2) & !(v1%in%dfr$v2)) | !is.na(v2) & (v1 != v2 & paste(v1, v2) %in% paste(dfr$v2, dfr$v1)))
v1 v2
1 a z
2 b <NA>
11 k p
14 n <NA>
16 p k
26 z a
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it foolish not to use DirectShow as the basis of a CUDA video processing pipeline for Windows? When building a CUDA oriented video processing pipeline to run exclusively on windows,there are two approaches.
You either use DirectShow or you don't.
The decision not to use directshow is also the decision to code every portion of the pipeline yourself.
This includes reading, parsing, processing and rendering or retransmission of the stream. if if
With DirectShow, however, you gain access to a fairly large body of existing components that are quite capable of doing some portion of the pipeline's work.
This means you may focus your dev process on coding one or more DirectShow sources, filters, or renderers which use CUDA to encapsulate any novel or otherwise unavailable processing.
And as a result of adopting a component based architecture, you are in a good position to develop alternate implementations i.e. OpenCL. without having to touch the other parts of the pipeline.
Are there any liabilities to DirectShow participation that warrant the extra work involved to develop and maintain the pieces that are not CUDA specific?
A: If you haven't already, it might be useful to have a look at the "cudaDecodeD3D9" demo in the NVidia GPU SDK (CUDA SDK). It decodes and renders a video without DirectShow (using CUDA and DirectX9). Similarly, there's a "cudaDecodeOpenGL" demo if you prefer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to create custom iterator for Range I'd like to create a subclass of Range in order to specify a step size other than 1 so I can do things like:
>> a = RangeWithStepSize.new(-1, 2, 0.5).each {|x| puts(x)}
-1.0
-0.5
0.0
0.5
1.0
1.5
2.0
=> -1..2
My first attempt at an implementation doesn't work:
class RangeWithStepSize < Range
attr_reader :step_size
def initialize(start_v, end_v, step_size, exclusive = false)
super(start_v, end_v, exclusive)
@step_size = step_size
end
def each
self.step(step_size).each
end
end
>> a = RangeWithStepSize.new(-1, 2, 0.5).each {|x| puts(x)}
=> #<Enumerator: [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0]:each>
It appears that RangeWithStepSize#each is returning a valid enumerator, but it doesn't enumerate. Any idea why?
<aside>This may be related, but I notice is that Range#step without a block does NOT return an enumerator as specified in the documentation; it returns an array instead:
>> Range.new(-1, 2).step(0.5).class
=> Array
An Array is enumerable, but it is not an Enumerator. Is this a documentation bug?</aside>
clarification
I'd like to make a version of Range that encapsulates a step size, so I can do:
a = RangeWithStepSize(-1, 2, 0.5)
b = RangeWithStepSize(-1, 2, 0.25)
... so enumerating on a produces a step size of 0.5 and b produces 0.25.
A: You know you can do this, right? Inheritance isn't necessary here.
(-1..2).step(0.5) do |x|
puts x
end
Your code will work with a few small adjustments:
class RangeWithStepSize < Range
attr_reader :step_size
def initialize(start_v, end_v, step_size, exclusive = false)
super(start_v, end_v, exclusive)
@step_size = step_size
end
def each (&block)
self.step(step_size).each(&block)
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What actually happens when objects are dealloc'd in Objective-c? I'd like to understand Objective-c's memory management at a lower level. Say I have 100 bytes allocated on the heap to some Objective-c object. What happens to this 100 byte block when the object is dealloc'd?
I'm curious about how the runtime knows that a block of memory is available for re-use after it's dealloc'd. What happens to the actual bytes? Are they set to random values? Or perhaps they keep their values and just get overwritten by other objects later.
A: They keep their value but are marked as unused and overridable.
This behavior is just like the malloc & free functions in C.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: audio in internet explorer and cross-browser I have an audio element in a webpage for a client and i have coded it as well as i can but i still can't get it to work on All browsers. I know cross browser and browser editions (i.e. internet explorer 6,7,8,9 ) with audio is tricky but there has to be an answer here. Can this be done and without needing browser plugins? Here is my current code.
<audio preload="auto" autobuffer autoplay="autoplay">
<source src="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.mp3"/>
<source src="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.ogg" />
<source src="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.wav" />
<source src="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.au" />
<source src="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.wma" />
<!-- browser compatibility fallbacks -->
<object>
<param name="autostart" value="true">
<param name="src" value="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.wav">
<param name="autoplay" value="true">
<param name="controller" value="false">
<embed src="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.wav" controller="false" HIDDEN="TRUE" autoplay="true" autostart="True" type="audio/wav" />
<embed src="http://brodysfurniture.com/wp-content/themes/Brodys/images2/08_Track_8.mp3" controller="false" HIDDEN="TRUE" autoplay="true" autostart="True" type="audio/mpeg" />
</object>
<!-- End browser compatibility fallbacks -->
</audio>
A: I would look here for some answers. I personally have made a page that uses the native <audio> element but provides a WMP fall back for the less tech savvy users that insist on using old deprecated software.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to retrieve content passed back from remote server when the server reponds with a System.Net.WebException 422 I am working with an api that also returns a valid xml string containing the error that was encountered on their system.
<?xml version="1.0" encoding="UTF-8"?>
<error>
<request>Request made to server</request>
<message>No user found for account 12345</message>
</error>
Is there any way to get that xml from the remote server out of the System.Net.WebException object?
Thanks in advance :)
A: Direct from the MSDN docs:
When WebException is thrown by a descendant of the WebRequest class,
the Response property provides the Internet response to the
application.
So if you are if you are getting the exception while reading the response, you should just be able to read the Response property to get the XML contents.
A: Sure ya can! Just need to throw a try-catch around your request.GetResponse(), catch a WebException and read from the exceptions Response property.
WebRequest request = WebRequest.Create("http://www.google.com/ohnoa404");
WebResponse response;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
String responseString = String.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Notepad++ HTML Tidy Unknown Exception Windows 7 x64 When I attempt to run HTML Tidy from the TextFX menu in NotePad++ (v5.9.3) I get the following error:
Config file "C:\Program Files(x86)\Notepad++\plugins\Config\tidy\HTMLTIDY.CFG" not found! I'll pick whatever defaults I want to!
After I click OK I get:
"Unknown exception" and my cursor changes to the hourglass whenever I am in the document I was attempting to run HTMLTidy on.
The file exists in the location specified, I have tried changing the permissions on the file so Everyone has full control but that made no difference.
A: Windows 7 x64, Notepad++ 5.9.5 Solution:
It has to do with the libTidy.dll not being included in the current distributions.
However, it was available in earlier versions.
Solution is to download the 5.9 zip, then
copy the ansi\plugins\Config\tidy folder to your current Notepad++\plugins\Config folder
Also, if you install to the c:\Program Files or c:\Program Files (x86) directories, you will need to adjust the permissions on the tidy folder to allow non-administrator access
A: I have the same problem. Seems to be a bug. Wasted a few hours on this.
Ended up piping everything through the Tidy online beatutifier.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android app does not run on emulator I'm trying to run the Hello World tutorial code using Eclipse. I've set up an AVD but when I try and run the code, the emulator loads to the home screen and the app does not appear. No errors are shown in the console, and the logcat is completely empty (I've also left it running for 30 minutes).
Console output:
[2011-09-28 18:00:31 - AndroidTest] ------------------------------
[2011-09-28 18:00:31 - AndroidTest] Android Launch!
[2011-09-28 18:00:31 - AndroidTest] adb is running normally.
[2011-09-28 18:00:31 - AndroidTest] Performing com.example.helloandroid.AndroidTest activity launch
[2011-09-28 18:00:31 - AndroidTest] Automatic Target Mode: launching new emulator with compatible AVD 'myAVD'
[2011-09-28 18:00:31 - AndroidTest] Launching a new emulator with Virtual Device 'myAVD'
Code:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidTest extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello World!");
setContentView(tv);
}
}
I'm running on Windows 7 x64.
Thanks.
A: I think you need to create a quick layout, and set the content to the layout.
Create this home.xml in your /layout folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/my_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="24sp"
/>
</LinearLayout>
In onCreate, do this
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
This should work,
Later, you can reference to your TextView and change its text...
Let us know how it goes.
-serkan
A: Unlock the emulator and redeploy your app to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to pluck a Backbone collection's attribute I want to create an array of specific attribute values from a Backbone collection.
var days = _.select(
this.collection.models,
function(model) {
return model.attributes.type === 'session';
}
);
days = _.pluck(days, 'attributes'),
days = _.pluck(days, 'date');
This works, but seems inefficient. Is there a way to accomplish the same thing without having to define days three times?
A: I think this could work :
var days =
_( this.collection.where({ type : "session" }))
.chain()
.pluck("attributes")
.pluck("date")
.value()
Slightly more elegant, but still close to unreadable, in my opinion.
A: Have the same question, and figured out a better solution. I might have just taken advantage of new features in underscore, since it's 2013 now :)
var days = _.invoke(this.collection.where({type : 'session'}), 'get', 'date');
A: pluck is a convenience method that wraps map, and map is available directly on the collection, which should make this easier.
assuming you are trying to get the date attribute out of your models, you can do this:
days = this.collection.map(function(model){
return model.get('date');
});
your select call is also available on the collection directly, as the filter method.
days = this.collection.filter(function(model){
return model.attributes.type === 'session';
});
you can chain these two together, but it helps if you define methods separately:
var sessionFilter = function(model){
return model.attributes.type === 'session';
};
var getDate = function(model){ return model.get('date'); }
days = this.collection.filter(sessionFilter).map(getDate);
this should return the results your looking for... or something close to this at least :)
A: I should have read the docs more carefully. In addition to the pluck method in underscore, backbone collections also have a pluck method.
http://documentcloud.github.com/backbone/#Collection-pluck
So, my solution would be
//Assumme 'collection' is a backbone collection
collection.pluck('date');
I still need to figure out how to best combine with filtering - perhaps using ideas from @Derick's answer, but this answers the meat of my own question.
A: This is functionally the same as Derick's answer using _.chain()
var days = _(this.collection.models)
.chain()
.filter(function(model){return model.attributes.type === 'session';})
.pluck('date')
.value();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: What is this code in Javascript? On some JS code on some sites I see Javascript code such as this:
SomeName.init = (function () {
// some stuff
})();
I mean, this is not a jQuery plugin code such as this:
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Then, what is it? and what is the resulting JS object?
A: It's a anonymous function, which doesn't leak variables to the global scope when declaring variables using var.
SomeName.init = (function () {
return 3.1415;
})();
SomeName.init is a number (3.1415), because () after the anonymous function declaration executes the function. There's no way to obtain the original function, unless defined within the anonymous function:
(function foo(){
//foo refers to this function
too = foo;
})();;
//foo is undefined
//too refers to the function, because `too` has been defined without var
A: The Module Pattern. And those two snippets have more in common than you think.
A: (function () {
// some stuff
})()
is a anonymous function that calls itself instantly. It's just a closure around the code inside to stop the variable scope becoming global.
A: Whatever the function returns.
(function() {
//...
})();
Is used as a way to namespace code, or declare self-executing constructors. The resulting object is whatever that self-executing function returns.
The second snippet doesn't return anything and there is no resulting JS object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Dynamic Languages on / off the Java JVM I'm interested in learning a dynamic language after at least 10 years on the Java platform. There are two choices that I was considering. One, learning one such as Clojure / Groovy that ride on top of the Java JVM. Secondly, a language off the JVM, which would include Ruby / Rails or Erlang.
Having knowing alot about the Java side, I'd like to choose a JVM based solution, but considering an off the JVM solution.
My question is:
*
*What advantages / disadvantages would I get by choosing a language off of the Java JVM?
One of my biggest pain points is deployment memory footprint. I'd like to have a solution that allows low memory consumption, because most cloud / ISP providers require high dollar for anything greater the 512 MB / server. I've been so used to using High Memory JVM's which just don't work well with my costs. Maybe this isn't a concern for using clojure or groovy, but I'd expect a high memory footprint since it's running on the JVM.
I've already started using Ruby / Rails lately and I've been impressed with it.
A: If you go off the JVM then you have a good tool you can use in the cases where the JVM is poorly suited, like command line utilities where JVM startup time is really annoying.
If you go with Clojure you get both, with the clojure compiler you can produce classes for the JVM and with the ClojureScript compiler you can produce javascript that will run on very nearly anything.
My personal and therefore unverifiable advice is to go with the option that will expand your programming mind cough clojure but I am personally rather biased.
A: You could try JRuby to support ruby on and off a JVM.
I wouldn't assume that using JVM means using lots of memory. This depends on how you use the JVM. Using a profiler and more compact data structures can minimise memory usage. You can look at using C++, but if you are not careful C++ can use more memory. (But not if you know what you are doing)
How much memory you use is more about how you develop your program than which language you use.
A: For a low footprint solution, you may wish to consider JavaScript coupled with the V8 JS engine and Node.js technology
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Dojox FloatingPane is growing every time I update the content I've created a simple mapping widget using Dojo and Google Maps. The map is displayed in a dijit.layout.ContentPane set as the center panel of a dijit.layout.BorderContainer (which has the address field and a BusyButton in its top panel); the BorderContainer is in turn wrapped in a dojox.layout.FloatingPane. The widget has a subscription to a topic that will trigger a refresh of the map display when new address data is provided. The updater function is very simple, and looks like this:
_updateAddress: function(data) {
this.addressMapper.show();
if (data === null || !data.address || data.address === "" ) {
this.address.attr("value", "");
} else {
this.address.attr("value", data.address);
}
this.mapBtn.makeBusy();
this._getMap();
}
Every time I call this function, the FloatingPane's resize() method is invoked when I call show(), and it's increasing the height and width of the BorderContainer by 12 pixels every time the pane is shown (even with doLayout and isLayoutContainer set to false on the FloatingPane). I can't seem to prevent this from happening, or correct it afterwards, no matter what I try.
Anyone have any ideas how to remedy this?
Thanks in advance!
-- Joe M --
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Validation Rule not working in cakePHP I have a registration page and within this registration page the user will be required to fill in some interest, the interests values is called from a model with the name interest.php, all values are pulling through and saves as expected.
The relationship to the user model is
var $hasAndBelongsToMany = array(
'Interest' => array(
'className' => 'Interest',
'joinTable' => 'users_interests',
'foreignKey' => 'user_id',
'associationForeignKey' => 'interest_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
Whenever I add a validation rule in interest.php the little required star appears next to the checkboxes but it is not validating at all
<label for="InterestInterestId">Interests</label>
<input type="hidden" value="" name="data[Interest][interest_id]">
<div class="checkbox">
<input id="InterestInterestId8" type="checkbox" value="8" name="data[Interest][interest_id][]">
<label for="InterestInterestId8">Interest 1</label>
</div>
<div class="checkbox">
<input id="InterestInterestId1" type="checkbox" value="1" name="data[Interest][interest_id][]">
<label for="InterestInterestId1">Interest2</label>
</div>
in my view I call the multiple checkboxes like this
echo $form->input('Interest.interest_id', array('label' => __l('Interests'), 'multiple' => 'checkbox'));
This is my validation rule in interest.php
$this->validate = array(
'interest_id' => array(
'rule' => array(
'equalTo',
'1'
) ,
'message' => __l('Please select some interests')
)
);
Am I doing something wrong here, or missing something, any help will be appreciated!!!!
A: Found the answer with the help of this link HABTM form validation in CakePHP provided by bfavaretto
The problem was this $this->User->Interest->set($this->data);
I forgot to add it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Displaying decimals as fractions using SQL I need to write a SELECT query for some users that will return a ratio. The math involved would just be the simple division of two numbers. However, they would like to have the ratio presented as a fraction rather than as a decimal. What is the best way to do that in SQL using Oracle 10g?
A: You can define a function in Oracle to calculate greatest common divisor (taken from here):
CREATE FUNCTION gcd (x INTEGER, y INTEGER) RETURN INTEGER AS
ans INTEGER;
BEGIN
IF (y <= x) AND (x MOD y = 0) THEN
ans := y;
ELSIF x < y THEN
ans := gcd(y, x); -- Recursive call
ELSE
ans := gcd(y, x MOD y); -- Recursive call
END IF;
RETURN ans;
END;
And then use that function in your SQL to concatenate a fraction string:
SELECT CAST(TRUNC(A / GCD(A, B)) AS VARCHAR2(10))
|| ' / ' ||
CAST(TRUNC(B / GCD(A, B)) AS VARCHAR2(10)) AS FRACTION FROM TABLE
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: List all system certificate stores I'm looking for a way to get all system certificate stores, in any location (CurrentUser or LocalMachine).
The StoreLocation enumeration clearly won't include user-defined certificate stores created with X509Store(String) or X509Store(String, StoreLocation). Also this doesn't define other standard stores such as SPC or Request.
I've looked at the crypto32.dll API and I couldn't see anything relevant in there apart from register/unregister.
Non file-system based stores appear in the registry (eg HKEY_CURRENT_USER\SOFTWARE\Microsoft\SystemCertificates\Root). The PowerShell Certificate Provider can interrogate stores. Is this -- querying the registry -- what it's doing under the hood? Would such a hand-rolled solution be portable between XP/Vista/7/8?
A: Well, our SecureBlackbox product does what you need via CryptoAPI, namely CertEnumSystemStore() function. It has plenty of parameters, though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tumblr API2: Create A Photo Post with several Images Hi I have read the docs here:
http://www.tumblr.com/docs/en/api/v2#posting
I know how to upload one pic via the The photo 'source' URL parameter. like:
source: 'http://www.example.com/example.jpg'
How can I upload several pics in one photo post?
Thanks a lot!
A: Did you see this on the API page link for photo uploads?
data Array (URL-encoded binary contents) Limit: 5 MB
You would pass in an array containing the image links containing the multiple values as data instead of a single source file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Including a postscript file into another one? I wonder if there a standard way to include a postscript file into another.
For example, say I have got one file of data generated by a 3rd party program:
%!PS
\mydata [ 1 2 3 4 5 6
(...)
1098098
1098099
] def
and I would like to include it into a main PS document
%PS
\processData
{
mydata { (..) } foreach
}
(...)
(data.ps) include %<=== ???
Thanks
A: The operator you want is run.
string run -
execute contents of named file
Unfortunately, run is not allowed if the interpreter has the SAFER option set.
Edit: Bill Casselman, author of *Mathematical Illustrations" has a Perl script called psinc you can use to "preprocess" yor postscript files, inlining all (...) run files.
A: The standard way to include PostScript is to make the code to be included an EPS (Encapsulated PostScript) file. There are rules on how encapsulated PostScript must be created, and how to include it. See Adobe Tech Note 5002 'Encapsulated PostScript File Format Specification'
Simply executing 'run' on a PostScript file may well work, but it might also cause problems. Many PostScript files (especially those produced by 3rd parties) will include procedure definitions which may clash with your own names, and also the included program may leave the interpreter in a state different from the one it was in when the included file was executed. At the very least you should execute a save/restore pair around the code included via 'run'.
A: I would suggest meta-solution: use C preprocessor or M4 preprocessor. They are powerful tools and their power may find use in other ways as well, not only file inclusion. Though this was not asked, but use of Makefile will be wise to automate whole workflow. By using a preprocessor and Makefile in combination you can elegantly automate complex inclusions processing and beyond.
C Preprocessor
Including a file:
#include "other.ps"
Commandline for preprocessing:
cpp -P main.pps main.ps
M4 Preprocessor
Including a file:
include(other.ps)
Commandline for preprocessing:
m4 main.pps > main.ps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: add line break in mobile sms I am working with an API of a certain sms service and I just want to know how to add a line break from php code in a plain text format to mobile?
Can someone help me?
A: $text = "This is line 1.\nThis is line 2.";
Be sure to use double quotes around the string, not single quotes.
If that's not working, you'll need to talk to the folks who made the API.
A: If nothing working try with %0a like bellow:
$sms = 'This is line 1%0aThis is line 2';
A: Try with : "\r\n"
and also don't forget to enclose your message with double quotes.
It will work, if not the link below have more ways, try them...
https://codeupweb.wordpress.com/2017/07/18/how-to-add-a-line-break-in-sms-message/
A:
I know this is an old question but anyway it might help someone.
I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).
echo "line 1".PHP_EOL."line 2".PHP_EOL;
If you're planning to show the result in a browser then you have to use "<br>".
A: If API is HTTP based, then you should use url-encoded LF. If It isn´t work then you should use GSM-7.
A: you should use \n ,try this
$sender->sendMessage("Vocabulary:\n".$word.$meaning,$test);
A: It better to start with double quote it work fine. Do not use single quote
Use this example below to capture your idea
$message = "This is my message \n This is my second message"
A: I use clicksend api , and The "<br>" tag works correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: What is a good approach to bind an entityproxy to a UI component? I'm currently working on a GWT project. The thing is, I find very hard to believe that I need to repeat some boilerplate over and over to bind the data from an EntityProxy (say a getSomeData() method) to a UI component (say a TextBox).
How do you guys overcome this issue? For now I have to create a method to read from the TextBox and set it to the EntityProxy, and a method to write to the TextBox after reading from the EntityProxy.
Basically, it's always the same! i.e.:
// Update the text box
T someData = entity.getSomeData();
textBox.setText(someData);
// Update the entity
String value = textBox.getText();
entity.setSomeData(value);
You get my point? I'm aware there is no Reflection at client side. I could use deffered binding but I'm not sure how or if it is a good approach with RequestFactory's EntityProxys.
Thank you
A: I use the technique you have defined in your question to push and collect data from my controls. Recently I have found out that there is a built-in feature of GWT called Editors. I didn't have a chance to try it myself yet but perhaps you want to check it out it seems promising. Also here is another useful link from Thomas Broyer's blog about Editors
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: uiActivityindicatorView in splashscreen creates memory leakage problem? I want to display UIActivityIndicatorView over splash screen.
I'm just creating a splashView and activityindicator over splashview in AppDelegate.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//[NSThread sleepForTimeInterval:3];
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
splashView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UIImage *splashImage = [UIImage imageNamed:@"Splashimage.png"];
splashImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
splashImageView.image = splashImage;
[splashView addSubview:splashImageView];
progressIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(145,440,30,30)];
progressIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
[progressIndicator startAnimating];
[splashView addSubview:progressIndicator];
[self.window addSubview:splashView];
[NSThread detachNewThreadSelector:@selector(getInitialData:)
toTarget:self withObject:nil];
[self.window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
return YES;
}
- (void)getInitialData:(id)obj {
[NSThread sleepForTimeInterval:3.0];
[splashView removeFromSuperview];
[window addSubview:viewController.view];
}
It is working fine except memory leakage.
I'm getting message in console that autoreleased with no pool in place - just leaking.
What i m doing wrong?
Any help will be appreciated.
A: You don't seem to be releasing anything here.
A: Do you really need to make as ivar/properties ?
UIActivityIndicatorView* progressIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(145,440,30,30)];
progressIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
[progressIndicator startAnimating];
[splashView addSubview:progressIndicator];
[progressIndicator release]; // release
[self.window addSubview:splashView];
[splashView release]; // release
The following line is not none of my business:
I do not know, but first time i am seeing that some one is adding the
activity indicator on splash image. and why do you need to have
splashImageView, you could have directly make an entry in your plist
file for LaunchImage key entry
A: Your thread method getInitialData must create and drain an autorelease pool. This is done automatically for the main thread but not for any extra threads that you create. Just add this at the top of the method:
NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
and this at the bottom:
[localpool drain];
The reason that you are getting the error message is because viewController.view is returning an autoreleased object and you don't have an autorelease pool in place on the thread.
A: There's a couple problems here. You need to release anything you alloc. The variables splashview, splashImageView, and progressIndicator are allocated but not released, so those will leak.
The message you are getting about the NSAutoreleasePool is because you are doing getInitialData: on a separate thread. NSAutoreleasePools are per-thread, so you you need to do this:
-(void)getInitialData:(id)obj {
NSAutoreleasePool pool = [NSAutoreleasePool new];
[NSThread sleepForTimeInterval:3.0];
[splashView removeFromSuperview];
[window addSubview:viewController.view];
[pool release];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 2.3.5 collection_select: how to grab attributes from selected object and send to javascript function I have a collection_select with the following code:
<%= collection_select(:address, :id, current_user.addresses, :id, :address1, options ={:prompt => "Select an address"},
html_options={:onchange => "insert_address_fields()"}) %>
insert_address_fields gets called properly when i select an address in the list, but what i want to do is send all the attributes of of the selected address (first name, last name, address, city, state, etc) to the insert_address_fields function. Something like insert_address_fields(<% address.attributes %>), or, if i have to, list the the attributes individually. Is this possible with the setup i have now without making things overly complicated?
A: collection_select generates an <input> with a set of <options> fetched from the column of the table you are setting.
You can only (and should) send the selected address to insert_address_fields() by doing "insert_address_fields(this.value)". In this case, this will be the input field of the html.
The function should take care of fetching the relevant information from the address by accessing the database.
¿Why?
*
*Otherwise, you are giving too much responsiblity to the view. The view should not parse information and send it to the function (it should be the other way around!)
*If you add a column to the address atributes, you will need to change your view. Adding columns should be transparent to the view of your application
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the best approach to handling multiple file uploads in rails? I'm trying to attach multiple files to a comment model (currently with a has_many :attachments) using paperclip. It seems to be quite a lot of work and a bit fiddly for something that should be trivial. What's the modern rails way of doing this, with scalability and security taken into account?
A: I'd recommend using jQuery File Upload. It's compatible with all browsers and doesn't require any flash or whatever: only javascript.
Look in the wiki, there are tutorials. I made one for v3 and v4, and someone did the one for the latest version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to deal with namespaces in XML in XmlDocument c# I have several XML documents, all of which have the same structure (element names, attribute names and hierarchy).
However, some of the elements and attribute have custom namespaces in each XML document which are not known at design time. They change, don't ask...
How can I deal with this when traversing the documents using a single set of XPath?
Should I remove all the namespaces before processing?
Can I automatically register all namespaces with an XmlNamespaceManager?
Any thoughts?
Update: some examples (with namespace declarations omitted for clarity):
<root>
<child attr="val" />
</root>
<root>
<x:child attr="val" />
</root>
<root>
<y:child z:attr="val" />
</root>
Thanks
A: Suppose you have following xml:
<root xmlns="first">
<el1 xmlns="second">
<el2 xmlns="third">...
You can write you queries to ignore namespaces in the following way:
/*[local-name()='root']/*[local-name()='el1']/*[local-name()='el2']
etc.
Of course you can iterate over the whole document to get namespaces and load them into nsmanager. But in general case this will cause you to evaluate every node in the document. In this case it will be faster to just treat document as a tree of objects and don't use XPath.
A: I believe you'll find some good insight in this Stackoverflow thread
XPath + Namespace Driving me crazy
In my opinion you have either of two solutions:
1- If the set of all possible namespaces are know before hand, then you can register them all in a XmlNamespaceManager before you begin parsing
2- Use Xpath namespace-agnostic selectors
Of course you can always scrub the xml document from any inline namespaces and start your parsing on a clean unfiorm xml without namespace.. but honestly I don't see the gain in adding this overhead step.
A: Scott Hanselman has a nice article about extracting all of the XML Namespaces in an XML document. Presumably, when you get all of the XML Namespaces, you can just iterate over all of them and register them in your namespace manager.
A: You could try something like this to strip the namespaces:
//Implemented based on interface, not part of algorithm
public string RemoveAllNamespaces(string xmlDocument)
{
return RemoveAllNamespaces(XElement.Parse(xmlDocument)).ToString();
}
//Core recursion function
private XElement RemoveAllNamespaces(XElement xmlDocument)
{
if (!xmlDocument.HasElements)
{
XElement xElement = new XElement(xmlDocument.Name.LocalName);
xElement.Value = xmlDocument.Value;
return xElement;
}
return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
}
See Peter Stegnar's answer here for more details:
How to remove all namespaces from XML with C#?
A: You can also use direct node tests with wildcards, which will match any namespace (or lack thereof):
$your-document/*:root/*:child/@*:attr
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does cygwin's "-mwindows" switch work in windows 7? I am building an FLTK application in Windows XP under cygwin.
When I pass "-mwindows" to the linker, it behaves as advertized, and I don't get the command window popping up. However, when i run the same application under windows 7, a black console window pops up as if I hadn't passed -mwindows! does anyone know how i can debug this problem?
Thanks,
Woody
A: ak2 was right, i needed to update Cygwin.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Publishing on facebook using open graph This is Sasikumar A, I created the app for Galatta and i added the following details in web page head section
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xmlns:og="http://ogp.me/ns#" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta property="fb:app_id" content="123225854445872"><meta property="og:type" content="galatta-new:news"> <meta property="og:url" content="http://v3.galatta.com/tamil/news/tamannaah-the-golden-girl/39536/"><meta property="og:title" content="Tamannaah: The golden girl"> <meta property="og:description" content="Tamannaah: The golden girl"> <meta property="og:image" content="http://v3.galatta.com/community/images/logo.png"> <meta property="og:site_name" content="Galatta.com" /><meta property="og:locale" content="en_US" /></head><body><div id="fb-root"></div>{literal}<script>(function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js =d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js#appId=123225854445872&xfbml=1"; d.getElementsByTagName('head')[0].appendChild(js);}(document));</script>{/literal}<div class="fb-like" data-href="{$HTTP_REFERER}" data-send="true" data-layout="button_count" data-width="450" data-show-faces="false"
data-font="tahoma"></div></body></html>
Link : http://v3.galatta.com/tamil/news/tamannaah-the-golden-girl/39536/
I created the Open Graph action type, object type, aggregations for Galatta App.
In action type i got the code for - See all your Read actions:, Create a new Read action:, Delete a Read action:
Please tell me how to use this code in my web page.
I need while i click the Like button I need result like below / or how to work for below result.
Sasi Arjun read "Tamannaah: The golden girl" on Galatta
Please guide me how to publish the page on Facebook like above line.
A: Here is a really nice tutorial on exactly that topic.
If you are asking about the "code" links next to the action types in the Open Graph Developer tool: These serve just as an example, as you can invoke your actions via curl.
Your website would have to send these requests, e.g. using PHP on your server, or in the client's browser using the Facebook Javascript SDK.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ActionScript 2.0 - Matching Traces Don't Actually Match (lord help me for programming in AS2)
i'm itterating thru an array of text field objects and tracing the selected focus field when pressing tab, as well as each object.
i'm trying to equate these object, but while they trace the exact same they are not.
m_InputFieldsArray = new Array(m_TitleTextInput, m_CommentsTextArea, m_EmailTextInput);
for (var i:Number = 0; i < m_InputFieldsArray.length; i++)
{
trace("Get Focus: " + Selection.getFocus());
trace("Arr Index: " + m_InputFieldsArray[i].textField);
if (Selection.getFocus() == m_InputFieldsArray[i].textField)
{
trace("Match!");
return;
}
else
{
trace("NO Match!");
}
}
the output:
Get Focus: _level0.m_Window.form.m_TitleTextInput.textField
Arr Index: _level0.m_Window.form.m_TitleTextInput.textField
NO Match!
Get Focus: _level0.m_Window.form.m_TitleTextInput.textField
Arr Index: _level0.m_Window.form.m_CommentsTextArea.textField
NO Match!
Get Focus: _level0.m_Window.form.m_TitleTextInput.textField
Arr Index: _level0.m_Window.form.m_EmailTextInput.textField
NO Match!
the first group traces the same, but apparently they do not match. Selection.getFocus() returns a string, while the array index is tracing the text field object. if i add toString() to the text field object it will trace as [Object object]
how can i accomplish a match?
A: Use eval() for the Selection.getFocus()
A: An alternative, if you don't want to use eval(), that has a bad reputation, to get the same kind of string representation as Selection.getFocus() returns, you can use "" + m_InputFieldsArray[i].textField. It won't return "[Object object]", as toString() does.
That is basically what you see in your trace calls, that a string concatenated with the object reference gives the path to the object, rather than .toString() on the object.
I can't test AS2 right now, but I'm pretty sure that is how it works. So you could do something like this:
if (Selection.getFocus() == "" + m_InputFieldsArray[i].textField)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting timezone to UTC (0) in PHP Why does this work?
date_default_timezone_set('Australia/Currie');
But this doesn't seem to take any effect at all?
date_default_timezone_set('UTC');
This value doesn't change when setting the timezone to UTC:
echo date('Y-m-d H:i:s', time());
I'm using php 5.2.13, and the timezone of my server is:
$server_tz = date_default_timezone_get();
echo $server_tz; //outputs 'America/Guayaquil'
This is the original code:
echo time() . "<br>\n";
date_default_timezone_set('UTC');
echo time() . "<br>\n";
Output:
1317235130
1317235130
A: The problem is that you're displaying time(), which is a UNIX timestamp based on GMT/UTC. That’s why it doesn’t change. date() on the other hand, formats the time based on that timestamp.
A timestamp is the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
A: UTC is definitely a valid timezone. It is simply an abbreviation for Coordinated Universal Time. In addition, remember that date_default_timezone_set accepts one of the following values:
$timezones=array(
"America/Adak",
"America/Argentina/Buenos_Aires",
"America/Argentina/La_Rioja",
"America/Argentina/San_Luis",
"America/Atikokan",
"America/Belem",
"America/Boise",
"America/Caracas",
"America/Chihuahua",
"America/Cuiaba",
"America/Denver",
"America/El_Salvador",
"America/Godthab",
"America/Guatemala",
"America/Hermosillo",
"America/Indiana/Tell_City",
"America/Inuvik",
"America/Kentucky/Louisville",
"America/Lima",
"America/Managua",
"America/Mazatlan",
"America/Mexico_City",
"America/Montreal",
"America/Nome",
"America/Ojinaga",
"America/Port-au-Prince",
"America/Rainy_River",
"America/Rio_Branco",
"America/Santo_Domingo",
"America/St_Barthelemy",
"America/St_Vincent",
"America/Tijuana",
"America/Whitehorse",
"America/Anchorage",
"America/Argentina/Catamarca",
"America/Argentina/Mendoza",
"America/Argentina/Tucuman",
"America/Atka",
"America/Belize",
"America/Buenos_Aires",
"America/Catamarca",
"America/Coral_Harbour",
"America/Curacao",
"America/Detroit",
"America/Ensenada",
"America/Goose_Bay",
"America/Guayaquil",
"America/Indiana/Indianapolis",
"America/Indiana/Vevay",
"America/Iqaluit",
"America/Kentucky/Monticello",
"America/Los_Angeles",
"America/Manaus",
"America/Mendoza",
"America/Miquelon",
"America/Montserrat",
"America/Noronha",
"America/Panama",
"America/Port_of_Spain",
"America/Rankin_Inlet",
"America/Rosario",
"America/Sao_Paulo",
"America/St_Johns",
"America/Swift_Current",
"America/Toronto",
"America/Winnipeg",
"America/Anguilla",
"America/Argentina/ComodRivadavia",
"America/Argentina/Rio_Gallegos",
"America/Argentina/Ushuaia",
"America/Bahia",
"America/Blanc-Sablon",
"America/Cambridge_Bay",
"America/Cayenne",
"America/Cordoba",
"America/Danmarkshavn",
"America/Dominica",
"America/Fort_Wayne",
"America/Grand_Turk",
"America/Guyana",
"America/Indiana/Knox",
"America/Indiana/Vincennes",
"America/Jamaica",
"America/Knox_IN",
"America/Louisville",
"America/Marigot",
"America/Menominee",
"America/Moncton",
"America/Nassau",
"America/North_Dakota/Beulah",
"America/Pangnirtung",
"America/Porto_Acre",
"America/Recife",
"America/Santa_Isabel",
"America/Scoresbysund",
"America/St_Kitts",
"America/Tegucigalpa",
"America/Tortola",
"America/Yakutat",
"America/Antigua",
"America/Argentina/Cordoba",
"America/Argentina/Salta",
"America/Aruba",
"America/Bahia_Banderas",
"America/Boa_Vista",
"America/Campo_Grande",
"America/Cayman",
"America/Costa_Rica",
"America/Dawson",
"America/Edmonton",
"America/Fortaleza",
"America/Grenada",
"America/Halifax",
"America/Indiana/Marengo",
"America/Indiana/Winamac",
"America/Jujuy",
"America/Kralendijk",
"America/Lower_Princes",
"America/Martinique",
"America/Merida",
"America/Monterrey",
"America/New_York",
"America/North_Dakota/Center",
"America/Paramaribo",
"America/Porto_Velho",
"America/Regina",
"America/Santarem",
"America/Shiprock",
"America/St_Lucia",
"America/Thule",
"America/Vancouver",
"America/Yellowknife",
"America/Araguaina",
"America/Argentina/Jujuy",
"America/Argentina/San_Juan",
"America/Asuncion",
"America/Barbados",
"America/Bogota",
"America/Cancun",
"America/Chicago",
"America/Creston",
"America/Dawson_Creek",
"America/Eirunepe",
"America/Glace_Bay",
"America/Guadeloupe",
"America/Havana",
"America/Indiana/Petersburg",
"America/Indianapolis",
"America/Juneau",
"America/La_Paz",
"America/Maceio",
"America/Matamoros",
"America/Metlakatla",
"America/Montevideo",
"America/Nipigon",
"America/North_Dakota/New_Salem",
"America/Phoenix",
"America/Puerto_Rico",
"America/Resolute",
"America/Santiago",
"America/Sitka",
"America/St_Thomas",
"America/Thunder_Bay",
"America/Virgin",
"Indian/Antananarivo",
"Indian/Kerguelen",
"Indian/Reunion",
"Australia/ACT",
"Australia/Currie",
"Australia/Lindeman",
"Australia/Perth",
"Australia/Victoria",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Chisinau",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Madrid",
"Europe/Moscow",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Tallinn",
"Europe/Vatican",
"Europe/Zagreb",
"Pacific/Apia",
"Pacific/Efate",
"Pacific/Galapagos",
"Pacific/Johnston",
"Pacific/Marquesas",
"Pacific/Noumea",
"Pacific/Ponape",
"Pacific/Tahiti",
"Pacific/Wallis",
"Indian/Chagos",
"Indian/Mahe",
"Australia/Adelaide",
"Australia/Darwin",
"Australia/Lord_Howe",
"Australia/Queensland",
"Australia/West",
"Europe/Andorra",
"Europe/Bratislava",
"Europe/Copenhagen",
"Europe/Isle_of_Man",
"Europe/Lisbon",
"Europe/Malta",
"Europe/Nicosia",
"Europe/Riga",
"Europe/Simferopol",
"Europe/Tirane",
"Europe/Vienna",
"Europe/Zaporozhye",
"Pacific/Auckland",
"Pacific/Enderbury",
"Pacific/Gambier",
"Pacific/Kiritimati",
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Port_Moresby",
"Pacific/Tarawa",
"Pacific/Yap",
"Africa/Abidjan",
"Africa/Asmera",
"Africa/Blantyre",
"Africa/Ceuta",
"Africa/Douala",
"Africa/Johannesburg",
"Africa/Kinshasa",
"Africa/Lubumbashi",
"Africa/Mbabane",
"Africa/Niamey",
"Africa/Timbuktu",
"Africa/Accra",
"Africa/Bamako",
"Africa/Brazzaville",
"Africa/Conakry",
"Africa/El_Aaiun",
"Africa/Juba",
"Africa/Lagos",
"Africa/Lusaka",
"Africa/Mogadishu",
"Africa/Nouakchott",
"Africa/Tripoli",
"Africa/Addis_Ababa",
"Africa/Bangui",
"Africa/Bujumbura",
"Africa/Dakar",
"Africa/Freetown",
"Africa/Kampala",
"Africa/Libreville",
"Africa/Malabo",
"Africa/Monrovia",
"Africa/Ouagadougou",
"Africa/Tunis",
"Africa/Algiers",
"Africa/Banjul",
"Africa/Cairo",
"Africa/Dar_es_Salaam",
"Africa/Gaborone",
"Africa/Khartoum",
"Africa/Lome",
"Africa/Maputo",
"Africa/Nairobi",
"Africa/Porto-Novo",
"Africa/Windhoek",
"Africa/Asmara",
"Africa/Bissau",
"Africa/Casablanca",
"Africa/Djibouti",
"Africa/Harare",
"Africa/Kigali",
"Africa/Luanda",
"Africa/Maseru",
"Africa/Ndjamena",
"Africa/Sao_Tome",
"Atlantic/Azores",
"Atlantic/Faroe",
"Atlantic/St_Helena",
"Atlantic/Bermuda",
"Atlantic/Jan_Mayen",
"Atlantic/Stanley",
"Atlantic/Canary",
"Atlantic/Madeira",
"Atlantic/Cape_Verde",
"Atlantic/Reykjavik",
"Atlantic/Faeroe",
"Atlantic/South_Georgia",
"Asia/Aden",
"Asia/Aqtobe",
"Asia/Baku",
"Asia/Calcutta",
"Asia/Dacca",
"Asia/Dushanbe",
"Asia/Hong_Kong",
"Asia/Jayapura",
"Asia/Kashgar",
"Asia/Kuala_Lumpur",
"Asia/Magadan",
"Asia/Novokuznetsk",
"Asia/Pontianak",
"Asia/Riyadh",
"Asia/Shanghai",
"Asia/Tehran",
"Asia/Ujung_Pandang",
"Asia/Vladivostok",
"Asia/Almaty",
"Asia/Ashgabat",
"Asia/Bangkok",
"Asia/Choibalsan",
"Asia/Damascus",
"Asia/Gaza",
"Asia/Hovd",
"Asia/Jerusalem",
"Asia/Kathmandu",
"Asia/Kuching",
"Asia/Makassar",
"Asia/Novosibirsk",
"Asia/Pyongyang",
"Asia/Saigon",
"Asia/Singapore",
"Asia/Tel_Aviv",
"Asia/Ulaanbaatar",
"Asia/Yakutsk",
"Asia/Amman",
"Asia/Ashkhabad",
"Asia/Beirut",
"Asia/Chongqing",
"Asia/Dhaka",
"Asia/Harbin",
"Asia/Irkutsk",
"Asia/Kabul",
"Asia/Katmandu",
"Asia/Kuwait",
"Asia/Manila",
"Asia/Omsk",
"Asia/Qatar",
"Asia/Sakhalin",
"Asia/Taipei",
"Asia/Thimbu",
"Asia/Ulan_Bator",
"Asia/Yekaterinburg",
"Asia/Anadyr",
"Asia/Baghdad",
"Asia/Bishkek",
"Asia/Chungking",
"Asia/Dili",
"Asia/Hebron",
"Asia/Istanbul",
"Asia/Kamchatka",
"Asia/Kolkata",
"Asia/Macao",
"Asia/Muscat",
"Asia/Oral",
"Asia/Qyzylorda",
"Asia/Samarkand",
"Asia/Tashkent",
"Asia/Thimphu",
"Asia/Urumqi",
"Asia/Yerevan",
"Asia/Aqtau",
"Asia/Bahrain",
"Asia/Brunei",
"Asia/Colombo",
"Asia/Dubai",
"Asia/Ho_Chi_Minh",
"Asia/Jakarta",
"Asia/Karachi",
"Asia/Krasnoyarsk",
"Asia/Macau",
"Asia/Nicosia",
"Asia/Phnom_Penh",
"Asia/Rangoon",
"Asia/Seoul",
"Asia/Tbilisi",
"Asia/Tokyo",
"Asia/Vientiane",
"Australia/Canberra",
"Australia/LHI",
"Australia/NSW",
"Australia/Tasmania",
"Australia/Broken_Hill",
"Australia/Hobart",
"Australia/North",
"Australia/Sydney",
"Pacific/Chuuk",
"Pacific/Fiji",
"Pacific/Guam",
"Pacific/Kwajalein",
"Pacific/Niue",
"Pacific/Pitcairn",
"Pacific/Saipan",
"Pacific/Truk",
"Pacific/Chatham",
"Pacific/Fakaofo",
"Pacific/Guadalcanal",
"Pacific/Kosrae",
"Pacific/Nauru",
"Pacific/Palau",
"Pacific/Rarotonga",
"Pacific/Tongatapu",
"Pacific/Easter",
"Pacific/Funafuti",
"Pacific/Honolulu",
"Pacific/Majuro",
"Pacific/Norfolk",
"Pacific/Pohnpei",
"Pacific/Samoa",
"Pacific/Wake",
"Antarctica/Casey",
"Antarctica/McMurdo",
"Antarctica/Vostok",
"Antarctica/Davis",
"Antarctica/Palmer",
"Antarctica/DumontDUrville",
"Antarctica/Rothera",
"Antarctica/Macquarie",
"Antarctica/South_Pole",
"Antarctica/Mawson",
"Antarctica/Syowa",
"Arctic/Longyearbyen",
"Europe/Athens",
"Europe/Brussels",
"Europe/Dublin",
"Europe/Istanbul",
"Europe/Ljubljana",
"Europe/Mariehamn",
"Europe/Oslo",
"Europe/Rome",
"Europe/Skopje",
"Europe/Tiraspol",
"Europe/Vilnius",
"Europe/Zurich",
"Europe/Belfast",
"Europe/Bucharest",
"Europe/Gibraltar",
"Europe/Jersey",
"Europe/London",
"Europe/Minsk",
"Europe/Paris",
"Europe/Samara",
"Europe/Sofia",
"Europe/Uzhgorod",
"Europe/Volgograd",
"Europe/Belgrade",
"Europe/Budapest",
"Europe/Guernsey",
"Europe/Kaliningrad",
"Europe/Luxembourg",
"Europe/Monaco",
"Europe/Podgorica",
"Europe/San_Marino",
"Europe/Stockholm",
"Europe/Vaduz",
"Europe/Warsaw",
"Indian/Cocos",
"Indian/Mauritius",
"Indian/Christmas",
"Indian/Maldives",
"Indian/Comoro",
"Indian/Mayotte",
"Australia/Brisbane",
"Australia/Eucla",
"Australia/Melbourne",
"Australia/South",
"Australia/Yancowinna",
);
Timezones in PHP at http://www.php.net/manual/en/timezones.php
A: In PHP DateTime (PHP >= 5.3)
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->getTimestamp();
A:
List of entire available timezones.
$time_zones = array (
0 => 'Africa/Abidjan',
1 => 'Africa/Accra',
2 => 'Africa/Addis_Ababa',
3 => 'Africa/Algiers',
4 => 'Africa/Asmara',
5 => 'Africa/Asmera',
6 => 'Africa/Bamako',
7 => 'Africa/Bangui',
8 => 'Africa/Banjul',
9 => 'Africa/Bissau',
10 => 'Africa/Blantyre',
11 => 'Africa/Brazzaville',
12 => 'Africa/Bujumbura',
13 => 'Africa/Cairo',
14 => 'Africa/Casablanca',
15 => 'Africa/Ceuta',
16 => 'Africa/Conakry',
17 => 'Africa/Dakar',
18 => 'Africa/Dar_es_Salaam',
19 => 'Africa/Djibouti',
20 => 'Africa/Douala',
21 => 'Africa/El_Aaiun',
22 => 'Africa/Freetown',
23 => 'Africa/Gaborone',
24 => 'Africa/Harare',
25 => 'Africa/Johannesburg',
26 => 'Africa/Juba',
27 => 'Africa/Kampala',
28 => 'Africa/Khartoum',
29 => 'Africa/Kigali',
30 => 'Africa/Kinshasa',
31 => 'Africa/Lagos',
32 => 'Africa/Libreville',
33 => 'Africa/Lome',
34 => 'Africa/Luanda',
35 => 'Africa/Lubumbashi',
36 => 'Africa/Lusaka',
37 => 'Africa/Malabo',
38 => 'Africa/Maputo',
39 => 'Africa/Maseru',
40 => 'Africa/Mbabane',
41 => 'Africa/Mogadishu',
42 => 'Africa/Monrovia',
43 => 'Africa/Nairobi',
44 => 'Africa/Ndjamena',
45 => 'Africa/Niamey',
46 => 'Africa/Nouakchott',
47 => 'Africa/Ouagadougou',
48 => 'Africa/Porto-Novo',
49 => 'Africa/Sao_Tome',
50 => 'Africa/Timbuktu',
51 => 'Africa/Tripoli',
52 => 'Africa/Tunis',
53 => 'Africa/Windhoek',
54 => 'America/Adak',
55 => 'America/Anchorage',
56 => 'America/Anguilla',
57 => 'America/Antigua',
58 => 'America/Araguaina',
59 => 'America/Argentina/Buenos_Aires',
60 => 'America/Argentina/Catamarca',
61 => 'America/Argentina/ComodRivadavia',
62 => 'America/Argentina/Cordoba',
63 => 'America/Argentina/Jujuy',
64 => 'America/Argentina/La_Rioja',
65 => 'America/Argentina/Mendoza',
66 => 'America/Argentina/Rio_Gallegos',
67 => 'America/Argentina/Salta',
68 => 'America/Argentina/San_Juan',
69 => 'America/Argentina/San_Luis',
70 => 'America/Argentina/Tucuman',
71 => 'America/Argentina/Ushuaia',
72 => 'America/Aruba',
73 => 'America/Asuncion',
74 => 'America/Atikokan',
75 => 'America/Atka',
76 => 'America/Bahia',
77 => 'America/Bahia_Banderas',
78 => 'America/Barbados',
79 => 'America/Belem',
80 => 'America/Belize',
81 => 'America/Blanc-Sablon',
82 => 'America/Boa_Vista',
83 => 'America/Bogota',
84 => 'America/Boise',
85 => 'America/Buenos_Aires',
86 => 'America/Cambridge_Bay',
87 => 'America/Campo_Grande',
88 => 'America/Cancun',
89 => 'America/Caracas',
90 => 'America/Catamarca',
91 => 'America/Cayenne',
92 => 'America/Cayman',
93 => 'America/Chicago',
94 => 'America/Chihuahua',
95 => 'America/Coral_Harbour',
96 => 'America/Cordoba',
97 => 'America/Costa_Rica',
98 => 'America/Creston',
99 => 'America/Cuiaba',
100 => 'America/Curacao',
101 => 'America/Danmarkshavn',
102 => 'America/Dawson',
103 => 'America/Dawson_Creek',
104 => 'America/Denver',
105 => 'America/Detroit',
106 => 'America/Dominica',
107 => 'America/Edmonton',
108 => 'America/Eirunepe',
109 => 'America/El_Salvador',
110 => 'America/Ensenada',
111 => 'America/Fort_Nelson',
112 => 'America/Fort_Wayne',
113 => 'America/Fortaleza',
114 => 'America/Glace_Bay',
115 => 'America/Godthab',
116 => 'America/Goose_Bay',
117 => 'America/Grand_Turk',
118 => 'America/Grenada',
119 => 'America/Guadeloupe',
120 => 'America/Guatemala',
121 => 'America/Guayaquil',
122 => 'America/Guyana',
123 => 'America/Halifax',
124 => 'America/Havana',
125 => 'America/Hermosillo',
126 => 'America/Indiana/Indianapolis',
127 => 'America/Indiana/Knox',
128 => 'America/Indiana/Marengo',
129 => 'America/Indiana/Petersburg',
130 => 'America/Indiana/Tell_City',
131 => 'America/Indiana/Vevay',
132 => 'America/Indiana/Vincennes',
133 => 'America/Indiana/Winamac',
134 => 'America/Indianapolis',
135 => 'America/Inuvik',
136 => 'America/Iqaluit',
137 => 'America/Jamaica',
138 => 'America/Jujuy',
139 => 'America/Juneau',
140 => 'America/Kentucky/Louisville',
141 => 'America/Kentucky/Monticello',
142 => 'America/Knox_IN',
143 => 'America/Kralendijk',
144 => 'America/La_Paz',
145 => 'America/Lima',
146 => 'America/Los_Angeles',
147 => 'America/Louisville',
148 => 'America/Lower_Princes',
149 => 'America/Maceio',
150 => 'America/Managua',
151 => 'America/Manaus',
152 => 'America/Marigot',
153 => 'America/Martinique',
154 => 'America/Matamoros',
155 => 'America/Mazatlan',
156 => 'America/Mendoza',
157 => 'America/Menominee',
158 => 'America/Merida',
159 => 'America/Metlakatla',
160 => 'America/Mexico_City',
161 => 'America/Miquelon',
162 => 'America/Moncton',
163 => 'America/Monterrey',
164 => 'America/Montevideo',
165 => 'America/Montreal',
166 => 'America/Montserrat',
167 => 'America/Nassau',
168 => 'America/New_York',
169 => 'America/Nipigon',
170 => 'America/Nome',
171 => 'America/Noronha',
172 => 'America/North_Dakota/Beulah',
173 => 'America/North_Dakota/Center',
174 => 'America/North_Dakota/New_Salem',
175 => 'America/Ojinaga',
176 => 'America/Panama',
177 => 'America/Pangnirtung',
178 => 'America/Paramaribo',
179 => 'America/Phoenix',
180 => 'America/Port-au-Prince',
181 => 'America/Port_of_Spain',
182 => 'America/Porto_Acre',
183 => 'America/Porto_Velho',
184 => 'America/Puerto_Rico',
185 => 'America/Rainy_River',
186 => 'America/Rankin_Inlet',
187 => 'America/Recife',
188 => 'America/Regina',
189 => 'America/Resolute',
190 => 'America/Rio_Branco',
191 => 'America/Rosario',
192 => 'America/Santa_Isabel',
193 => 'America/Santarem',
194 => 'America/Santiago',
195 => 'America/Santo_Domingo',
196 => 'America/Sao_Paulo',
197 => 'America/Scoresbysund',
198 => 'America/Shiprock',
199 => 'America/Sitka',
200 => 'America/St_Barthelemy',
201 => 'America/St_Johns',
202 => 'America/St_Kitts',
203 => 'America/St_Lucia',
204 => 'America/St_Thomas',
205 => 'America/St_Vincent',
206 => 'America/Swift_Current',
207 => 'America/Tegucigalpa',
208 => 'America/Thule',
209 => 'America/Thunder_Bay',
210 => 'America/Tijuana',
211 => 'America/Toronto',
212 => 'America/Tortola',
213 => 'America/Vancouver',
214 => 'America/Virgin',
215 => 'America/Whitehorse',
216 => 'America/Winnipeg',
217 => 'America/Yakutat',
218 => 'America/Yellowknife',
219 => 'Antarctica/Casey',
220 => 'Antarctica/Davis',
221 => 'Antarctica/DumontDUrville',
222 => 'Antarctica/Macquarie',
223 => 'Antarctica/Mawson',
224 => 'Antarctica/McMurdo',
225 => 'Antarctica/Palmer',
226 => 'Antarctica/Rothera',
227 => 'Antarctica/South_Pole',
228 => 'Antarctica/Syowa',
229 => 'Antarctica/Troll',
230 => 'Antarctica/Vostok',
231 => 'Arctic/Longyearbyen',
232 => 'Asia/Aden',
233 => 'Asia/Almaty',
234 => 'Asia/Amman',
235 => 'Asia/Anadyr',
236 => 'Asia/Aqtau',
237 => 'Asia/Aqtobe',
238 => 'Asia/Ashgabat',
239 => 'Asia/Ashkhabad',
240 => 'Asia/Baghdad',
241 => 'Asia/Bahrain',
242 => 'Asia/Baku',
243 => 'Asia/Bangkok',
244 => 'Asia/Beirut',
245 => 'Asia/Bishkek',
246 => 'Asia/Brunei',
247 => 'Asia/Calcutta',
248 => 'Asia/Chita',
249 => 'Asia/Choibalsan',
250 => 'Asia/Chongqing',
251 => 'Asia/Chungking',
252 => 'Asia/Colombo',
253 => 'Asia/Dacca',
254 => 'Asia/Damascus',
255 => 'Asia/Dhaka',
256 => 'Asia/Dili',
257 => 'Asia/Dubai',
258 => 'Asia/Dushanbe',
259 => 'Asia/Gaza',
260 => 'Asia/Harbin',
261 => 'Asia/Hebron',
262 => 'Asia/Ho_Chi_Minh',
263 => 'Asia/Hong_Kong',
264 => 'Asia/Hovd',
265 => 'Asia/Irkutsk',
266 => 'Asia/Istanbul',
267 => 'Asia/Jakarta',
268 => 'Asia/Jayapura',
269 => 'Asia/Jerusalem',
270 => 'Asia/Kabul',
271 => 'Asia/Kamchatka',
272 => 'Asia/Karachi',
273 => 'Asia/Kashgar',
274 => 'Asia/Kathmandu',
275 => 'Asia/Katmandu',
276 => 'Asia/Khandyga',
277 => 'Asia/Kolkata',
278 => 'Asia/Krasnoyarsk',
279 => 'Asia/Kuala_Lumpur',
280 => 'Asia/Kuching',
281 => 'Asia/Kuwait',
282 => 'Asia/Macao',
283 => 'Asia/Macau',
284 => 'Asia/Magadan',
285 => 'Asia/Makassar',
286 => 'Asia/Manila',
287 => 'Asia/Muscat',
288 => 'Asia/Nicosia',
289 => 'Asia/Novokuznetsk',
290 => 'Asia/Novosibirsk',
291 => 'Asia/Omsk',
292 => 'Asia/Oral',
293 => 'Asia/Phnom_Penh',
294 => 'Asia/Pontianak',
295 => 'Asia/Pyongyang',
296 => 'Asia/Qatar',
297 => 'Asia/Qyzylorda',
298 => 'Asia/Rangoon',
299 => 'Asia/Riyadh',
300 => 'Asia/Saigon',
301 => 'Asia/Sakhalin',
302 => 'Asia/Samarkand',
303 => 'Asia/Seoul',
304 => 'Asia/Shanghai',
305 => 'Asia/Singapore',
306 => 'Asia/Srednekolymsk',
307 => 'Asia/Taipei',
308 => 'Asia/Tashkent',
309 => 'Asia/Tbilisi',
310 => 'Asia/Tehran',
311 => 'Asia/Tel_Aviv',
312 => 'Asia/Thimbu',
313 => 'Asia/Thimphu',
314 => 'Asia/Tokyo',
315 => 'Asia/Ujung_Pandang',
316 => 'Asia/Ulaanbaatar',
317 => 'Asia/Ulan_Bator',
318 => 'Asia/Urumqi',
319 => 'Asia/Ust-Nera',
320 => 'Asia/Vientiane',
321 => 'Asia/Vladivostok',
322 => 'Asia/Yakutsk',
323 => 'Asia/Yekaterinburg',
324 => 'Asia/Yerevan',
325 => 'Atlantic/Azores',
326 => 'Atlantic/Bermuda',
327 => 'Atlantic/Canary',
328 => 'Atlantic/Cape_Verde',
329 => 'Atlantic/Faeroe',
330 => 'Atlantic/Faroe',
331 => 'Atlantic/Jan_Mayen',
332 => 'Atlantic/Madeira',
333 => 'Atlantic/Reykjavik',
334 => 'Atlantic/South_Georgia',
335 => 'Atlantic/St_Helena',
336 => 'Atlantic/Stanley',
337 => 'Australia/ACT',
338 => 'Australia/Adelaide',
339 => 'Australia/Brisbane',
340 => 'Australia/Broken_Hill',
341 => 'Australia/Canberra',
342 => 'Australia/Currie',
343 => 'Australia/Darwin',
344 => 'Australia/Eucla',
345 => 'Australia/Hobart',
346 => 'Australia/LHI',
347 => 'Australia/Lindeman',
348 => 'Australia/Lord_Howe',
349 => 'Australia/Melbourne',
350 => 'Australia/North',
351 => 'Australia/NSW',
352 => 'Australia/Perth',
353 => 'Australia/Queensland',
354 => 'Australia/South',
355 => 'Australia/Sydney',
356 => 'Australia/Tasmania',
357 => 'Australia/Victoria',
358 => 'Australia/West',
359 => 'Australia/Yancowinna',
360 => 'Europe/Amsterdam',
361 => 'Europe/Andorra',
362 => 'Europe/Athens',
363 => 'Europe/Belfast',
364 => 'Europe/Belgrade',
365 => 'Europe/Berlin',
366 => 'Europe/Bratislava',
367 => 'Europe/Brussels',
368 => 'Europe/Bucharest',
369 => 'Europe/Budapest',
370 => 'Europe/Busingen',
371 => 'Europe/Chisinau',
372 => 'Europe/Copenhagen',
373 => 'Europe/Dublin',
374 => 'Europe/Gibraltar',
375 => 'Europe/Guernsey',
376 => 'Europe/Helsinki',
377 => 'Europe/Isle_of_Man',
378 => 'Europe/Istanbul',
379 => 'Europe/Jersey',
380 => 'Europe/Kaliningrad',
381 => 'Europe/Kiev',
382 => 'Europe/Lisbon',
383 => 'Europe/Ljubljana',
384 => 'Europe/London',
385 => 'Europe/Luxembourg',
386 => 'Europe/Madrid',
387 => 'Europe/Malta',
388 => 'Europe/Mariehamn',
389 => 'Europe/Minsk',
390 => 'Europe/Monaco',
391 => 'Europe/Moscow',
392 => 'Europe/Nicosia',
393 => 'Europe/Oslo',
394 => 'Europe/Paris',
395 => 'Europe/Podgorica',
396 => 'Europe/Prague',
397 => 'Europe/Riga',
398 => 'Europe/Rome',
399 => 'Europe/Samara',
400 => 'Europe/San_Marino',
401 => 'Europe/Sarajevo',
402 => 'Europe/Simferopol',
403 => 'Europe/Skopje',
404 => 'Europe/Sofia',
405 => 'Europe/Stockholm',
406 => 'Europe/Tallinn',
407 => 'Europe/Tirane',
408 => 'Europe/Tiraspol',
409 => 'Europe/Uzhgorod',
410 => 'Europe/Vaduz',
411 => 'Europe/Vatican',
412 => 'Europe/Vienna',
413 => 'Europe/Vilnius',
414 => 'Europe/Volgograd',
415 => 'Europe/Warsaw',
416 => 'Europe/Zagreb',
417 => 'Europe/Zaporozhye',
418 => 'Europe/Zurich',
419 => 'Indian/Antananarivo',
420 => 'Indian/Chagos',
421 => 'Indian/Christmas',
422 => 'Indian/Cocos',
423 => 'Indian/Comoro',
424 => 'Indian/Kerguelen',
425 => 'Indian/Mahe',
426 => 'Indian/Maldives',
427 => 'Indian/Mauritius',
428 => 'Indian/Mayotte',
429 => 'Indian/Reunion',
430 => 'Pacific/Apia',
431 => 'Pacific/Auckland',
432 => 'Pacific/Bougainville',
433 => 'Pacific/Chatham',
434 => 'Pacific/Chuuk',
435 => 'Pacific/Easter',
436 => 'Pacific/Efate',
437 => 'Pacific/Enderbury',
438 => 'Pacific/Fakaofo',
439 => 'Pacific/Fiji',
440 => 'Pacific/Funafuti',
441 => 'Pacific/Galapagos',
442 => 'Pacific/Gambier',
443 => 'Pacific/Guadalcanal',
444 => 'Pacific/Guam',
445 => 'Pacific/Honolulu',
446 => 'Pacific/Johnston',
447 => 'Pacific/Kiritimati',
448 => 'Pacific/Kosrae',
449 => 'Pacific/Kwajalein',
450 => 'Pacific/Majuro',
451 => 'Pacific/Marquesas',
452 => 'Pacific/Midway',
453 => 'Pacific/Nauru',
454 => 'Pacific/Niue',
455 => 'Pacific/Norfolk',
456 => 'Pacific/Noumea',
457 => 'Pacific/Pago_Pago',
458 => 'Pacific/Palau',
459 => 'Pacific/Pitcairn',
460 => 'Pacific/Pohnpei',
461 => 'Pacific/Ponape',
462 => 'Pacific/Port_Moresby',
463 => 'Pacific/Rarotonga',
464 => 'Pacific/Saipan',
465 => 'Pacific/Samoa',
466 => 'Pacific/Tahiti',
467 => 'Pacific/Tarawa',
468 => 'Pacific/Tongatapu',
469 => 'Pacific/Truk',
470 => 'Pacific/Wake',
471 => 'Pacific/Wallis',
472 => 'Pacific/Yap',
473 => 'Brazil/Acre',
474 => 'Brazil/DeNoronha',
475 => 'Brazil/East',
476 => 'Brazil/West',
477 => 'Canada/Atlantic',
478 => 'Canada/Central',
479 => 'Canada/East-Saskatchewan',
480 => 'Canada/Eastern',
481 => 'Canada/Mountain',
482 => 'Canada/Newfoundland',
483 => 'Canada/Pacific',
484 => 'Canada/Saskatchewan',
485 => 'Canada/Yukon',
486 => 'CET',
487 => 'Chile/Continental',
488 => 'Chile/EasterIsland',
489 => 'CST6CDT',
490 => 'Cuba',
491 => 'EET',
492 => 'Egypt',
493 => 'Eire',
494 => 'EST',
495 => 'EST5EDT',
496 => 'Etc/GMT',
497 => 'Etc/GMT+0',
498 => 'Etc/GMT+1',
499 => 'Etc/GMT+10',
500 => 'Etc/GMT+11',
501 => 'Etc/GMT+12',
502 => 'Etc/GMT+2',
503 => 'Etc/GMT+3',
504 => 'Etc/GMT+4',
505 => 'Etc/GMT+5',
506 => 'Etc/GMT+6',
507 => 'Etc/GMT+7',
508 => 'Etc/GMT+8',
509 => 'Etc/GMT+9',
510 => 'Etc/GMT-0',
511 => 'Etc/GMT-1',
512 => 'Etc/GMT-10',
513 => 'Etc/GMT-11',
514 => 'Etc/GMT-12',
515 => 'Etc/GMT-13',
516 => 'Etc/GMT-14',
517 => 'Etc/GMT-2',
518 => 'Etc/GMT-3',
519 => 'Etc/GMT-4',
520 => 'Etc/GMT-5',
521 => 'Etc/GMT-6',
522 => 'Etc/GMT-7',
523 => 'Etc/GMT-8',
524 => 'Etc/GMT-9',
525 => 'Etc/GMT0',
526 => 'Etc/Greenwich',
527 => 'Etc/UCT',
528 => 'Etc/Universal',
529 => 'Etc/UTC',
530 => 'Etc/Zulu',
531 => 'Factory',
532 => 'GB',
533 => 'GB-Eire',
534 => 'GMT',
535 => 'GMT+0',
536 => 'GMT-0',
537 => 'GMT0',
538 => 'Greenwich',
539 => 'Hongkong',
540 => 'HST',
541 => 'Iceland',
542 => 'Iran',
543 => 'Israel',
544 => 'Jamaica',
545 => 'Japan',
546 => 'Kwajalein',
547 => 'Libya',
548 => 'MET',
549 => 'Mexico/BajaNorte',
550 => 'Mexico/BajaSur',
551 => 'Mexico/General',
552 => 'MST',
553 => 'MST7MDT',
554 => 'Navajo',
555 => 'NZ',
556 => 'NZ-CHAT',
557 => 'Poland',
558 => 'Portugal',
559 => 'PRC',
560 => 'PST8PDT',
561 => 'ROC',
562 => 'ROK',
563 => 'Singapore',
564 => 'Turkey',
565 => 'UCT',
566 => 'Universal',
567 => 'US/Alaska',
568 => 'US/Aleutian',
569 => 'US/Arizona',
570 => 'US/Central',
571 => 'US/East-Indiana',
572 => 'US/Eastern',
573 => 'US/Hawaii',
574 => 'US/Indiana-Starke',
575 => 'US/Michigan',
576 => 'US/Mountain',
577 => 'US/Pacific',
578 => 'US/Pacific-New',
579 => 'US/Samoa',
580 => 'UTC',
581 => 'W-SU',
582 => 'WET',
583 => 'Zulu',
)
A: Is 'UTC' a valid timezone identifier on your system?
<?php
if (date_default_timezone_set('UTC')){
echo "UTC is a valid time zone";
}else{
echo "The system doesn't know WTFUTC. Maybe try updating tzinfo with your package manager?";
}
A: You can always check this maintained list to timezones
https://www.php.net/manual/en/function.date.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "59"
}
|
Q: pragmatic cross platform (and very fast to make it - actually - work) "throwaway" code: which language/tools? my development style brings me to write a lot of throw-away "assisting" code,
whether for automatic generation of code parts, semi-automated testing, and generally to build dummies, prototypes or temporary "sparring partners" for the main development; I know I'm not the only one...
since I frequently work both under windows and Unicies, I'd like to non-exclusively focus on a single "swiss army knife" tool that can work in both the environments with limited differences, that would allow me to do usual stuff like text parsing, db access, sockets, nontrivial filesystem and process manipulation
until now under unix I've used a bit of perl and massive amounts of shell scripts, but the latter are a bit limited and perl... despite being very capable and having modules for an incredible array of duties, sincerely I find it too "hostile" for me for something that goes beyond 100 lines of code.
what would you suggest?
scripting is not a requirement, it would be ok to use more static-styled languages IF it makes development faster (getting programs to actually do their work and possibly in a human readable state) and if it doesn't become nightmarish to handle errors/exception and to adapt to dynamic environments (e.g. I don't like to hardwire data /db table structure in my code, especially by hand).
I've been intrigued by python, ruby, but maybe groovy (with its ability to access the huge class library and his compact syntax) or something else is better suited
thanks a lot in advance!
(meanwhile, on a completely different note, scala looks really tempting just for the cleanliness of it, but that's - probably - a completely different story, unless you tell me the opposite...?)
A: Python is arguably one of the best choices. Its biggest benefit is that it has a huge built-in library for doing all sorts of stuff. It is also mature, very cross-platform, actively developed, and has many support options (mailing lists, newsgroups, etc).
In addition, it has a built-in GUI toolkit (tkinter) for those times when you need to write a quick GUI to get input from a user or display output from a running process. And if you don't like tkinter, there are other cross-platform GUI toolkits available.
A: I suggest Python.
For me it has a sweet spot of good libraries, documentation, community, cross-platform functionality, and ease of writing/reading.
It fills a similar niche to Perl's, but if you find Perl to be 'hostile' for longer scripts, you will probably like Python, especially when compared to Ruby, which feels more Perl-y, IMHO.
As an aside, all of these are quite easy to just try out - why not do that?
Then you can decide for yourself instead of trusting the questionable wisdom of an online forum (:
A: I think that Python and Ruby are your best bets, depending on exactly how you think and code.
I personally find Python EXTREMELY readable and its syntax is highly intuitive. I've heard Python described as "pseudo-code plus colons."
On the other hand, once you get around its slightly bizarre syntax, Ruby makes for high-speed development. It's built around DRY principles and convention-before-configuration, which is great for rapid prototyping.
There are other languages--especially Haskell and the Lisp dialects--that can make for super-rapid prototyping, but they don't have as large a supportive community, so there's a shortage in library and discussion supply.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Arg.Do() is not firing when expected in a When..Do for void method I have the below structure in a test of mine, intended to test that a certain log is being called with the right complex argument object, even when it throws an exception which is then wrapped and generally manipulated further.
The logThing has a method:
void AddEntry(LogEntry);
So I am using When..Do to make it throw an exception,
public void UnitTest()
{
// Arrange
ILogThing logThing = Substitute.For<ILogThing>()
SystemUnderTest system = new SystemUnderTest(logThing);
List<LogEntry> actualEntries = new List<LogEntry>();
LogEntry expectedEntry = GetSomeTestData();
logThing.When(
lt => lt.AddEntry(Arg.Do<LogEntry>(r => actualEntries.Add(r)))).Do(
call => { throw new InvalidOperationException("testMessage"); });
// Act
try
{
system.DoSomethingWhichLogs(someArgs)
}
catch(WrappedException ex)
{
// Assert
Assert.AreEqual(1, actualEntries.Count);
Assert.AreEqual(actualEntries[0], expectedEntry);
}
}
However, the expected call to Arg.Do() never happens with this setup.
I have put a breakpoint in the catch block, and used Visual Studio's immediate window to call RecievedCalls<>() on the logThing, and it does have a record of a single call to logThing with the right arguments - it's just that Arg.Do appears to only execute after the When..Do block has finished. Clearly that means that since I am throwing in the When..Do, it never reaches it.
I really didn't expect NSubstitute to order the calls in this way, is that expected behaviour?
If so, is there anything I can do to test the incoming argument like this, or should I just put my argument checking into the main When..Do block (which makes it harder to read)?
The system under test does various things to the exception which include wrapping it together with the logEntry, so it -is- useful for me to have all of these checks in one test - I did think about splitting it into two separate tests, but realized that if I did that, I couldn't easily pin down where the incorrect wrapped output was coming from (it could either be the part that originally generates the logEntry, or the part wrapping it) wheras with this pattern I can check to make sure the logThing is receiving what I expect it to. Still, if there's a better way to do that, I'm certainly open to suggestions.
A: The exact order of When..Do and Arg.Do isn't defined, and I wouldn't recommend counting on it as I imagine it could change between versions depending on implementation. (If you have a good reason to define it in a particular order please post your suggestion to the usergroup.)
If you just want to check logThing received the expected LogEntry, you can check the argument after the fact using Arg.Is():
logThing.Received().AddEntry(Arg.Is(expectedEntry));
If you need more complex comparison logic, you can do the same thing but use a method to check the argument:
logThing.Received().AddEntry(Arg.Is<LogEntry>(x => CheckLogEntry(x)));
CheckLogEntry can do whatever checks you require, and you can keep the When..Do throwing as before.
If you need to use the When..Do approach, you can can keep your existing approach but move the capture of the argument into the Do call to ensure the order of calls that you expect:
logThing.When(
lt => lt.AddEntry(Arg.Any<LogEntry>())).Do(
call =>
{
actualEntries.Add(call.Arg<LogEntry>());
throw new InvalidOperationException("testMessage");
});
In terms of suggestions for other ways of testing this, I'm not entirely clear on what you are trying to do here, but if you are having trouble isolating where the wrapped output is coming from maybe you could move this responsibility to another dependency? This would let you substitute for this dependency and control exactly where this happened from the perspective of this test.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: The simplest way to create a set of jquery object s Yeah, the way I was doing is
A.add(B).add(C).add(D).show()
While A,B,C,D are jQuery objects. I wonder if there's such a simpler way to do this out there?
I've tried all the following approaches, but no results:
$(A,B,C,D).show()
A.add(B,C,D).show()
All suggestions are welcome!
Addition to clarify the question:
The part ".show()" is just for demonstration. I just wanted to know how could I create a set of JQuery object like $('p') create a set of p tag.
In my real case, I used
$([A,B,C,D]).each(fn)
instead of .show() (And I wonder why this worked?)
It's obviously that
$([A,B,C,D]).each(fn)
$('p').each(fn)
both work. But
$([A,B,C,D]).show() //--doesn't work
$('p').show() //--works
Just the second line works. Does anyone know the diffrence between them ?
(I just thought they're the same, then made a bit of tangle in my question)
A: $.each([A,B,C,D], function(){
$(this).css('background','red');
})
Instead of using a selector this solution uses a jQuery method called $.each which takes an array and iterates over it. The array passed is a set of jQuery objects. $(this) referes to the jQuery objects being iterated on each time.
demo: http://jsfiddle.net/SCjMc/1/
Other facts about how $() works:
$(element) is an shortcut for jQuery(element). The jQuery() method accepts a different set of parameters:
The description for each type of parameter can be found in this link.
One of the type of parameters is "elementArray". The description for this is:
elementArray An array containing a set of DOM elements to wrap in a jQuery object.
The catch is that when you use jQuery to select an element this returns a jQuery object and not a DOM Element directly. Therefore this will not return any elements:
var element1 = $("selector1");
var element2 = $("selector2");
$([element1,element2]) // will not return any elements
To return a DOM Element instead of a jQuery object you have to access the property in the position of 0 of the jQuery object. As follows: $("element")[0]. And that is why this will work:
var element1 = $("selector1")[0]; //accessing dom element
var element2 = $("selector2")[0]; //from jQuery object
$([element1,element2])
A: Assuming you have raw DOM elements (not jQuery objects such as $('#abc') or $('.abc')), there's no need to use add:
$([A,B,C,D]).show();
See the documentation of the $(...) function for details.
If you really want something like $(A,B,C,D) where A,B,C,D are jQuery objects, then the only real way is to roll your own function.
This does the trick:
var all = function() {
var objs = $();
$.each(arguments, function(i,e) {
objs = objs.add(e);
});
return objs;
};
// ...
all(A,B,C,D).show();
Working example: http://jsfiddle.net/Jb6VD/5/
A: Here's the shortest version I could think of:
A.add([B[0], C[0], D[0]]).show();
This passes in an array of elements, rather than jQuery objects. Only works if B, C, and D are single-element arrays.
http://jsfiddle.net/nrabinowitz/Jb6VD/1/
A: To get the set resulting from the union of several jQuery objects (which are "just" arrays in a way), you can use $.merge:
var union = $.merge( $.merge(A,B), $.merge(C,D) );
$.merge only works on a pair of arrays, so using this on a large amount of jQuery objects would get very tiresome... in this case, you can use $().get() to obtain the "raw" array and concat them together:
var union = $([].concat(A.get(), B.get(), C.get(), ...));
// Assuming A, B, C... are jQuery objects
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Is this a valid sitemap URL? I have thousands of uique urls that look like this:
<url>
<loc>http://my_site_url/view_profile=1577</loc>
<changefreq>daily</changefreq>
</url>
are these urls that google or any other SE will crawl?
A: Yes, those links will definitely be crawled, but you should ensure that in addition to your sitemap they are in some way properly linked. Could the urls be improved? Definitely, in the following ways:
*
*Seperate words with dashes, not underscores
*Make use of url rewriting to change that = to a /
You may also want to consider using a username rather than profile number. You might find Google's Article on URL Structure interesting as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .Net text calculator (formula parser) I am going to implement custom server side validation of numeric user input.
All is what I nee is to be able to feed a formula to the calculator, feed parameters and get the result back.
The formula consist of basic arithmetical operation, for example like this
([name1] + [name2] - [name3])*1.5
Then it should accept parameters like
calculator.AddParam("name1", 12);
And return the result of calculation like
var result = calculator.Calculate();
Does such libriary exist for .net?
A: I've used Flee a couple times to do this pretty quickly and easily.
A: Try this
(C# compiling code at runtime)
http://www.codeproject.com/KB/recipes/matheval.aspx
A: You could reuse the Javascript engine that comes with Windows, as explained here: parse and execute JS by C#
It's quite powerful, supports 32-bit and 64-bit architectures, and does not need to be documented, as everyone knows how to write some JS statemements :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Telerik MVC Grid: Getting Parent Row Client-Side I am trying to get the value of a column in the parent row of a child row's onEdit event for a Telerik MVC Grid. How would I achieve that?
e.target.parentNode.parentNode.parentNode.innerHTML gives me table row of the parent row. I now need to parse this to get the column data I want. Someone know of a more elegant solution?
Steve
A: use $(e.target).parent('tr').find('td:nth-child(2)').text() where 2 is the column you want the contents of.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best-Practice for adding an empty row to a databound Listbox using Linq2SQL & Winforms what is the most robust method for adding a empty row (to select "nothing") to a ListBox?
Sofar i used:
Dim List = Enumerable.Repeat(New TABLE With {.Text = "", .ID = -1}, 1).AsQueryable().Union(From t In mainctx.TABLEs)
ddlMangelKategorie.DisplayMember = "Text"
ddlMangelKategorie.ValueMember = "ID"
ddlMangelKategorie.DataSource = List.ToList
But this has some drawbacks:
*
*wordy
*must explicit write the Type (TABLE in this case), so i cant wrap this in a function
*have not found an solution, which works with anonymous types
I.e. if I add a
From t In mainctx.TABLEs Select Text=col1, id=col2
to the query, this method does not work anymore.
Thanks
A: Here's how I would do it using Union (notice that you don't need Enumerable.Repeat nor AsQueryable).
Dim emptyTable As New TABLE With {.Text = "", .ID = -1}
Dim list = {emptyTable}.Union(mainctx.TABLEs).ToList()
ddlMangelKategorie.DataSource = list
With anonymous types:
Dim emptyTable = New With {.Text = "", .ID = -1}
Dim databaseTables = From t In mainctx.TABLEs
Select Text = t.col1, ID = t.col2
Dim list = {emptyTable}.Union(databaseTables).ToList()
ddlMangelKategorie.DataSource = list
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ImportError: No module named - Python I have a python application with the following directory structure:
src
|
+---- main
|
+---- util
|
+---- gen_py
|
+---- lib
In the package main, I have a python module named MyServer.py which has an import statement like:
from gen_py.lib import MyService
In order for this statement to work, I placed the following line at the beginning of MyServer.py:
import sys
sys.path.append('../gen_py/lib')
When I run MyServer.py in the terminal, I get the following error:
ImportError: No module named gen_py.lib
What I am missing here?
A: Your modification of sys.path assumes the current working directory is always in main/. This is not the case. Instead, just add the parent directory to sys.path:
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import gen_py.lib
Don't forget to include a file __init__.py in gen_py and lib - otherwise, they won't be recognized as Python modules.
A: For the Python module import to work, you must have "src" in your path, not "gen_py/lib".
When processing an import like import gen_py.lib, it looks for a module gen_py, then looks for a submodule lib.
As the module gen_py won't be in "../gen_py/lib" (it'll be in ".."), the path you added will do nothing to help the import process.
Depending on where you're running it from, try adding the relative path to the "src" folder. Perhaps it's sys.path.append('..'). You might also have success running the script while inside the src folder directly, via relative paths like python main/MyServer.py
A: from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py file on each directory.
A: make sure to include __init__.py, which makes Python know that those directories containpackages
A: This is if you are building a package and you are finding error in imports. I learnt it the hard way.The answer isn't to add the package to python path or to do it programatically (what if your module gets installed and your command adds it again?) thats a bad way.
The right thing to do is:
1) Use virtualenv pyvenv-3.4 or something similar
2) Activate the development mode - $python setup.py develop
A: Make sure if root project directory is coming up in sys.path output.
If not, please add path of root project directory to sys.path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
}
|
Q: C# TimeSpan two days equal the same time span? So I have a situation where I need to trigger certain events on a specific day, I thought I would use TimeSpan to get that specific day, the idea here is when the TimeSpan.Days == 0 I trigger my event, if its Less then or Greater then 0 do nothing...
but I thought this would work but two days give me 0
Here is what I am doing.
TimeSpan timeSpanDays = DateTime.Parse("12/13/2011").Subtract(DateTime.Now.AddDays(76));
TimeSpan timeSpanDays1 = DateTime.Parse("12/14/2011").Subtract(DateTime.Now.AddDays(76));
TimeSpan timeSpanMonths = DateTime.Parse("2011-11-28").Subtract(DateTime.Now.AddMonths(2));
TimeSpan timeSpanMonths1 = DateTime.Parse("2011-11-29").Subtract(DateTime.Now.AddMonths(2));
Console.WriteLine("14 days after issuance: {0}",timeSpanDays.Days);
Console.WriteLine("14 days after issuance: {0}",timeSpanDays1.Days);
Console.WriteLine("\r\n");
Console.WriteLine("22 months after issuance: {0}",timeSpanMonths.Days);
Console.WriteLine("22 months after issuance: {0}",timeSpanMonths1.Days);
Console.WriteLine("\r\n");
Console.WriteLine("TESTING DATE {0}",DateTime.Now.AddMonths(2));
Here Are the results
14 days after issuance: 0
14 days after issuance: 0
22 months after issuance: 0
22 months after issuance: 0
TESTING DATE 11/28/2011 10:55:43 AM
Is this because I'm not stripping the time on the DateTime.Now??
Any help or pointers would be greatly appreciated.
Thanks!!!
A: You're misunderstanding what the Days property is I think. I think what you want is TotalDays.
A: If you want to have the total of day between two DateTime you need to use the TotalDays of TimeSpan.
TotalDays, TotalMinutes, TotalHours, TotalMilliseconds give you the total amount of time between the time span.
On the other hand, Days, Minutes, Hours and Milliseconds give you the current component of the instance.
So, you need to change you example to use Total methods.
TimeSpan timeSpanDays = DateTime.Parse("12/13/2011").Subtract(DateTime.Now.AddDays(76));
TimeSpan timeSpanDays1 = DateTime.Parse("12/14/2011").Subtract(DateTime.Now.AddDays(76));
TimeSpan timeSpanMonths = DateTime.Parse("2011-11-28").Subtract(DateTime.Now.AddMonths(2));
TimeSpan timeSpanMonths1 = DateTime.Parse("2011-11-29").Subtract(DateTime.Now.AddMonths(2));
Console.WriteLine("14 days after issuance: {0}",timeSpanDays.TotalDays);
Console.WriteLine("14 days after issuance: {0}",timeSpanDays1.TotalDays);
Console.WriteLine("\r\n");
Console.WriteLine("22 months after issuance: {0}",timeSpanMonths.TotalDays);
Console.WriteLine("22 months after issuance: {0}",timeSpanMonths1.TotalDays);
Console.WriteLine("\r\n");
Console.WriteLine("TESTING DATE {0}",DateTime.Now.AddMonths(2));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery dialog dissappearing act? I'm using jQuery / jQueryUI to do some simple cookie checking on certain link types..
I want to check the cookie value on certain links and fire a form dialog if that value is met.
i.e.
<p id="clickLowValueAsset"><a href="page2.html" id="basic">go to page 2</a></p>
effectively firing this function on each click of type 'clickLowValueAsset'..
function checkLowValueCookie()
{
cookie_value=getCookie('assetPoints');
if (cookie_value != -1)
{
if (cookie_value>20) {
$('#lowValueSurvey').dialog('open');
}
else
{
setCookie('assetPoints',(parseInt(cookie_value) + 3),30);
}
}
}
--
My form dialog is as follows:
$(function(){
$('#lowValueSurvey').dialog({
bgiframe: true,
autoOpen: false,
modal: true,
width: 500,
resizable: false,
buttons: {
Submit: function(){
<!-- todo -->
}
}
});
});
Everything works great.. The dialog 'lowValueSurvey' is displayed correctly when the cookie condition is met.. However it immediately disappears after firing dialog.open; I think the href click happens causing the form dialog to disappear. I want to force the user to act on the form.. Either submit it or Close it -
How can I prevent this behavior? Or is does a better method exist to force dialog popups/form on a certain cookie condition?
thank you!
patrick
A: If it is the href trying to navigate to a new page add return false to the end of the function.
function checkLowValueCookie()
{
cookie_value=getCookie('assetPoints');
if (cookie_value != -1)
{
if (cookie_value>20) {
$('#lowValueSurvey').dialog('open');
return false;
}
else
{
setCookie('assetPoints',(parseInt(cookie_value) + 3),30);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Zend_Navigation and module specific layout I am developing a web site using the Zend Framework.
I was using this site to get my navigation working: http://www.rvdavid.net/zend_navigation-makes-writing-navigation-for-zf-sites-very-easy/.
However, the $this->layout()->menu returns NULL.
I have a modular structure, with a plugin that takes care of module specific layout:
<?php
class Custom_Controller_Plugin_ModuleBasedLayout
extends Zend_Layout_Controller_Plugin_Layout
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$this->getLayout()->setLayoutPath(Zend_Registry::get('config')->resources->frontController->moduleDirectory
. DS . $request->getModuleName() . DS . 'layouts' );
}
}
Does anybody have a clue why my navigation isn't working?
A: its $this->navigation()->menu();
not $this->layout()->menu
all the rendering stuff of Zend_Navigation is done by navigation view helper which you use in *.phtml files
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mysql php create extra colulmn in rs using as I have a question to which I have been unable to find the answer.
I can create an extra column in a PHP recordset by using an existing column and duplicating it:
SELECT
id_tst,
name_tst,
age_tst,
price_tst,
price_tst AS newprice_tst
FROM test_tst
From what I can work out the AS will only duplicate an existing colulmn or rename a column rs.
I want to add two extra columns to a table, but with no values.
I know a lot of people will say whats the point in that; it's pointless to have 2 columns with no data.
The reason is I am doing a price updating module for a CMS system, where the user can download a .csv file containing prices, modify the prices in a spreadsheet then re-upload the CSV to update he prices.
the two extra columns would be to hold the new prices keeping the old so a roll back from the CSV file could be performed if nessecary.
I could just get the client to add the two new colulmns into the spreadsheet, but would prefer to have the exported CSV with the columns already in place.
Is it possible to create blank columns when creaing an rs?
A: You can create empty "dummy" columns by aliasing a blank string:
SELECT '' AS emptyColumn, column1, column2 FROM table
This will produce another column in your query with all blank values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cocoa How to know if a file was edited/closed I open a file programmatically with the default application taking into account the file extension.
When the file is open, I need to know when the file is modified and when is no longer in use.
I used FSEventStreamCreate to create the event.
How can I know if the file was closed?
Thanks,
Ana
A: You can check the modified date of the file.
A: Here is the solution to see if my file was modified:
NSString * modified = [NSString stringWithFormat:@"%@",[fileAttributes objectForKey:@"NSFileModificationDate"]];
NSString * savedmod = [[NSUserDefaults standardUserDefaults] objectForKey:@"kFeedLastModified"];
[[NSUserDefaults standardUserDefaults] setObject:modified forKey:@"kFeedLastModified"];
[[NSUserDefaults standardUserDefaults] synchronize];
if (![savedmod isEqualToString:modified])
{
NSlog(@"File modified");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Which is better performance-wise: stored procedure or executing a query with dataadapter? I am reworking a .NET application that so far has been running slowly. Our databases are Oracle, and the code is written in VB. When writing queries, I typically pass the parameters to a middle tier function which builds the raw SQL. I have a database class that has a function ExecuteQuery which takes in a SQL string and returns a DataTable. This uses an OleDbDataAdapter to run the query on the database.
I found some existing code that sends the SQL and a parameter to a stored procedure which as far as I can tell, opens the query and ouputs it to a SYS_REFCURSOR / DataSet.
I don't know why it's set up this way, but could someone tell me which is better performance-wise? Or the pros/cons to doing it this way?
Thanks in advance
A: a stored procedure will definitely have better performance over building a raw query in code and executing it, but the important thing to realize is that, that difference in performance won't be your performance issue, there are many other things that will affect performance much more than just changing just query to be a stored procedure, even if you run a stored procedure and process the results using adapters, data tables, data sets, you're still incurring in a lot of performance, specially if you pass those large objects around (I have seen cases where datasets are returned wrapped in web service calls), so, don't focus on that, focus on caching data, having a good query, create the proper indexes, minimize the use of datasets, datatables, that will yield better benefits than just moving queries to stored procedures
A: Stored Procedures vs dynamic SQL have the exact same performance. In other words there is no performance advantage of one over the other. (Incidentally, I am a HUGE believer in using stored procs for everything for a host of other reasons but that's not the topic on hand).
Bottle necks can occur for many reasons.
For one, if you are actually code generating select statements it is highly probable that those statements are very unoptimized for the data the app needs. For example, doing a SELECT * which pulls 50 columns back versus a SELECT ID, Description which just pulls the two you need in your application at that point. In this example, the amount of data that has to be read from disk, transferred over the network wire, and pushed into objects in memory of the web server isn't trivial.
These will have to be evaluated on a case by case basis.
I would highly suggest that if you have a "slow" application that you need to improve the performance of the very first thing you ought to do is profile the application. What part of it is running slow? It might be inside the database server, it might be in your middle tier, it may even be a function of your network bandwidth or memory / load limitations on your web server. Heck, there might even be a WAIT command lurking somewhere in there placed by some previous programmer that left the company...
In short, you have at this point absolutely no idea on where to begin. So looking at actual code is premature. Go profile the app and see where things are slowing down. You might find that performance may radically improve simply by putting more memory in the database server.... Which is a much cheaper alternative than rewriting, testing and deploying vast amounts of code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the factors i should consider to select any MVC Framework I have worked on struts 1.2 and DWR as front end MVC framework.Now i have two projects to develop one is simple web application and another is complex.Which one i should select from most prevalent MVC Framework Spring mvc, Struts 2, DWR,JSF and brief reason to select any of the MVC . Most of the team knows all the frameworks. What are the factors i should consider to select any Framework.
A: I would consider what is the scope of my project, if I am anticipating complex system with lots and lots of various implementations, then I would go for Spring, for moderately complex system I would go for JSF.
One also need to consider if the primary designer leaves the team would other team members or a new comer will be able to pick particular MVC framework with ease or not (consider using well known MVC vs not-so-well-known-personal-favourite-picked-out-of-google). How mature the particular MVC framework is, are there good books written about it etc. These are just from top of my head.
Also keep in mind when there is too much of Spring (or any other ioC container) involved, there comes a time (after 8-12 months) when you are unable to debug code correctly because there are so many classes involved that you just keep tracking which class goes to which spring context files etc.
Finally, as one of my mentors used to say, don't solve the world problems (by using lots of design patterns), solve the problem at hand. :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: More help needed with farbtastic color picker
Possible Duplicate:
Help needed with farbtastic color picker. Simple example html included
I need a bit more help with the farbtastic color picker. I've got it working, and I can get it to change ONE ITEM on my page. But I need to get it to change the background color on a number of items, and can't figure out how to do it. Here is an example, where I've tried to do it with the jQuery change() event. Can anybody show me what I'm doing wrong?
http://bizzocall.com/farbtastic/demo1.html
A: I have the farbtastic color picker working really well now. Just for those of you who want an example to take apart and look at, here's a link. The sytax of how the farbtastic function is called to send the color to numerous items on the page is the tricky part. But, its working here. Just look at the source...
http://bizzocall.com/cp-BizzoActiveButton.php
This duplicates my answer to the other question. I put it here just in case someone stumbles upon this question instead of the other one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to refresh "Tasks" in Eclipse? I inherited a program with a lot of //TODO: messages, which i expected would show up under Tasks.
Unfortunately, that pane is empty. Is there a way to refresh it for the current project?
A: The tasks tags in *.java files are scanned automatically by Eclipse compiler. You can simply refresh your project and then click on the Project / Clean... menu. Also check that task tags are not disabled in the project settings under Java Compiler / Task Tags and your Tasks or Markers view in Eclipse configured to show tasks for an entire project and not only selected element.
A: There are two different views in eclipse. One is Tasks and the other is Task List. The latter shows build tasks using Mylyn. So for those who are looking for TODO list in java, please open Tasks in General view. Do a project clean if the list is empty.
A: In addition to Eugene's answer: A simple "Clean" is not enough, you have to build the project too.
(I do not use "Build Automatically", so I have to explicitly check "Start a build immediately" to get the Tasks View refreshed.)
A: The Clean method suggested by Eugene didn`t work for me, later I figured out that I didn't save the file, after saving it (ctrl+s) the Tasks view refreshed automatically.
A: If it is the "Eclipse IDE for C/C++ Developers" you are using then "Project -> C/C++ Index -> Rebuild" will do the trick rather than Project clean/build.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: keeping track of a moving shell script I hope someone can help me out. For the past month or so I have be learning the Bash... I have a program ( a simple language study program ) that I want to be able to install and run from a script.
I have a script that will create a new folder and move itself into it. The way I am doing it at the moment is below, although I have had problems with arrays that I am using later. I was wondering if there was a cleaner way of getting the new path to file name. Any help or insight would be greatly appreciated.
#!/bin/bash
echo "# path to me ---------------> ${0} "
echo "# parent path --------------> ${0%/*} "
echo "# my name ------------------> ${0##*/} "
if [[ ! -d ${0%/*}/SomeNewFolder ]] && [[ ! -d ${0%/*}/../SomeNewFolder ]]
then
mkdir ${0%/*}/SomeNewFolder
mv ${0} ${0%/*}/SomeNewFolder/${0##*/}
fi
echo ${0%/*}
newpath=$(echo "${0%/*}/SomeNewFolder")
echo $newpath
All the best, Ben
exit
A: For clarity, I would probably declare named variables for your common values instead of constantly reusing the ${0} array. It's also good practice to quote variables and strings.
The only major issue I saw, was running ./script.sh would make $0 equal just the filename, so I add "./" to the beginning in that case.
#!/bin/bash -u
ME="${0}"
if [[ ! "$ME" =~ /^\// ]]; then
ME="./$ME"
fi
PARENT="${ME%/*}"
FILENAME="${ME##*/}"
FOLDER="SomeNewFolder"
NEW="$PARENT/$FOLDER"
if [[ ! -d "$NEW" ]] && [[ "${PARENT%/*}" != "$FOLDER" ]]; then
mkdir "$NEW"
mv "$ME" "$NEW"
fi
echo "$PARENT"
echo "$NEW"
A: Well, you could do something like this to get an absolute path:
PARENTPATH=$( cd "$( dirname "$0" )" && pwd )
NEWPATH=${PARENTPATH}/SomeNewFolder
A: Installing and setting up programs is more appropriately done from a make file. Granted, it seems intimidating at first, but the basics, such as what you want, are quite simple. For your project, you would ideally have three item:
*
*your program
*your run script
*your makefile i.e. your installer
This breaks apart each of these different components, making each of them easier to manage. If you tar them together, you can move the tar file to a new computer and reinstall without any changes. Bash is a wonderful tool, but an installer it is not.
Sample make script below:
.PHONY: all clean
SCRIPT=yourScriptName.sh
SUBFOLDER=someFolder
all: $(SCRIPT)
$(SCRIPT): $(SUBFOLDER)
cp $(SCRIPT) $(SUBFOLDER)
$(SUBFOLDER):
mkdir $(SUBFOLDER)
clean:
-rm -f $(SUBFOLDER)/$(SCRIPT)
-rmdir $(SUBFOLDER)
IMPORTANT! make is whitespace sensitive! Those indents are tabs not four spaces.
A: me="$0"
newdir=SomeNewFolder
if [[ $me =~ ^/ ]] ; then
full_path="$me"
else
full_path="$PWD/$me"
fi
full_path="${full_path//\/\.\///}" # prettify
path_to_me="${full_path%/*}"
parent_dir="${path_to_me##*/}"
if [ ! "$parent_dir" = "$newdir" ] ; then
mkdir -p "$path_to_me/$newdir"
mv -f "$full_path" "$path_to_me/$newdir/"
fi
Basically similar to what lunixbochs was doing, but with a few minor alterations
*
*lower case variable names so as not to be confused with environment variables
*crudely estimates absolute path
*-f and -p becuase interactivity is never cool, and why not
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Converting Numpy Array to OpenCV Array I'm trying to convert a 2D Numpy array, representing a black-and-white image, into a 3-channel OpenCV array (i.e. an RGB image).
Based on code samples and the docs I'm attempting to do this via Python like:
import numpy as np, cv
vis = np.zeros((384, 836), np.uint32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
cv.CvtColor(vis, vis2, cv.CV_GRAY2BGR)
However, the call to CvtColor() is throwing the following cpp-level Exception:
OpenCV Error: Image step is wrong () in cvSetData, file /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp, line 902
terminate called after throwing an instance of 'cv::Exception'
what(): /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp:902: error: (-13) in function cvSetData
Aborted
What am I doing wrong?
A: This is what worked for me...
import cv2
import numpy as np
#Created an image (really an ndarray) with three channels
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)
#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255
#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)
#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image
#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])
#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)
A: Your code can be fixed as follows:
import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
Short explanation:
*
*np.uint32 data type is not supported by OpenCV (it supports uint8, int8, uint16, int16, int32, float32, float64)
*cv.CvtColor can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray do this conversion.
*Both arguments of cv.CvtColor must have the same depth. So I've changed source type to 32bit float to match the ddestination.
Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type:
import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
A: The simplest solution would be to use Pillow lib:
from PIL import Image
image = Image.fromarray(<your_numpy_array>.astype(np.uint8))
And you can use it as an image.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
}
|
Q: Style input type="text" I have an <input>, which is the body of a email form.
<input name="bodyEmail" style="width: 460px; height: 500px; " type="text" />
I would like to have a big input, and start writting from the top-left part. Whid this piece of code I start just in the centre, but the width and height are the propper ones.
Thanks in advance
A: It sounds like you might want a textarea instead.
<textarea name="bodyEmail" rows="6" cols="60">
The user can type multiple lines in a textarea.
You can specify the number of rows and columns this textarea should have.
</textarea>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Print the output of a shell command in Perl I would like to turn the outut of a shell command into a variable e.g. $result and then print it out on screen e.g. print $result
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }'
A: Just use backticks, and careful with the quoting:
my $result = `df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print \$5 " " \$1 }'`;
print $result;
A: I'm just a learner myself but I found this http://perldoc.perl.org/Shell.html useful... "This package is included as a show case, illustrating a few Perl features. It shouldn't be used for production programs".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Possible to prevent accidental bitwise operators on non-bitmask field? In C# you are recommended to add the [Flags] attribute to bitmask enumerations, like so:
[Flags]
public enum Condiments
{
None = 0,
Ketchup = 1,
Mustard = 2,
Mayo = 4,
Pickle = 8,
AllTheWay = 15
}
I discovered I had code that erroneously performed bitwise operations on an enumeration without the [Flags] attribute that was not a bitmask at all (First=1, Second=2, Third=3, etc.). This was of course logically wrong, but perfectly acceptable to the compiler.
I'm wondering if there's any way to leverage the [Flags] attribute, or some other approach, to turn this into a compile-time error/warning. I don't know where to begin, but it seems like it should be doable, so any help would be appreciated.
A: I would suggest for this "custom" checks, where compiler is not able to figure out the problem use http://research.microsoft.com/en-us/projects/contracts/. CodeContracts, if you can.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: GROUP_CONCAT Question So I am trying to do multiple GROUP_CONCAT()s in a query on the same column with if statements.
Even though the data is there, it is not giving me accurate info. I tried upping the group_concat_max_len, but I still get the same incorrect data.
Here is an example:
SELECT
field1,
field2,
GROUP_CONCAT(DISTINCT IF(field3 = 2, field4, NULL)) list1,
GROUP_CONCAT(DISTINCT IF(field3 = 3, field4, NULL)) list2,
GROUP_CONCAT(DISTINCT IF(field3 = 4, field4, NULL)) list3
FROM table1
GROUP BY field5
The results in the list1, list2 and list3 are not accurate, though the data is. Am I hitting some constraint from doing it this way?
A: SELECT field1,field2,last1,list2,list3 FROM
(
SELECT
field1,
field2,
field5,
GROUP_CONCAT(DISTINCT IF(field3 = 2, field4, 'NULL')) list1,
GROUP_CONCAT(DISTINCT IF(field3 = 3, field4, 'NULL')) list2,
GROUP_CONCAT(DISTINCT IF(field3 = 4, field4, 'NULL')) list3
FROM
table1
GROUP BY
field1,field2,field5
) A;
I changed the SELECT list, changed the GROUP BY, changed NULL to 'NULL', put the whole query in a subquery, and pull out of the subquery everything except field5. Please see if this produces the desired result.
If you want this query to run fast, please add this index:
ALTER TABLE table1 ADD INDEX (field1,field2,field5);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Warning: max() [function.max]: Array must contain at least one element - whats is this? So, im trying to do a poll, when i run mysql gives me this error, and i dont know what it means.
Warning: max() [function.max]: Array must contain at least one element in .... in line 18.
Could anyone please guide me of whats that?
This is my code:
$query = mysql_query("SELECT * FROM `poll` ORDER BY `id` ASC LIMIT 1");
$rows = mysql_num_rows($query);
if($rows > 0){
$poll = mysql_fetch_array($query);
$title = $poll['name'];
} else {
$title = 'No Poll Yet';
}
$query = mysql_query("SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`");
$me = array();
while($row = mysql_fetch_array($query)){
$me[] = $row['hits'];
}
$max = max($me); ////// THIS IS LINE 18
$query = mysql_query("SELECT `questions`.`pid` FROM `responses`, `questions` WHERE `responses`.`qid`=`questions`.`id` AND `responses`.`ip`='".$_SERVER['REMOTE_ADDR']."' AND pid='".$poll['id']."'");
line 18 is noted after "//////"
Any help ? :s
A: simply what the error-message says: $me is an empty array (caused by your sql-query returning nothing - why this happens is hard to say without seeing your tablestructure and contents of the table)
A: Just change in line number 18
if(!empty($me)) $max = max($me);
Full Code After Changes:
$query = mysql_query("SELECT * FROM `poll` ORDER BY `id` ASC LIMIT 1");
$rows = mysql_num_rows($query);
if($rows > 0){
$poll = mysql_fetch_array($query);
$title = $poll['name'];
} else {
$title = 'No Poll Yet';
}
$query = mysql_query("SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`");
$me = array();
while($row = mysql_fetch_array($query)){
$me[] = $row['hits'];
}
if(!empty($me)) $max = max($me); ////// THIS IS LINE 18
$query = mysql_query("SELECT `questions`.`pid` FROM `responses`, `questions` WHERE `responses`.`qid`=`questions`.`id` AND `responses`.`ip`='".$_SERVER['REMOTE_ADDR']."' AND pid='".$poll['id']."'");
A: You must be passing an empty array to the max() function. Just check the array is not empty before calling the max() or min() function. You can check by count($arr) > 0, Here are a few key points from the documentation.
max() in php, returns the parameter value considered "highest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.
If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.
The values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied. If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to bind to the submit event when HTML5 validation is used? Using HTML5 validation...
In HTML5 browsers, validation occurs before the submit event. So if the form is invalid, the submit event never fires.
I would like to hook an event into the form submit, to fire whether the form validates or not. Here's a small example, where I'm trying to alert() when the user submits the form.
HTML:
<!DOCTYPE html>
<html>
<head><title>Example</title></head>
<body>
<form>
<input type="text" name="foo" required title="Foo field"/>
<input type="submit"/>
</form>
</body>
</html>
JavaScript:
$(function() {
$('form').submit(function() {
alert('submit!')
});
});
Interactive demo: http://jsfiddle.net/gCBbR/
My question is: do browsers provide an alternative event that I can bind to that will run before the validation?
A: Yes, there is an event for that reason. The event is called invalid when user tries to submit the for orr when you check validity via HTML5 validation method checkValidity(). This event does not fire on blur or something like that without calling checkValidity() just because you have HTML validation attributes in your input tags. But it does fire on before form submit.
From W3C:
When the checkValidity() method is invoked, if the element is a
candidate for constraint validation and does not satisfy its
constraints, the user agent must fire a simple event named invalid
that is cancelable (but in this case has no default action) at the
element and return false. Otherwise, it must only return true without
doing anything else.
For example you have this markup:
<form>
<input type="text" name="foo" required title="Foo field"/>
<input type="submit"/>
</form>
Then you need to call checkValidity() to fire invalid event if the input data is invalid:
document.querySelectorAll('input')[0].addEventListener('blur', function(){
this.checkValidity();
}, false);
document.querySelectorAll('input')[0].addEventListener('invalid', function(){
console.log('invalid fired');
}, false);
Look at my example here: http://jsbin.com/eluwir/2
A: $(function() {
$('form').one('submit',function() {
alert(1);
[...]
$(this).submit(); // optional
return false; // returning false skips validator's trigger
});
});
this code will be executed only once, for permanent handling use $.bind
A: if you want to use the browser default validation you should use the following as you need to bind to the default submit then prevent the it and use $.ajax or $.post
$("form").bind('submit', function(e){
e.preventDefault();
$.post("url",$("form").serialize(),function(data){
$("#result").html(data).show();
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: jQuery - Run jQuery script each time a ".load" function is called? I am developing a control panel for a project, and I am having a bit of a conflict with some of my code. I am running some jQuery so that every link will insert the content of the requested page into a DIV. This code is located in the index.php page, so it's on first on the page to be run, no matter what. You never actually navigate away from the index.
$('a').live("click",function(){
var external = $(this).attr('class');
if (external == "externalLink") {
return true;
}
var page = $(this).attr('href');
if (!(page == "#") && (page)) {
$("#loading").fadeToggle("fast", "linear");
$("#split-view-right #content").load(page, function(){
var parentHeader = $("#split-view-right #content #parentHeader").html();
$("#split-view-right #header").html(parentHeader);
$("#loading").fadeToggle("fast", "linear");
});
}
return false;
});
In the #header, I also have some code being put there, including some buttons. Some of them I have just link to a page, which works great, but some I require to run a script. When I try to define a script to run on one of these pages, it will not find the button unless I run it with '.live'. The problem with that is, when I try to go to another page after it runs that live script, it ignores the hyperlink and runs that code again. Heres a sample of the code being run.
$(function() {
$("#headerbutton").live('click', function() {
$("#loading").fadeToggle("fast", "linear");
var title = $("input#title").val();
var partnum = $("input#partnum").val();
var descript = $("textarea#descript").val();
var startprice = $("input#startprice").val();
var minprice = $("input#minprice").val();
var domship = $("input#domship").val();
var intship = $("input#intship").val();
var startdate = $("input#startdate").val();
var droprate = $("input#droprate").val();
var dataString = 'title='+title+'&partnum='+partnum+'&descript='+descript+'&startprice='+startprice+'&minprice='+minprice+'&domship='+domship+'&intship='+intship+'&startdate='+startdate+'&droprate='+droprate;
$.post("savenewproduct.php",
{ "title": title, "partnum": partnum, "descript": descript, "startprice": startprice, "minprice": minprice, "domship": domship, "intship": intship, "startdate": startdate, "droprate": droprate },
function(postdata){
$("#split-view-right #content").load('upload_images.php?id=' + postdata.newID, function(){
var parentHeader = $("#split-view-right #content #parentHeader").html();
$("#split-view-right #header").html(parentHeader);
$("#loading").fadeToggle("fast", "linear");
});
}, "json");
return false;
});
});
What I would like to try and do (unless there is a better solution) is to make it so each time I run a '.load', I can run a '.die' script to cancel out the previous live codes on that page.
Any ideas?
A: First off, the following code can be simplified:
$('a').live("click",function(){
var external = $(this).attr('class');
if (external == "externalLink") {
return true;
}
...
becomes
$('a:not(.external)').live("click",function(){
...
As far as your load problem with scripts, if you are loading a page that contains scripts, make sure that the scripts are always after the elements that they are modifying. The $(function(){}); wont actually help you here because the DOMReady event has already been triggered when the main index was loaded.
A: I'm not sure if I've understood your details enough, but here's what I take from this.
Firstly, it sounds like .one() would've saved your behind here, if not for the .live() requirement. If you can manage to refactor your code so that you can take advantage of .one(), that would be great.
Barring that, why not just stick a .die() call on your .load() function's callback? From what I can see, your code is basically:
$('#headerbutton').live('click', function() {
// some stuff
$.post(foo, bar, function () {
$("#split-view-right #content").load(herp, function () {
// some stuff
// some more stuff
// ...
// what's stopping you from doing something like this:
$('#headerbutton').die('click');
});
});
});
That would effectively cancel out the .live() handler on your #headerbutton.
A: Not sure if this helps or not but you can try and use:
$('a:not(.external)').live("click", function(e){
e.preventDefault();
....
}
which will prevent the browser from following the link by default and allow you to execute your code instead.
A: i would use bind() to whatever user input produces a load()
http://api.jquery.com/bind/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get values in a report, like in a form? here is my situation:
I have a report that is displaying several values like the expected value and the obtained value. I would like to display an alert when the expected is over the obtained. This kind of manipulation is straightforward in a form:
If expectedCtrl > obtainedCtrl Then alertCtrl = "PROBLEM"
The problem is that in a report, its continuous aspect makes it impossible to get the expectedCtrl and obtainedCtrl values that way. Does anybody know the right way to perform this simple task ?
Thank you very much for your help, I'm really stuck on it and I don't have much time...
A: Just create an unbound control and set an expression for the control data source. Something like this...
=iif(expectedCtrl>obtainedCtrl, "PROBLEM","")
Alternatively you can use the Conditional Formatting feature and define a condition to change the color, for example, of the obtainedCtrl field if it is greater than the expectedCtrl.
A: I believe you need to set up some code for one of the events in the Detail section of the report. In the report's design view, right-click 'Detail', then properties, and check its events. This will allow you to run code for each detail record that shows up on the report.
A: You need to include both If and Else. For a picture, I suggest you set the visible property, say:
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
If expectedCtrl > obtainedCtrl Then
Me.PicAlert.Visible = True
Else
Me.PicAlert.Visible = False
End If
End Sub
Or more simply:
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
Me.PicAlert.Visible = (expectedCtrl > obtainedCtrl)
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: wpf dual monitor application? I'm very new to WPF. I want to create a dual monitor/projector application. What I want to do is have the "presenters screen" on one monitor and another panel on the secondary monitor, similar to how powerpoint works. I'm struggling to wrap my mind around the panels and XAML. So what I'm after is user clicks on a button on screen1 and information gets updated on screen2.
I'm using this code:
this.Width = System.Windows.SystemParameters.VirtualScreenWidth;
this.Height = System.Windows.SystemParameters.VirtualScreenHeight;
this.Top = 0;
this.Left = 0;
to set the width and height of the screen.
Edit:
The later goal is to cause screen2 to retrieve items out of a database based on the selection on screen1
Question: tutorials, places to go, nudges on how to update monitor2 from a button on monitor1
A: Short Answer
Create a view model that shared between two views; make one of the views the master (makes the changes) and the other pure presentation. The views are new windows. Initially do not be concerned with the window position (we'll get to that later) just get the shared viewmodel working.
Tip: research the MVVM pattern. Google has a lot of articles on the subject.
Long Answer
After you have researched MVVM and created a few example applications (from scatch or using a framework), below are few additional features you want implement to create the "powerpoint-like" application.
*
*Fullscreen Mode
At the very least you will want the presentation window to be full screen. To achieve this, you set the WindowStyle to None and AllowsTransparency to True.
If you want to make the second window also fullscreen you may need to do some Win32 overrides to get the window to maximize properly without covering the taskbar (post a comment if you want to know how to do this).
*Detect Multiple Monitors
Get the size and position of the monitors using Win32 Interop commands. There will be plenty of articles on the Internet that will help you with this (or post another StackoverFlow question).
This would be a neat™ feature as it will position the two windows correctly (use the secondary screen as the presentation).
That is all that I can think of now, post-back if you any questions on MVVM or any of the additional points above.
A: 1) You should have 2 Windows, the way this looks I'd make monitor2 a child window of monitor1 (after all, it is a child ;)
What i mean by that, is that StartupUri in App.xaml should point to monitor1, and in monitor1's constructor, you should create an instance of monitor2 (which would be a singleton if i were to do it).
2) To maximize a window on the second screen:
Subscribe to the Loaded event of the window (in code-behind), and set
private void Window_Loaded(object sender, RoutedEventArgs e) {
WindowState = WindowState.Maximized;
}
More info (and source): here
3) As to how to make monitor2 react when you set something in monitor1, make monitor1 and monitor2 bind to the same ViewModel, only they show different stuff.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Django. Pre-processing data from DB I need to add some additional information for data returned from DB. For example there is 'name' field in DB for Person and I need to add '{', '}' to it when it is showed on form. I thought that method bound_data of 'Field' class from 'django.forms.fields' module is what I need. But seems that it serves for other purposes. It works when form was submitted and failed validation for any reason - just to not lose data that was correct.
So how can I implement some decorating for my 'name' field?
A: I found in Field class of 'django.forms.fields' module the method 'prepare_value' which does some manipulation with data from DB or with some initial data for field. So I overrode this method in 'MyField' and placed all decoration work in it. It allow you to work with more than one fields of model, so guess it's better than unicode method.
But still thank Goran.
A: You didn't explain in what situation you need it. I was have the similar problem and I solve it inside unicode
class Person(models.Model):
name = models.CharField(max_length=150)
def __unicode__(self):
return '%s,' % self.name
Now inside form you will have unicode for the model and when you need just the name you use person.name instead. Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails how to touch Active Record Object without locking? In my photos class I have this association.
belongs_to :user, :touch => true
One day I got this exception.
A ActiveRecord::StatementInvalid occurred in photos#update:
Mysql::Error: Deadlock found when trying to get lock; try restarting transaction:
UPDATE `users` SET `updated_at` = '2011-09-20 14:17:44' WHERE `users`.`id` = 6832
production/ruby/1.8/gems/activerecord-3.0.10/lib/active_record/connection_adapters/abstract_adapter.rb:207:in `log'
What should I do to prevent future exceptions like this from occurring? I would like the update statement shown in the error to not use locking if possible. I don't think using optimistic locking will work in this case because optimistic locking would probably raise an ActiveRecord::StaleObjectError instead.
A: That's an issue I stumbled upon myself, too.
Short answer: There is no easy way around this problem. All the touches are wrapped in the same transaction, hence the deadlock.
Long answer: I am guessing you need touch objects to invalidate some sort of (dependent) caches. The usually recommended use of touch only works for a limited amount of "relationships". E.g. invalidating the article when the comment is being updated.
My solution was the asynchronous collection (using a sidekiq job) of DB Objects that need to be invalidated. I wrote my own control logic for it that defines what (other) objects need to be invalidated when an object changed. E.g. comment ==> article.
This way we had a way more verbose way invalidating dependent objects. Plus I invalidated using an Model.update_all which was way faster then the "touch chain". It solved our deadlock problems (and added verbosity and performance to our cache invalidation).
Extra tip: Don't use updated_at. It's highly debatable if a DB object really changed because another object changed. Overwriting the cache_key model lets you easily define a custom cache key like "#{id}-#{valid_from}". valid_from could be a timestamp you define on your models (and that you use instead of updated_at).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: cancelPreviousPerformRequest from background thread issue I have the following code, which is executed when a button is pressed:
[self performSelector:@selector(timeout:) withObject:nil afterDelay:30.0];
The issue comes in when I wanted to cancel this from a background thread:
[NSObject cancelPreviousPerformRequestsWithTarget:self];
I did this and it didn't cancel, it still calls timeout after 30 second. So my question, is there a way to cancel this from the background thread?
A: From the documentation, 'This method removes perform requests only in the current run loop, not all run loops.' That means that you have to call cancelPreviousPerformRequestsWithTarget on the main thread. Use performSelectorOnMainThread:withObject:waitUntilDone: from your thread to schedule a call to cancelPreviousPerformRequestsWithTarget on the main thread.
It's a roundabout way of doing things, but should work.
Edit to show example:
The easiest way is to use a helper method:
-(void)cancelTimeout
{
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
Then on your background thread call this when you want to cancel the timeout:
[self performSelectorOnMainThread:@selector(cancelTimeout) withObject:nil waitUntilDone:NO];
A: You can use NSTimer to call method after some time and invalidate if you want
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.