text stringlengths 8 267k | meta dict |
|---|---|
Q: MS Access, How to pass parameter to subquery? i've got two tables. one contains all my customers, another one all their orders.
i would like to create an sql query that looks like this:
SELECT c.CustomerID, c.Firstname, c.Lastname,
(
SELECT count(orderID)
FROM tbl_orders o
WHERE o.CustomerID = c.CustomerID
) as OrderCount
FROM tbl_customers c;
The problem I have with this is that access keeps asking me for the parameter "CustomerID" which would be used in the subselect WHERE clause. Obviously, I'd like to figure it out automatically. How do I do this?
A: There is no apparent reason, it should work. Maybe you made a mispell on one of your fields. Check if CustomerID is part of tbl_orders & tbl_customers.
You can find some information about sub query thru the following link : SubQueryDoc
A: Why not trying with a join and a group by ? it seems simpler and richer to me.
SELECT c.CustomerID, c.Firstname, c.Lastname, count(o.orderId) as Orders, max(o.OrderDate) as LastOrder
FROM tbl_customers c LEFT JOIN tbl_orders o
ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerID, c.Firstname, c.Lastname
Such a query can be designed visually in the query design view. You can then switch to SQL View, and copy or edit the generated SQL statement.
A: Remove alias "c" on both main and sub query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: set table row height My lacking skills of CSS is giving me a headache. As presented in this picture below, captured from firebug:
Using a GWT like framework called Vaadin I have given a Table component the class name m2m-modal-table and I want set a min-height to the four rows in that table. However, I can't seem to get it to work.. And as you see from the image the table doesn't even seem to have the class name m2m-modal-table but v-table-table instead (styles are being added outside my involvement since I'm using an already setup framework library).
So, can anyone who has good knowledge of CSS class referring tell me what I should write in the style sheet to set the row height of the table?
Thank you!
EDIT: Thank you avall for the help. And I found that writing the CSS as:
.m2m-modal-table .v-table-table th,
.m2m-modal-table .v-table-table td {
height: 55px;
min-height: 55px;
}
Will only set the style on the table in question and not all tables in the application.
A: Always set your height to cells, not rows.
.v-table-table th,
.v-table-table td{
height: 55px;
/* min-height: 55px; EDITED */
}
will do (min-height alone doesn't work).
Edit: As djsadinoff wrote, min-height doesn't work everywhere. IE8 and IE9 interpret min-height but it is not the norm for other browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Browser Update Script Browser-Update.org provides a nice piece of javascript which alerts users of out-of-date browsers to update them. Unfortunately (a) IE7 is not included in the default list of out-of-date browsers, and (b) the script doesn't work over SSL.
The script they suggest is
<script type="text/javascript">
var $buoop = {}
$buoop.ol = window.onload;
window.onload=function(){
try {if ($buoop.ol) $buoop.ol();}catch (e) {}
var e = document.createElement("script");
e.setAttribute("type", "text/javascript");
e.setAttribute("src", "http://browser-update.org/update.js");
document.body.appendChild(e);
}
</script>
Instead, I'm using external javascript as follows:
app.onload(function() {
if ('https:' === document.location.protocol) return; // Browser Update script is not currently available over SSL.
var $buoop = {vs:{i:7,f:2,o:10.5,s:2,n:9}};
var e = document.createElement('script');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', 'http://browser-update.org/update.js');
document.body.appendChild(e);
});
To be clear: app.onload() is a nice function which adds functions to the window.onload handler.
This seems to work, but there's an unfortunate side-effect. If the alert is dismissed, it shouldn't show again in that browsing session. With the script above, that doesn't seem to work. On IE7, the alert happens on each page load. Is there a way around that?
A: var _shown = false;
app.onload(function() {
if(!_shown) {
if ('https:' === document.location.protocol) return; // Browser Update script is not currently available over SSL.
var $buoop = {vs:{i:7,f:2,o:10.5,s:2,n:9}};
var e = document.createElement('script');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', 'http://browser-update.org/update.js');
document.body.appendChild(e);
_shown = true;
}
});
and if the page is reloading between navigation store it in a cookie or as a session variable.
A: you could save a cookie when the alert is shown and check every time if that cookie exists before showing the alert.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to parse JSON in iOS App Im getting a response from twitter in the form of a string,
What I need is to send the parts where is a comment to an array,
here an example of the string
[{"geo":null,"coordinates":null,"retweeted":false,...
"text":"@KristinaKlp saluditos y besos d colores!"},{"geo":null,"coordinates...
so what I really need are the posts after "text":" =
@KristinaKlp saluditos y besos d colores!
So, how can I take the string and parse it so I get all the messages in an array hopefully?
Thanks a lot!
A: NSJSONSerialization does the job of converting your JSON data into usable data structures as NSDictionary or NSArray very well. I recommend it, even more because it is part of the Cocoa public interface and it is maintained by Apple.
However, if you want to map the content of your JSON to your Objective-C objects, you will have to map each attribute from the NSDictionary/NSArray to your object property. This might be a bit painful if your objects have many attributes.
In order to automatise the process, I recommend you to use the Motis category (personal project) on NSObject to accomplish it, thus it is very lightweight and flexible. You can read how to use it in this post. But just to show you, you just need to define a dictionary with the mapping of your JSON object attributes to your Objective-C object properties names in your NSObject subclasses:
- (NSDictionary*)mjz_motisMapping
{
return @{@"json_attribute_key_1" : @"class_property_name_1",
@"json_attribute_key_2" : @"class_property_name_2",
...
@"json_attribute_key_N" : @"class_property_name_N",
};
}
and then perform the parsing by doing:
- (void)parseTest
{
NSData *data = jsonData; // <-- YOUR JSON data
// Converting JSON data into NSArray (your data sample is an array)
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error)
return; // <--- If error abort.
// Iterating over raw objects and creating model instances
NSMutableArray *parsedObjects = [NSMutableArray array];
for (NSDictionary *rawObject in jsonArray)
{
// Creating an instance of your class
MyClass instance = [[MyClass alloc] init];
// Parsing and setting the values of the JSON object
[instance mjz_setValuesForKeysWithDictionary:rawObject];
[parsedObjects addObject:instance];
}
// "parseObjects" is an array with your parsed JSON.
// Do whatever you want with it here.
}
The setting of the properties from the dictionary is done via KeyValueCoding (KVC) and you can validate each attribute before setting it via KVC validation.
A: I haven't done JSON parsing myself in an iOS App, but you should be able to use a library like the json-framework. This library will allow you to easily parse JSON and generate json from dictionaries / arrays (that's really all JSON is composed of).
SBJson docs:
JSON is mapped to Objective-C types in the following way:
*
*null -> NSNull
*string -> NSString
*array -> NSMutableArray
*object -> NSMutableDictionary
*true -> NSNumber's -numberWithBool:YES
*false -> NSNumber's -numberWithBool:NO
*integer up to 19 digits -> NSNumber's -numberWithLongLong:
*all other numbers -> NSDecimalNumber
Since Objective-C doesn't have a dedicated class for boolean values,
these turns into NSNumber instances. However, since these are
initialised with the -initWithBool: method they round-trip back to JSON
properly. In other words, they won't silently suddenly become 0 or 1;
they'll be represented as 'true' and 'false' again.
As an optimisation integers up to 19 digits in length (the max length
for signed long long integers) turn into NSNumber instances, while
complex ones turn into NSDecimalNumber instances. We can thus avoid any
loss of precision as JSON allows ridiculously large numbers.
@page objc2json Objective-C to JSON
Objective-C types are mapped to JSON types in the following way:
*
*NSNull -> null
*NSString -> string
*NSArray -> array
*NSDictionary -> object
*NSNumber's -initWithBool:YES -> true
*NSNumber's -initWithBool:NO -> false
*NSNumber -> number
@note In JSON the keys of an object must be strings. NSDictionary
keys need not be, but attempting to convert an NSDictionary with
non-string keys into JSON will throw an exception.
NSNumber instances created with the -numberWithBool: method are
converted into the JSON boolean "true" and "false" values, and vice
versa. Any other NSNumber instances are converted to a JSON number the
way you would expect.
Tutorials
Are there any tutorials? Yes! These are all tutorials provided by
third-party people:
JSON Framework for iPhone - a Flickr tutorial in three parts by John
Muchow. JSON Over HTTP On The iPhone - by Dan Grigsby. AS3 to Cocoa touch: JSON by Andy Jacobs.
There are other libraries you can check out as well like TouchJSON, JSONKit, Yet Another JSON Library
A: For a good comparison of the speed of the different libraries for JSON parsing on iOS, take a look at The Ultimate Showdown.
A: I recently had to do this. After looking at the various options out there, I threw JSONKit into my app (I found it on a JSON discussion on StackOverflow). Why?
A) It is VERY VERY simple. I mean, all it has is the basic parsing/emitting functions, what more do you need?
B) It is VERY VERY fast. No overhead - just get the job done.
I should note, I had never done JSON before - only heard of the term and didn't even know how to spell it. I went from nothing, to a working app, in about 1 hour. You just add one class to your app (the .h, .m), instantiate it, and call the parser to a dictionary object. Voila. If it contains an array, you just get the objectForKey, cast it as an NSArray. It's really hard to get simpler than that, and very fast.
A: -(IBAction)btn_parse_webserivce_click:(id)sender
{
// Take Webservice URL in string.
NSString *Webservice_url = self.txt_webservice_url.text;
NSLog(@"URL %@",Webservice_url);
// Create NSURL from string.
NSURL *Final_Url = [NSURL URLWithString:Webservice_url];
// Get NSData from Final_Url
NSData* data = [NSData dataWithContentsOfURL:
Final_Url];
//parse out the json data
NSError* error;
// Use NSJSONSerialization class method. which converts NSData to Foundation object.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
// Create Array
NSArray* Response_array = [json objectForKey:@"loans"];
NSLog(@"Array: %@", Response_array);
// Set Response_array to textview.
self.txt_webservice_response.text = [NSString stringWithFormat:@"%@"
,Response_array];
}
A: How about NSJSONSerialization? I've been using it to parse JSON
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: auto foo = ref new Foo(); What is "ref"? I was watching a video from, //build/ and several of the MS developers were using a syntax like this in their C++11 programs:
auto foo = ref new Foo();
I understand what everything does in this line except "ref". What does that mean?
A: "ref new" is a 2 token keyword. It instructs the compiler to instantiate a windows runtime object and automatically manage the lifetime of the object (via the "^" operator).
Instantiating a windows runtime object causes an allocation, but it does not have to be on the heap.
A: ref in this case stands for reference counting. Classes using ref are WinRT component which have reference count machanisms out of the box.
A: The forthcoming Visual C++ compiler adds this syntax for dealing with WinRT objects (which are in turn the next generation of COM, what have we gone through now? COM, DCOM, COM+, ActiveX, ...)
That line is nearly equivalent to:
com_ptr_t<Foo> foo = CreateInstance<Foo>();
But there's a new version of com_ptr_t as well, using the syntax Foo^.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: HTTP Error 500.19 - Internal Server Error in BlogEngine.NET I'm trying to install BlogEngine.NET in my Hosted Plan at arvixe.com
I get this error when I try to navigate to the Blog :
The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration
53: </system.serviceModel>
54: <system.web.extensions>
55: <scripting>
And here is my web.config file.
There is some articles on internet about get this fixed but the problem is :
1- I'm using the blog in a Hosted plan
2- I don't have access to the IIS configuration with Arvixe.
Do you think I can fixe this just by changing the web.config file ?
A: You need to tell your host to change the framework version your AppPool is tied to. Its probably tied to 2.0 which doesn't recognize system.web.extensions. It needs to be changed to 4.0
More info here and here
A: A couple of things to try:
If the OS is 64bit, try to recompile your application in Any to have it run as a 64bit application. Or change the Application Pool to enable 32bit applications.
A: A couple of things to try:
If the OS is 64bit, try to recompile your application in Any to have it run as a 64bit application. Or change the Application Pool to enable 32bit applications.
If that doesn't help, perhaps the web.config section is locked down, and you will then have to ask your hosting company to allow the section.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: query avoding subselect I have this query and it's very slow. Can i write this query in other way by avoiding subselects for example?
Also i tried adding composite index on
MyIndex(kategorije_id,izdvojen,izdvojen_kad,datum)
but it doesent use it when i explain this query so is there another index that i can use to speed up this query?
SELECT artikli.datum AS brojx, artikli.izdvojen AS i, artikli.izdvojen_kad AS ii, artikli.name
FROM artikli
WHERE artikli.izbrisan =0
AND artikli.prodano !=3
AND artikli.zavrseno =0
AND artikli.od_id !=0
AND kategorije_id
IN ( 18 )
AND (
SELECT count( * )
FROM artikli_polja, polja
WHERE polja.id_kat = artikli.kategorije_id
AND artikli_polja.id_polja = polja.id
AND artikli_polja.id_artikal = artikli.id
AND polja.name = "godiste"
AND artikli_polja.valueInt >= "1993"
) >0
AND (
SELECT count( * )
FROM artikli_polja, polja
WHERE polja.id_kat = artikli.kategorije_id
AND artikli_polja.id_polja = polja.id
AND artikli_polja.id_artikal = artikli.id
AND polja.name = "godiste"
AND artikli_polja.valueInt <= "2000"
) >0
ORDER BY i DESC , ii DESC , brojx DESC
LIMIT 140 , 35
A: Try this query -
SELECT a.datum AS brojx, a.izdvojen AS i, a.izdvojen_kad AS ii, a.name FROM artikli a
JOIN artikli_polja ap
ON ap.id_artikal = a.id
JOIN polja p
ON ap.id_polja = p.id AND p.id_kat = a.kategorije_id
WHERE
a.izbrisan =0
AND a.prodano !=3
AND a.zavrseno =0
AND a.od_id !=0
AND kategorije_id = 18
AND p.name = 'godiste'
AND ap.valueInt >= 1993 AND ap.valueInt <= 2000;
I have removed ORDER BY and LIMIT clauses from the query; try to work out this query firstly.
A: Try this query:
SELECT a.datum AS brojx, a.izdvojen AS i, a.izdvojen_kad AS ii, a.name
FROM artikli a
WHERE a.izbrisan =0
AND a.prodano !=3
AND a.zavrseno =0
AND a.od_id !=0
AND a.kategorije_id = 18
AND EXISTS
(select 'X'
from artikli_polja ap,
JOIN polja p
ON ap.id_polja = p.id AND p.id_kat = a.kategorije_id
AND ap.id_artikal = a.id
AND p.name = 'godiste'
AND ap.valueInt >= 1993 AND ap.valueInt <= 2000
);
Please check.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting input for character arrays I was coding a program to find the longest common sub-sequence today and I was getting the elements of the each sequence into a character array. but I ran into a little problem. I used a for loop to get the elements but not matter how high I set the number of iterations the loop should execute it always terminated after 5 iterations. The array into which the data was being input was an array of size 10 so there were no issues with the array size. I coded a small test program to check and even in the test program the for loops that get data for a character array always terminate after 5 iterations . Why ?( I am forced to use turbo c++ in my lab)
#include<stdio.h>
void main()
{
int i;
char s[10];
for(i=0;i<10;i++)
scanf("%c",&a[i]);
}
The above code was the test program.for loop terminated after 5 iterations here too !
A: Newline characters ('\n') are characters too. If you type H, <return>, e, <return>, l, <return>, l, <return>, o, <return>, they you've entered 10 characters.
A: It's a much better idea to just read the entire "array" as a single string, all at once:
char s[10];
fgets(s, sizeof s, stdin);
A: Let me guess, you're pressing return after each character? The scanf() call will read those too...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery Mobile: Getting a cancelled Postback that's causing a page load error So, I've been trying to get this page working for a couple of days now, when I clicked the send button it would work, but if you tried to hit enter it would just do a postback to the same page. Yesterday I thought I finally got it so it would work on chrome (it has been working just fine on firefox, but breaking on chrome/safari and it is an app for the iphone). But, even though I finally got it so it would change pages, it is now displaying an error. I narrowed down the cause to a postback that is being called right before the postback I want is being sent which is then cancelled. I assume the cancelled postback is blank because the problem I was having was the page would do a blank postback.
I 'fixed' the problem by adding
javascript:if (event.keyCode == 13) __doPostBack('" & btnSearch.UniqueID & "','')
to the onKeyPress for txtSearch. The ending html for the asp:LinkButton and asp:TextBox (which is enclosed in an asp:Panel, inside an asp:Content for a master page which is inside a form, may or may not be relevant) is
<input name="ctl00$contentMain$txtSearch" id="contentMain_txtSearch" type="text" data-type="search" onkeypress="javascript:if (event.keyCode == 13) __doPostBack('ctl00$contentMain$btnSearchByIDName','')" class="...">
<a id="contentMain_btnSearch" class="..." data-role="button" onclientclick="return false;" href="javascript:__doPostBack('ctl00$contentMain$btnSearch','')" data-theme="c"><span class="..."><span class="...">Search</span></span></a>
There is an on button click event in the code behind.
This is the header from the post, the response and everything else is empty.
Accept:text/html, */*; q=0.01
Content-Type:application/x-www-form-urlencoded
Origin:Local.Website
Referer:Local.Website/EmployeePhoneList/PhoneList.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1
X-Requested-With:XMLHttpRequest
Anyone have any ideas how to figure out why it is doing two postbacks? Or how I could determine what is causing it? Thanks for any help.
Update: Looking further into the response, btnSearch is the origin for both the incorrect and correct postbacks. Also, things that HAVE NOT worked, AutoPostBack="false", CauseValidation="false", ViewStateMode="Disabled" and UseSubmitBehavior="false".
A: Have you tried disabling jQuery Mobile's Ajax navigation? Here's how I did it in an MVC project, should be similar in WebForms:
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")"></script>
<script type="text/javascript">
$(document).bind("mobileinit", function() {
$.mobile.ajaxEnabled = false;
});
</script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.mobile-1.0b2.min.js")"></script>
A: While fixing an seemingly unrelated problem on another page we accidentally fixed the problem. Turns out even with ajaxEnabled = false, you sometimes need to put data-ajax="false" in the form of the masterpage to make asp.net code work correctly with JQuery mobile. Either that or rc1 fixed the problem, I don't know for sure and at this point I don't really care anymore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: HandlerThread should i override run()? I'm trying to use the HandlerThread class to manage thread in my application. The following code is working great :
public class ThreadA extends HandlerThread
{
private void foo()
{
//do something
}
private void bar()
{
//Do something else
}
@Override
public boolean handleMessage(Message msg) {
switch(msg.what)
{
case 1:
{
this.foo();
break;
}
case 2:
{
this.bar();
break;
}
}
return false;
}
@Override
protected void onLooperPrepared()
{
super.onLooperPrepared();
synchronized (this) {
this.AHandler = new Handler(getLooper(),this);
notifyAll();
}
}
}
1- Should i override the run() method ? In a "classic" thread most of the code is located in the run method.
2- Lets imagine i need my foo() method to be a infinite process (getting a video streaming for example).
What's the best solution ?
*
*Overriding run with my foo() code ?
*Simply adding a sleep(xxx) in foo() :
private void foo()
{
//do something
sleep(100);
foo();
}
-Using a delayed message like :
private void foo()
{
//do something
handler.sendEmptyMessageDelayed(1,100);
}
PS : Asynctask will not cover my need , so do not bother to tell me to use it.
Thanks
A: I think you didn't get the idea of HandlerThread. HandlerThread is designed to implement thread that handles messages. What this means is that it uses Looper.loop() in its run() method (and that's why you shouldn't override it). This in turn means that you don't need to sleep in onHandleMessage() in order to prevent thread from exiting, as Looper.loop() already takes care of this.
To summarize:
*
*No, do not override run().
*You don't need to do anything to keep thread alive.
If you want to learn/undestand more about HandlerThread, read about Looper and Handler classes.
A: You shouldn't override the run method in the HandlerThread since that is where the core functionality of the class actually occurs. Based on what you are showing, I also see no reason to do so.
If your task itself is infinite, there isn't anything preventing you from having it execute that way. The only reason you might want to use handler.sendEmptyMessageDelayed is if you plan to have other tasks that you want run queued on the HandlerThread while foo() is executing. The other approach you recommended will prevent the HandlerThread from handling any other message. That being said, I suspect there is a better way to make your task infinite.
Finally, you should remember to stop your infinite task and call HandlerThread.getLooper().quit() to make sure your HandlerThread stops nicely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PlotLegends` default options I'm trying to redefine an option of the PlotLegends package after having loaded it,
but I get for example
Needs["PlotLegends`"]
SetOptions[ListPlot,LegendPosition->{0,0.5}]
=> SetOptions::optnf: LegendPosition is not a known option for ListPlot.
I expect such a thing as the options in the PlotLegends package aren't built-in to Plot and ListPlot.
Is there a way to redefine the default options of the PlotLegends package?
A: The problem is not really in the defaults for PlotLegends`. To see it, you should inspect the ListPlot implementation:
In[28]:= Needs["PlotLegends`"]
In[50]:= DownValues[ListPlot]
Out[50]=
{HoldPattern[ListPlot[PlotLegends`Private`a:PatternSequence[___,
Except[_?OptionQ]]|PatternSequence[],PlotLegends`Private`opts__?OptionQ]]:>
PlotLegends`Private`legendListPlot[ListPlot,PlotLegends`Private`a,
PlotLegend/.Flatten[{PlotLegends`Private`opts}],PlotLegends`Private`opts]
/;!FreeQ[Flatten[{PlotLegends`Private`opts}],PlotLegend]}
What you see from here is that options must be passed explicitly for it to work, and moreover, PlotLegend option must be present.
One way to achieve what you want is to use my option configuration manager, which imitates global options by passing local ones. Here is a version where option-filtering is made optional:
ClearAll[setOptionConfiguration, getOptionConfiguration, withOptionConfiguration];
SetAttributes[withOptionConfiguration, HoldFirst];
Module[{optionConfiguration}, optionConfiguration[_][_] = {};
setOptionConfiguration[f_, tag_, {opts___?OptionQ}, filterQ : (True | False) : True] :=
optionConfiguration[f][tag] =
If[filterQ, FilterRules[{opts}, Options[f]], {opts}];
getOptionConfiguration[f_, tag_] := optionConfiguration[f][tag];
withOptionConfiguration[f_[args___], tag_] :=
f[args, Sequence @@ optionConfiguration[f][tag]];
];
To use this, first define your configuration and a short-cut macro, as follows:
setOptionConfiguration[ListPlot,"myConfig", {LegendPosition -> {0.8, -0.8}}, False];
withMyConfig = Function[code, withOptionConfiguration[code, "myConfig"], HoldAll];
Now, here you go:
withMyConfig[
ListPlot[{#, Sin[#]} & /@ Range[0, 2 Pi, 0.1], PlotLegend -> {"sine"}]
]
A: LegendsPosition works in ListPlot without problems (for me at least). You don't happen to have forgotten to load the package by using Needs["PlotLegends"]`?
A: @Leonid, I added the possibility to setOptionConfiguration to set default options to f without having to use a short-cut macro.
I use the trick exposed by Alexey Popkov in What is in your Mathematica tool bag?
Example:
Needs["PlotLegends`"];
setOptionConfiguration[ListPlot, "myConfig", {LegendPosition -> {0.8, -0.8}},SetAsDefault -> True]
ListPlot[{#, Sin[#]} & /@ Range[0, 2 Pi, 0.1], PlotLegend -> {"sine"}]
Here is the implementation
Options[setOptionConfiguration] = {FilterQ -> False, SetAsDefault -> False};
setOptionConfiguration[f_, tag_, {opts___?OptionQ}, OptionsPattern[]] :=
Module[{protectedFunction},
optionConfiguration[f][tag] =
If[OptionValue@FilterQ, FilterRules[{opts},
Options[f]]
,
{opts}
];
If[OptionValue@SetAsDefault,
If[(protectedFunction = MemberQ[Attributes[f], Protected]),
Unprotect[f];
];
DownValues[f] =
Union[
{
(*I want this new rule to be the first in the DownValues of f*)
HoldPattern[f[args___]] :>
Block[{$inF = True},
withOptionConfiguration[f[args], tag]
] /; ! TrueQ[$inF]
}
,
DownValues[f]
];
If[protectedFunction,
Protect[f];
];
];
];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Creating dynamic XSL-FO table using XSLT I am creating a table in xsl-fo, with undefined number of elements (indtr).
I wonder if there a smart way to do this?
Here is my input xml file
<pr-levels>
<prs>
<pr_nme><![CDATA[Level 1]]></pr_nme>
<nt><![CDATA[standards:]]></nt>
<b_is>
<indtr id="5684"><![CDATA[cell_1]]></indtr>
<indtr id="5684"><![CDATA[cell_2]]></indtr>
<indtr id="5684"><![CDATA[cell_3]]></indtr>
<indtr id="5684"><![CDATA[cell_4]]></indtr>
</b_is>
</prs>
<prs>
<pr_nme><![CDATA[Level 2]]></pr_nme>
<nt><![CDATA[standards:]]></nt>
<b_is>
<indtr id="5684"><![CDATA[cell_1]]></indtr>
</b_is>
</prs>
<prs>
<pr_nme><![CDATA[Level 3]]></pr_nme>
<nt><![CDATA[standards:]]></nt>
<b_is>
<indtr id="5684"><![CDATA[cell_1]]></indtr>
<indtr id="5684"><![CDATA[cell_2]]></indtr>
</b_is>
</prs>
<prs>
<pr_nme><![CDATA[Level 4]]></pr_nme>
<nt><![CDATA[standards:]]></nt>
<b_is>
<indtr id="5684"><![CDATA[cell_1]]></indtr>
<indtr id="5684"><![CDATA[cell_2]></indtr>
<indtr id="5684"><![CDATA[cell_3]]></indtr>
<indtr id="5684"><![CDATA[cell_4]></indtr>
<indtr id="5684"><![CDATA[cell_5]]></indtr>
<indtr id="5684"><![CDATA[cell_6]]></indtr>
<indtr id="5684"><![CDATA[cell_7]]></indtr>
</b_is>
</prs>
<prs>
<pr_nme><![CDATA[Level 5]]></pr_nme>
<nt><![CDATA[standards:]]></nt>
<b_is>
<indtr id="5684"><![CDATA[cell_1]]></indtr>
<indtr id="5684"><![CDATA[cell_2]]></indtr>
<indtr id="5684"><![CDATA[cell_3]]></indtr>
<indtr id="5684"><![CDATA[cell_4]]></indtr>
<indtr id="5684"><![CDATA[cell_5]]></indtr>
<indtr id="5684"><![CDATA[cell_6]]></indtr>
<indtr id="5684"><![CDATA[cell_7]]></indtr>
<indtr id="5684"><![CDATA[cell_8]]></indtr>
<indtr id="5684"><![CDATA[cell_9]]></indtr>
<indtr id="5684"><![CDATA[cell_10]]></indtr>
<indtr id="5684"><![CDATA[cell_11]]></indtr>
<indtr id="5684"><![CDATA[cell_12]]></indtr>
<indtr id="5684"><![CDATA[cell_13]]></indtr>
<indtr id="5684"><![CDATA[cell_14]]></indtr>
<indtr id="5684"><![CDATA[cell_15]]></indtr>
<indtr id="5684"><![CDATA[cell_16]]></indtr>
<indtr id="5684"><![CDATA[cell_17]]></indtr>
<indtr id="5684"><![CDATA[cell_18]]></indtr>
<indtr id="5684"><![CDATA[cell_19]]></indtr>
</b_is>
</prs>
</pr-levels>
Here is my XSLT template that produces the XSL-FO table:
<xsl:template match="pr-levels">
<fo:table xsl:use-attribute-sets="table_p" break-after="page" force-page-count="no-force">
<fo:table-column column-number="1" xsl:use-attribute-sets="table_col_p"/>
<fo:table-column column-number="2" xsl:use-attribute-sets="table_col_p"/>
<fo:table-column column-number="3" xsl:use-attribute-sets="table_col_p"/>
<fo:table-column column-number="4" xsl:use-attribute-sets="table_col_p"/>
<fo:table-column column-number="5" xsl:use-attribute-sets="table_col_p"/>
<fo:table-header xsl:use-attribute-sets="table_header">
<xsl:for-each select="prs/pr_nme">
<fo:table-cell>
<fo:block>
<xsl:apply-templates/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-header>
<fo:table-body >
<fo:table-row>
<xsl:for-each select="prs/nt">
<fo:table-cell>
<fo:block xsl:use-attribute-sets="nt" >
<xsl:apply-templates/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-row>
<fo:table-row>
<xsl:for-each select="prs/b_is">
<fo:table-cell padding="1pt">
<fo:block>
<xsl:value-of select="indtr[1]"/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-row>
<fo:table-row>
<xsl:for-each select="prs/b_is">
<fo:table-cell padding="1pt">
<fo:block>
<xsl:value-of select="indtr[2]"/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-row>
<fo:table-row>
<xsl:for-each select="prs/b_is">
<fo:table-cell padding="1pt">
<fo:block>
<xsl:value-of select="indtr[3]"/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-row>
<fo:table-row>
<xsl:for-each select="prs/b_is">
<fo:table-cell padding="1pt">
<fo:block>
<xsl:value-of select="indtr[4]"/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-row>
<fo:table-row>
<xsl:for-each select="prs/b_is">
<fo:table-cell padding="1pt">
<fo:block>
<xsl:value-of select="indtr[5]"/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-row>
</fo:table-body>
</fo:table>
</xsl:template>
There could be NULL,1,69 or whatever numbers of <indtr>s in a <b_is>,but right now I just hard code the numbers.My question is how I can dynamically count the number of indtrs and add rows in my table.maybe a for loop in xsl?
________________________________________________________
| level 1 | level 2 | level 3 | level 4 | level 5 |
--------------------------------------------------------
|standards:|standards:|standards:|standards:|standards:|
--------------------------------------------------------
| cell 1 | cell 1 | cell 1 | cell 1 | cell 1 |
--------------------------------------------------------
| cell 2 | cell 2 | cell 2 | cell 2 | cell 2 |
--------------------------------------------------------
| | cell 3 | cell 3 | cell 3 | cell 3 |
--------------------------------------------------------
| | cell 4 | | | cell 4 |
--------------------------------------------------------
| | | | | cell 5 |
--------------------------------------------------------
| | | | | cell 6 |
--------------------------------------------------------
A: Just because it's an interesting problem...
Replace the multiple hard-coded fo:table-row with:
<xsl:variable name="pr-levels" select="." />
<xsl:for-each
select="1 to max(for $prs in prs
return count($prs/b_is/indtr))">
<xsl:variable name="row" select="." as="xs:integer" />
<fo:table-row>
<xsl:for-each select="$pr-levels/prs">
<fo:table-cell padding="1pt">
<fo:block>
<xsl:value-of select="b_is/indtr[$row]"/>
</fo:block>
</fo:table-cell>
</xsl:for-each>
</fo:table-row>
</xsl:for-each>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery parsing json This is the JSON output that I currently have:
[{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
I want the output to be
[{"label": "Eli", "value": "1"}]
how can I take the values of pk and eng_name from the JSON data and output it like above?
A: You can use jQuery.map:
var data = [{"pk": 1, "model": "system.employees",
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}];
var new = $.map(data, function(index, item) {
return { label: item.fields.eng_name, value: item.pk };
});
A: var result = [{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
var output = [{ "label" : result[0].fields.eng_name, "value": result[0].pk}]
A: //assuming your source obj is called 'source'
var num = source[0].pk;
var eng_name = source[0].fields.eng_name;
...then you can do whatever with them, like
var output = [];
output.push({"label":eng_name, "value":num});
Good luck!
A: Try -
var h = JSON.parse('[{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]');
var a = [];
a.push({"label": h[0].fields.eng_name, "value": h[0].pk+''})
alert(JSON.stringify(a))
NB You'll need to import this code - https://github.com/douglascrockford/JSON-js/blob/master/json2.js if your browser doesn't support JSON.parse and JSON.stringify
Demo - http://jsfiddle.net/ipr101/uwZVW/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Print DIV content by JQuery suppose i have many div's in my page but i want to print the content of specific div using jquery. i found there is a plugin for that.
jQuery Print Element
using this plugin we can easily print div content like below.
$('SelectorToPrint').printElement();
but what happen if my div is hidden in page. so then does it work. this plugin can print the content of hidden div?
what happen if printer is not attach with client machine. i want to show message if printer is not there to customer that "Printer not found"? how to handle this situation. so please advise me what would be the best approach to print the content of hidden div in page and as well as handle printer issue if printer is not attached.
thanks
A: I prefer this one, I have tested it and its working
https://github.com/jasonday/printThis
$("#mySelector").printThis();
or
$("#mySelector").printThis({
* debug: false, * show the iframe for debugging
* importCSS: true, * import page CSS
* printContainer: true, * grab outer container as well as the contents of the selector
* loadCSS: "path/to/my.css", * path to additional css file
* pageTitle: "", * add title to print page
* removeInline: false * remove all inline styles from print elements
* });
A: If a hidden div can't be printed with that one line:
$('SelectorToPrint').printElement();
simply change it to:
$('SelectorToPrint').show().printElement();
which should make it work in all cases.
for the rest, there's no solution. the plugin will open the print-dialog for you where the user has to choose his printer. you simply can't find out if a printer is attached with javascript (and you (almost) can't print without print-dialog - if you're thinking about that).
NOTE:
The $.browser object has been removed in version 1.9.x of jQuery
making this library unsupported.
A: try this jquery library, jQuery Print Element
http://projects.erikzaadi.com/jQueryPlugins/jQuery.printElement/
A: Here is a JQuery&JavaScript solutions to print div as it styles(with internal and external css)
$(document).ready(function() {
$("#btnPrint").live("click", function () {//$btnPrint is button which will trigger print
var divContents = $(".order_summery").html();//div which have to print
var printWindow = window.open('', '', 'height=700,width=900');
printWindow.document.write('<html><head><title></title>');
printWindow.document.write('<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" >');//external styles
printWindow.document.write('<link rel="stylesheet" href="/css/custom.css" type="text/css"/>');
printWindow.document.write('</head><body>');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.onload=function(){
printWindow.focus();
printWindow.print();
printWindow.close();
}
});
});
This will print your div in new window.
Button to trigger event
<input type="button" id="btnPrint" value="Print This">
A: There is a way to use this with a hidden div but you have to work abit more with the printElement() function and css.
Css:
#SelectorToPrint{
display: none;
}
Script:
$("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}})
This will override the display: none in the new window you open and the content will be displayed on the print-preview page and the div on you site remains hidden.
A: You can follow these steps :
*
*wrap the div you want to print into another div.
*set the wrapper div display status to none in css.
*keep the div you want to print display status as block, anyway it will be hidden as its parent is hidden.
*simply call $('SelectorToPrint').printElement();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to call a method n times in Scala? I have a case where I want to call a method n times, where n is an Int. Is there a good way to do this in a "functional" way in Scala?
case class Event(name: String, quantity: Int, value: Option[BigDecimal])
// a list of events
val lst = List(
Event("supply", 3, Some(new java.math.BigDecimal("39.00"))),
Event("sale", 1, None),
Event("supply", 1, Some(new java.math.BigDecimal("41.00")))
)
// a mutable queue
val queue = new scala.collection.mutable.Queue[BigDecimal]
lst.map { event =>
event.name match {
case "supply" => // call queue.enqueue(event.value) event.quantity times
case "sale" => // call queue.dequeue() event.quantity times
}
}
I think a closure is a good solution for this, but I can't get it working. I have also tried with a for-loop, but it's not a beautiful functional solution.
A: With recursion:
def repeat(n: Int)(f: => Unit) {
if (n > 0) {
f
repeat(n-1)(f)
}
}
repeat(event.quantity) { queue.enqueue(event.value) }
A: The simplest solution is to use range, I think:
(1 to n) foreach (x => /* do something */)
But you can also create this small helper function:
implicit def intTimes(i: Int) = new {
def times(fn: => Unit) = (1 to i) foreach (x => fn)
}
10 times println("hello")
this code will print "hello" 10 times. Implicit conversion intTimes makes method times available on all ints. So in your case it should look like this:
event.quantity times queue.enqueue(event.value)
event.quantity times queue.dequeue()
A: Not quite an answer to your question, but if you had an endomorphism (i.e. a transformation A => A), then using scalaz you could use the natural monoid for Endo[A]
N times func apply target
So that:
scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._
scala> Endo((_:Int) * 2).multiply(5)
res3: scalaz.Endo[Int] = Endo(<function1>)
scala> res1(3)
res4: Int = 96
A: A more functional solution would be to use a fold with an immutable queue and Queue's fill and drop methods:
val queue = lst.foldLeft(Queue.empty[Option[BigDecimal]]) { (q, e) =>
e.name match {
case "supply" => q ++ Queue.fill(e.quantity)(e.value)
case "sale" => q.drop(e.quantity)
}
}
Or even better, capture your "supply"/"sale" distinction in subclasses of Event and avoid the awkward Option[BigDecimal] business:
sealed trait Event { def quantity: Int }
case class Supply(quantity: Int, value: BigDecimal) extends Event
case class Sale(quantity: Int) extends Event
val lst = List(
Supply(3, BigDecimal("39.00")),
Sale(1),
Supply(1, BigDecimal("41.00"))
)
val queue = lst.foldLeft(Queue.empty[BigDecimal]) { (q, e) => e match {
case Sale(quantity) => q.drop(quantity)
case Supply(quantity, value) => q ++ Queue.fill(quantity)(value)
}}
This doesn't directly answer your question (how to call a function a specified number of times), but it's definitely more idiomatic.
A: import List._
fill(10) { println("hello") }
Simple, built-in, and you get a List of Units as a souvenier!
But you'll never need to call a function multiple times if you're programming functionally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Instruments says I'm leaking a string, but I can't find it I used the leaks tool in Instruments to test the code, but the leaks tool cannot seem to find the leak.
At the end of my code, the output of NSLog(@"str count:%d",[str retainCount]); is 3. Why? I don't override the dealloc. [a.name retainCount] is there just one time
and I only autorelease str for one time. So str shouldn't leak.
@interface DataMode : NSObject {
NSString * name;
}
@property (retain) NSString * name;
- initWithName:(NSString * )name_;
@end
@implementation DataMode
@synthesize name;
- initWithName:(NSString * )name_
{
if ([super init] != nil)
{
name = name_;
return self;
}
return nil;
}
@end
- (void) pressed:(id)sender
{
for( int i = 0;i<10000000;i++)
{
NSString * str = [NSString stringWithFormat:@"zhang"];
DataMode * a = [[DataMode alloc] initWithName:str];
NSLog(@"a0 count:%d",[a retainCount]);
NSLog(@"name1 count:%d",[a.name retainCount]);
NSLog(@"name1 count:%d",[a.name retainCount]);
NSLog(@"a1 count:%d",[a retainCount]);
[ a release];
NSLog(@"str count:%d",[str retainCount]);
NSLog(@"str count:%d",[str retainCount]);
}
}
@end
A: retainCount is useless. Don't call it.
It is not useful for finding leaks as there are much better, more accurate, and less misleading tools available.
There are several problems with your code (but leaking isn't one of them):
*
*NSString* properties should be copy
*you don't use the property to set the string value in init, thus the DataMode instances are not retaining their strings.
*there is no dealloc method
As for the retain counts; I'm surprised it is "3". I'd expect it to be 2bazillionsomething as that is a constant string (and stringWithString: of a constant string just returns the string).Since you used stringWithFormat:, the constant string is turned into a non-constant string. If you had used the constant string or stringWithString:, it'd be abazillionsomething (unsigned -1... UINT_MAX...).
In any case, you have:
*
*+1 for stringWithString:
*+1 for calling a.name
*+1 for calling a.name
+3 overall.
If Instruments is claiming a leak, post a screenshot.
A: I quote the NSObject protocol reference for -retainCount:
This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.
The retain count could be 3 for any number of reasons; if you can't find a leak with the leaks tool, it's likely you don't have a leak. Don't worry about the actual value of the retain count.
If you're really interested in why it's 3, recall that:
*
*The reference from your DataMode object a will likely be held until the closest autorelease pool is drained
*You're still holding a reference in the str variable
*The NSString class cluster, among others, does some - unusually inexplicable - caching things internally, so you may see a few retains here and there for which nobody can account
A: Since you are using the convenience method to create str which is autoreleased you will not see determinate behavior using retain counts in this way.
Check my response to another question and add those methods to DataMode and you should see when the framework releases your objects from the autorelease pool.
Overriding release and retain in your class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does $_POST have a size limit?
Possible Duplicate:
What is the size limit of a post request?
Does $_POST when used in conjunction with forms in PHP have a size limit? Obviously there must be some restrictions with $_GET seeing as most browsers will start to complain at ~250 characters (or something like that) and data could be lost, obviously this restraint doesn't apply to $_POST.
I could test it myself but thought it might be quicker to simply ask here. If I had a simple form with a textarea, how much data could I enter before I ran into problems?
A: Yes it has limitation, you can set the limit from several place:
1., in php.ini
post_max_size="8M"
2., from the .htaccess file, if you have
php_value post_max_size 8M
3., from php side,
ini_set('post_max_size',"8M")
A: yes,
you can change limit from php.ini "post_max_size"
A: That depends on the value of the PHP configuration directive POST_MAX_SIZE which is usually set to 8 MB (~8 million characters).
A: It's a PHP ini directive, post_max_size. It defaults to 8MB.
A: Yes. It's defined in the php.ini file.
A: Yes the POST data is regulated by the post_max_size variable (default to 8M)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Getting information if Topmost property is changed I have a class, deriving from Window, in which I want to be notified when the Topmost property is changed.
I tried to override setter, but it's not marked as virtual. Changing metadata connected with this property made it not working (nothing happens after setting topmost true). Also WPF does not provide event connected with this property. I was thinking about overriding Topmost property, but I use it to data binding, so it must stay DependencyProperty.
Is there any way to get that notification?
A: I try this and it seems like it work fine for me.
public partial class MainWindow : Window
{
static MainWindow()
{
Window.TopmostProperty.OverrideMetadata(typeof(MainWindow),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(OnTopMostChanged)));
}
public event EventHandler TopmostChanged;
private static void OnTopMostChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
MainWindow mv = (MainWindow)d;
if (mv.TopmostChanged != null)
mv.TopmostChanged(mv, EventArgs.Empty);
}
private void ChangeTopmostBtn_Click(object sender, RoutedEventArgs e)
{
this.Topmost = !this.Topmost;
}
...
}
When i click on my ChangeTopmost button, i get inside OnTopMostChanged method. So if you do the same and have anyone registered to TopmostChanged event, it will get the event.
A: You could create your own MyTopmostDependencyProperty with a PropertyChangedCallback where you can raise your notification event and bind it to the original TopmostDependencyProperty.
public static readonly DependencyProperty MyTopmostProperty =
DependencyProperty.Register("MyTopmost",
typeof(bool),
typeof(MyWindow),
new FrameworkPropertyMetadata {
PropertyChangedCallback = new PropertyChangedCallback(OnMyTopmostChanged)
}
);
A: Try to implement the NotifyPropertyChanged interface. You can read more about this interface on MSDN. (How to: Implement Property Change Notification)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MSBUILD error where folder contains more than one solution file I'm trying to set up CCNET and I've run into a problem.
My builds are failing and I'm getting this error
MSBUILD : error MSB1011: Specify which project or solution file to use because this folder contains more than one project or solution file.
In my configuration file ccnet.config my msbuild block is as follows
<msbuild>
<executable>C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe</executable>
<workingDirectory>C:\example\directory</workingDirectory>
<projectFile>ExampleSolution.sln</projectFile>
<buildArgs>/noconsolelogger /v:quiet
/p:Configuration=Debug
/p:ReferencePath="C:\Program Files (x86)\NUnit 2.5.10\bin\net-2.0\"
</buildArgs>
<targets>ReBuild</targets>
<timeout>600</timeout>
</msbuild>
In this case, C:\example\directory has multiple solution files. Even though I specified the project file I'm still getting that error.
A: You should specify what to build in the sln group.
msbuild SlnFolders.sln /t:NotInSolutionfolder:Rebuild;NewFolder\InSolutionFolder:Clean
So in CC.NET, add the /t parameter in the <buildArgs> tag.
Reference : http://msdn.microsoft.com/en-us/library/ms164311.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Where to put images that are called by css file in Django? I have downloaded a template online that includes a base html file, images and a css file. Now I would like to implement all this in django.
So far I tried like this but with no good results, the page gets rendered without css file or without images, or both... well something is wrong
settings.py:
MEDIA_ROOT = rel('resources')
MEDIA_URL = '/resources/'
base.html:
<link rel="stylesheet" type="text/css" href="resources/style.css" />
I have put my images and the css file in the resources folder and the templates folder and it doesnt work, please help
A: EDIT:
I was slightly off there... STATIC_ROOT refers to the directory where Django will collect all static files. STATICFILES_DIRS is a list of searchpaths for static files. So like this:
settings.py:
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = PROJECT_ROOT + 'static/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"C:/www/django/static",
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
and add the url to urls.py:
urlpatterns += staticfiles_urlpatterns()
ORIGINAL ANSWER:
This can be quite confusing.
The MEDIA_ROOT directory is for files uploaded via a file-upload form. For physical files that are directly accessible by client request (e.g style sheets, scripts and images) you have to use the STATIC_ROOT and STATIC_URL. STATIC_ROOT must be an absolute path i think.
settings.py
# the url: myserver.com/static/
STATIC_URL = '/static/'
# refers to this directory:
STATIC_ROOT = '/home/user/static server files'
let's say you put your css in "/home/user/static server files/css/" then refer to them like this:
base.html
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" />
A: Assuming you are working on a development server for now .
MEDIA_URL = 'http://localhost/media/'
calculated paths for django and the site
used as starting points for various other paths
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
PROJECT_ROOT = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates/'),
)
MEDIA_ROOT = os.path.join(SITE_ROOT, 'templates/media/')
The above should solve your problem as iot worked for me just fine.
While referring css files which are kept in "templates/media"
<link href="/media/css/base/base.css" rel="stylesheet" type="text/css"></link>
Hope this helps you out
A: hmm unfortunately this did not help. I could not find a variable STATIC_URL/ROOT in settings.py, so I added it as described above, also added the variable in base.html, but rendering still cannot find css file.
Another this I did is investigated code that works. I got a piece of good public application's source code and inspected base.html, and it says like this:
<link rel="stylesheet" href="{{ cssRootUrl }}style.css"
then I went to check the settings.py and cssRootUrl was not defined there. So I have no idea where else could this kind of variable hide...
A: this can solve your problem. I suggest you name your folder "static" for static files that you are using (css, js and images).
*
*open your settings.py and
-add this at the first line of your file:
import os.path
-change your STATIC_ROOT's value to:
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')
-change your STATIC_URL's value to:
STATIC_URL = '/static/'
*create a folder named "static" in your project root.
*create a folder for your static files like css, javascript and etc. I recommend you use a different folder for different types of files.
*open the urls.py of your project
-add this to your imports: import settings
-add this to the url patterns:
(r'(?:.*?/)?(?P(css|jquery|jscripts|images)/.+)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT }),
NOTE: In this example, there are folders named css, jquery, jscripts and images inside my static folder.
*In your template add this:
for css files: (in this example, default.css is the name of the css file)
<link href="/{{ STATIC_ROOT }}css/default.css" rel="stylesheet" type="text/css" media="all" />
for javascript:
<script type="text/javascript" src="/{{ STATIC_ROOT }}jquery/jquery.js"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NOLOCK with Linq to SQL without setting Transaction IsolationLevel Is there a way to use NOLOCK on a LIN2SQL single query without setting the Transaction IsolationLevel? I need to do this as the query part of a larger (distributed) transaction.
For example:
using (var txn = new TransactionScope())
{
// query1
// query2
// query3
}
I want the changes of query 1 and 3 to be transactional, but I need NOLOCK on query2, which happens to be on a separate db to the other queries. If I re-set the transaction scope for query2 to ReadUncommitted then I get the error:
The transaction specified for TransactionScope has a different IsolationLevel than the value requested for the scope.
Parameter name: transactionOptions.IsolationLevel
A: Will it work for you?
using (var txn = new TransactionScope())
{
// query1
using (TransactionScope txn2 =
new TransactionScope(TransactionScopeOption.RequiresNew),
new TransactionOptions() {//isolation level,timeout, etc}
)
{
// query2
}
// query3
}
A: How about making query2 a stored procedure, with nolock in the sql, and calling that from Linq2Sql?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there an equivalent to Django's reverse URL lookup in Java Struts framework? I want to find out whether there is a Struts equivalent to Django's reverse URL lookup, where you can associate names to URL patterns and refer to these in your code. This allows you to change the URLs easily, since all of them are defined at a single location (urls.py)
That is, a way to assign names to URL patterns, and then be able to generate a correct URL from the name and values for the replacement parameters.
https://docs.djangoproject.com/en/1.3/topics/http/urls/#reverse
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to set column default to SQL Server's NewId()? In fluentMigrator, is it possible to set a column default to a function?
Specifically, I'm adding a uniqueidentifier (Guid) column to a SQL Server 2008 table that already contains data, and it's going to be a required field - is it possible to set the default to the NewId() function?
A: Field defaults for NewId() and GetDate() are available (for SQL Server at least) by referring to either SystemMethods.NewGuid or SystemMethods.CurrentDateTime, for example:
Create
.Column("incomeIdGuid").OnTable("tblIncome")
.AsGuid()
.NotNullable()
.WithDefaultValue(SystemMethods.NewGuid);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: HTML placeholder does not work for Android I have a mobile version of my site and on the login page I use "placeholder" to display: Email or Password (instead of using label).
For iPhone it's working but not for Android, it disabled my field css (borders, colors etc...)
Edit:
I want to be able to use iPhone OS3, OS4 and Android 1 and 2
Why ?
A: Found it!
http://diveintohtml5.ep.io/forms.html
How to get rid of placeholder on password field taken over from label
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: ExtJS Replace Gridpanel Store Is there anyway to remotely override/replace a GridPanel's store?
I have a grid that has a dummy store as I get an error if I don't declare as store:
this.ds is undefined
When my form is submitted, it makes a GET REST call & loads a JSON store with the results. I want this store to be the store of my grid and show it underneath the formPanel.
I can get it to show & return JSON but can't seem to replace the store.
I tried using
searchGrid.store = formStore //the JSONStore returned from form submit
EDIT
This if the data store:
var formStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '...',
method: 'GET'
}),
root: 'Report',
fields:[
....]
});
This is the loading / changing of the store:
var data = this.getForm().getValues();
formStore.load({
params: {
fields: Ext.encode(data)
}
});
var grid = Ext.getCmp('search');
Ext.apply(grid, {store: formStore});
grid.show();
A: Try this
myGridPanel.getStore().proxy.setApi({read: url});
myGridPanel.getStore().load();
I'm using this solution when I want to read data from another url
A: grid.reconfigure(store, colModel);
Works fine for me. Is the formStore.data compatible with Grid's columns configuration? You don't need to specify the column model in the reconfigure call if it didn't change.
Show a slice of your formStore.data and grid configuration.
A: Have you tried Ext.apply()?
From the api:
apply( Object object, Object config, Object defaults ) : Object
EDIT:
Here's how you use it:
Ext.apply(myGrid, { store : mystore }); //no need for the third parameter, but if you do want a default, then you can use one
A: Should the root is inside reader? Like this
var formStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '...',
method: 'GET'
}),
reader: {
type: 'json',
root: 'Report'
},
fields:[
....]
});
A: I managed to solve this by moving the jsonStore to the grid itself and make it a singleton. Then reference to it from the form using StoreMgr
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android alert dialog query I have been working on android application and I have got stuck at a point.
I have a method which shows a progress dialog to the user. Then after the code has run I am showing an alert dialog.
Here I have got stuck. The progress dialog is not showing when method calls.
Code:
progressDialog = ProgressDialog.show(NameOfYourActivity.this, "", "Loading. Please wait...", true);
Thanks
A: put a title or try with null
progressDialog = ProgressDialog.show(NameOfYourActivity.this, "Title", "Loading. Please wait...", true);
progressDialog = ProgressDialog.show(NameOfYourActivity.this, null, "Loading. Please wait...", true);
A: What does the UI thread do next? Dialog showing code won't work until the UI thread returns from the current method - as in all GUI systems, window drawing logic is queued and invoked from the message loop. So if you show the dialog and then immediately start the loading, the dialog won't get a chance to show.
For one thing, doing lengthy loading in the UI thread is universally considered a bad design. I'd advise you to move the loading into either Thread or AsyncTask. But as a first step, you can insert a trip to the message loop between show() and the rest, like this:
ProgressDialog.show()
new Handler().post(new Runnable(){
public void run()
{
//Rest of the method
}});
A: this line just create the dialog object
progressDialog = ProgressDialog.show(NameOfYourActivity.this, "", "Loading. Please wait...", true);
after this call
progressDialog.show();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: os x alternative to Textmate (no Java or vim or xemacs) I am fed up with Textmate. It's great, but it's old and keeps crashing on me. No development in (what, 3+?) years, etc.
So I'm looking for a viable alternative. However, I don't want a bloated and slow editor that runs on Java (so NetBeans, Komodo, Eclipse, etc are out), nor something that includes the kitchen Sink (goodbye Coda, I already own Espresso but am extremely disappointed that after so long the new version doesn't include variable autocompletion, seriously Macrabbit!). Bbedit is a little too bare-bones for me.
In summary, as the title says, a Textmate replacement that is modern, stable and still in development. Mainly for PHP development. Does such a beast exist?
Thanks in advance.
A: Sublime Text 2?
I guess it's the best alternative for someone who used to use textmate, it has a lot of awesome features, once you get used to it you won't need to use anything else.
A: I hate to be "that guy", but I've been slowly teaching myself Vim, and… well it works I think. Give it another go if you haven't recently. Make it your mission to be awesome at Vim.
A: How about these:
*
*Smultron
*Kod
*Sublime Text X
*Chocolat (still in alpha beta, but great)
A: For what it's worth, TextMate 2 is in development.
A: I would recommend BBEdit (http://www.barebones.com/products/bbedit/) - the best I've seen on a mac. Have been using it for years. And it even has auto-complete for PHP.
A: TextWrangler!
Unlike BBEdit, which is like $50 (thats just a rediculous price for a text editor), TextWrangler is free!
A: Use Coda . It's not free but works great. I've been working with coda for over a year now and I think it's the best development tool.
A: Nusphere PhpED is the fastest php IDE I have work with but its not free .
A: I've moved to Vim one year ago. The steep learning curve is not a myth but not that hard to climb.
Also I second all Sublime Text 2 mentions. It's what TextMate should have been and probably more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Convert ASCII and UTF-8 to non-special characters with one function So I'm building a website that is using a database feed that was already set up and has been used by the client for all their other websites for quite some time.
They fill this database through an external program, and I have no way to change the way I get my data.
Now I have the following problem, sometimes I get strings in UTF-8 and sometimes in ASCII (I hope I've got these terms right, they're still a bit vague to me sometimes).
So I could get either this: Scénic or Scénic.
Now the problem is, I have to convert this to non-special characters (so it would become Scenic) for urls.
I don't think there's a function for converting é to e (if there is do tell) so I'll probably need to create an array for that containing all the source and destinations, but the bigger problem is converting é to é without breaking é when it comes through that function.
Or should I just create an array containing everything (so for example: array('é'=>'e','é'=>'e'); etc.
I know how to get é to é, by doing utf8_encode(html_entity_decode('é')), however putting é through this same function will return é.
Maybe I'm approaching this the wrong way, but in that case I'd love to know how I should approach it.
A: Thanks to @XzKto and this comment on PHP.net I changed my slug function to the following:
static function slug($input){
$string = html_entity_decode($input,ENT_COMPAT,"UTF-8");
$oldLocale = setlocale(LC_CTYPE, '0');
setlocale(LC_CTYPE, 'en_US.UTF-8');
$string = iconv("UTF-8","ASCII//TRANSLIT",$string);
setlocale(LC_CTYPE, $oldLocale);
return strtolower(preg_replace('/[^a-zA-Z0-9]+/','-',$string));
}
I feel like the setlocale part is a bit dirty but this works perfectly for translating special characters to their 'normal' equivalents.
Input a áñö ïß éèé returns a-ano-iss-eee
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: clearTimeout on multiple references I have a set of complex setTimeout() calls that trigger some jQuery animations.
I would like to be able to clear them all without knowing their various refs.
This code will not work - but should illustrate what I'm trying to do...
window.ref = [];
function doAnimation(i) {
$('div').each(function(index) {
window.ref.push(setTimeout('foo(index,i)',index*1000));
window.ref.push(setTimeout('bar(index,i)',index*2000));
});
}
Then clear them with
clearTimeout(window.ref);
A: I know this already has an accepted answer, but just because those timeout ids are worthless once you have cleared them, I would have cleared them by saying:
if (window.ref) while(window.ref.length > 0) clearTimeout(window.ref.pop());
A: thats not correct you should do like this:
window.ref = [];
function doAnimation(i) {
$('div').each(function(index) {
window.ref.push(setTimeout('foo(index,i)',index*1000));
window.ref.push(setTimeout('bar(index,i)',index*2000));
});
}
and then clear like :
for(var i=0;i<window.ref.length;i++){
clearTimeout(window.ref[i]);
}
A: if (window.ref && window.ref.length > 0) for (var i in window.ref) {
clearTimeout(window.ref[i]);
}
Or do it the jQuery way:
$.each(window.ref, function (index, value) { clearTimeout(value); });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to remove the last two zero? I have a function called zen_get_products_discount_price_qty($new_products->fields['products_id']) which outputs this: $8.0000.
I want to turn the $8.0000 into $8.00. How can I do this?
A: use number_format function
A: $output = zen_get_products_discount_price_qty($new_products->fields['products_id']);
$output = substr($output,0,-2);
A: first remove $ then use round() function.
A: Try this:
$value = '$8.0000';
$value = str_replace('$', '', $value);
$value = number_format($value, 2);
echo $value;
http://at2.php.net/number_format
It's important to use number_format to get correctly values. The function substr() only delete the last two zeros. The function number_format() round the number.
number_format(8.1199, 2); // == 8.12 - correct
substr(8.1199, 0, -2); // == 8.11 - false!
A: printf('$%.02f', 8.0000); // $8.00
A: Or preg_replace :)
echo preg_replace("/^\$(\d+?)(?:.\d*)?$/", "\$$1.00", '$8.0000');
Output: $8.00
A: DON'T use any substr(), printf(), number_format() etc. solutions. They don't take care of currencies other than USD where there might be different display requirements. Use instead Zen Cart global $currencies object:
$currencies->format($my_price);
Check includes/classes/currencies.php for reference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add localized .strings files back to Xcode? I have a .strings file that is localized in a number of languages. I'd like to add it to my Xcode project. How do you get Xcode to correctly reference the files? I've tried
*
*dragging the english version of the .strings file (found in English.lproj) to Xcode and hoping it would automatically pick up the other localized versions of the file -- it doesn't.
*dragging all 5 localized versions of the .strings file (found in English.lproj, es.lproj, etc.) assuming Xcode would create a single file reference with the various localized versions -- it crashes.
*dragging each of the .lproj folders to Xcode hoping it would figure out that the file in each of the folders is all the same file, but localized -- nope
*dragging the English version of the localized .strings file to Xcode, then add a localization that already exists -- Xcode warns that it will overwrite the file, but doesn't give the option to use the existing file.
UPDATE: Submitted a bug report to Apple: #10181468.
A: Add the original file (only the file, not the .lproj folder) then make it localizable, add all languages you want, xcode will create .lproj folders and duplicate your original file for each language.
After you can overwrite each file duplicated by your already translated file (either the file if it have the same name or content).
Don't forget to set the format of the original file to UTF-16 when you add it.
A: The simplest way as of Xcode 4.6 is to drag localization file (.strings file, not the folder it's located inside of) from Finder to the Xcode project tree. Be accurate and drag to the top of .strings group, not to the bottom or inside of the group as the latter makes Xcode crash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Accessing fully developed dom through plugin in Firefox I need to see the fully loaded and devloped dom of a page, i.e after my client loads up my page I want them to be able to click a button on fire fox and then fire fox will send me the fully developed dom so I can look through and see what happened there.
Can anyone help point me to the right direction?
A: First you need a function to know whether DOM is ready. A functionality provided by many Javascript frameworks, but refer this if you need a pure js implementation.
When the DOM is ready the button is enabled for the user to click.
Then you may have a function to serialize the DOM tree to a string. As Load and Save DOM is not yet implemented in Mozilla, read this MDN article to get to know what you want.
Now you can send the Saved DOM to your Web Service.
//Code grabbed mostly from MDN article linked
var req = new XMLHttpRequest();
req.open("GET", "chrome://passwdmaker/content/people.xml", false);
req.send(null);
var dom = req.responseXML;
var serializer = new XMLSerializer();
var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
var file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsILocalFile);//get profile folder
file.append("extensions"); // extensions sub-directory
file.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}");//GUID of your extension
file.append("myXMLFile.xml"); // filename
foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0);//write, create, truncate
serializer.serializeToStream(dom, foStream, "");//remember, dom is the DOM tree
foStream.close();
Hope this would help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't add event listener after it was removing by "removeEventListener" only on mobile I'm newbie in js and jquery.
I have the code:
function dragEnd(){
OnDrag = false;
wrapperHalfWidth = box.parent().width() * settings.animPartofScrennToSlide
if (Math.abs(dragLengthX) > wrapperHalfWidth ){
this.removeEventListener((useMobileDrag ? "touchstart" : "mousedown"), dragStart, false);
this.removeEventListener((useMobileDrag ? "touchmove" : "mousemove"), dragMove, false);
this.removeEventListener((useMobileDrag ? "touchend" : "mouseup"), dragEnd, false);
this.removeEventListener("touchcancel", dragCancel, false);
var Direction = dragLengthX > 0;
settings.prevNextClickCallback(outerSlCounter, Direction ? FORWARD : BACK);
setTimeout(function(){
this.addEventListener((useMobileDrag ? "touchstart" : "mousedown"), dragStart, false);
this.addEventListener((useMobileDrag ? "touchmove" : "mousemove"), dragMove, false);
this.addEventListener((useMobileDrag ? "touchend" : "mouseup"), dragEnd, false);
this.addEventListener("touchcancel", dragCancel, false);
}, 500);
return SlideTo(outerSlCounter + (Direction ? -1 : 1));
}
else{
dragLengthX = 0;
box.css({
'-webkit-transition-timing-function': settings.easingCss,
'-webkit-transition-duration': settings.animDragTime + 'ms',
'-webkit-transform': 'translate3d(' + dragLengthX + 'px, 0px, 0px)',
'transition-timing-function': settings.easingCss,
'transition-duration': settings.animDragTime + 'ms',
'transform': 'translate3d(' + dragLengthX + 'px, 0px, 0px)'
});
}
isDragging = false;
originalX = 0;
};
this.addEventListener((useMobileDrag ? "touchstart" : "mousedown"), dragStart, false);
this.addEventListener((useMobileDrag ? "touchmove" : "mousemove"), dragMove, false);
this.addEventListener((useMobileDrag ? "touchend" : "mouseup"), dragEnd, false);
this.addEventListener("touchcancel", dragCancel, false);
The borblem is within if (Math.abs(dragLengthX) > wrapperHalfWidth ){...} section. I need to delete event handlers for the 500ms to prevent other functions (dragStart(event) and dragMove(event)) start.
On desctop it work good. it delete event for the time, when Slidind function is work. But on mobile devices after alert event listeners don't work
A: Don't use addEventListener or removeEventListener with jQuery. Use bind()/unbind() instead.
if (Math.abs(dragLengthX) > wrapperHalfWidth ) {
$(this)
.bind("touchstart mousedown", dragStart)
.bind("touchmove mousemove", dragMove)
.bind("touchend mouseup", dragEnd)
.unbind("touchcancel");
var Direction = dragLengthX > 0;
settings.prevNextClickCallback(outerSlCounter, Direction ? FORWARD : BACK);
setTimeout(function () {
$(this)
.unbind("touchstart mousedown touchmove mousemove touchend mouseup")
.bind("touchcancel", dragCancel);
}, 500);
return SlideTo(outerSlCounter + (Direction ? -1 : 1));
}
Although I would find it more elegant if you would use a flag that that tells whether the event handlers should do anything or not, instead of constantly binding and undbinding them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Explain the steps for db2-cobol's execution process if both are db2 -cobol programs How to run two sub programs from a main program if both are db2-cobol programs?
My main program named 'Mainpgm1', which is calling my subprograms named 'subpgm1' and 'subpgm2' which are a called programs and I preferred static call only.
Actually, I am now using a statement called package instead of a plan and one member, both in 'db2bind'(bind program) along with one dbrmlib which is having a dsn name.
The main problem is that What are the changes affected in 'db2bind' while I am binding both the db2-cobol programs.
Similarly, in the 'DB2RUN'(run program) too.
A: Each program (or subprogram) that contains SQL needs to be pre-processed to create a DBRM. The DBRM is then bound into
a PLAN that is accessed by a LOAD module at run time to obtain the correct DB/2 access
paths for the SQL statements it contains.
You have gone from having all of your SQL in one program to several sub-programs. The basic process
remains the same - you need a PLAN to run the program.
DBA's often suggest that if you have several sub-programs containing SQL that you
create PACKAGES for them and then bind the PACKAGES into a PLAN. What was once a one
step process is now two:
*
*Bind DBRM into a PACKAGE
*Bind PACKAGES into a PLAN
What is the big deal with PACKAGES?
Suppose you have 50 sub-programs containing SQL. If you create
a DBRM for each of them and then bind all 50 into a PLAN, as a single operation, it is going
to take a lot of resources to build the PLAN because every SQL statement in every program needs
to be analyzed and access paths created for them. This isn't so bad when all 50 sub-programs are new
or have been changed. However, if you have a relatively stable system and want to change 1 sub-program you
end up reBINDing all 50 DBRMS to create the PLAN - even though 49 of the 50 have not changed and
will end up using exactly the same access paths. This isn't a very good apporach. It is analagous to compiling
all 50 sub-programs every time you make a change to any one of them.
However, if you create a PACKAGE for each sub-program, the PACKAGE is what takes the real work to build.
It contains all the access paths for its associated DBRM. Now if you change just 1 sub-program you
only have to rebuild its PACKAGE by rebinding a single DBRM into the PACKAGE collection and then reBIND the PLAN.
However, binding a set of PACKAGES (collection) into a PLAN
is a whole lot less resource intensive than binding all the DBRM's in the system.
Once you have a PLAN containing all of the access paths used in your program, just use it. It doesn't matter
if the SQL being executed is from subprogram1 or subprogram2. As long as you have associated the PLAN
to the LOAD that is being run it should all work out.
Every installation has its own naming conventions and standards for setting up PACKAGES, COLLECTIONS and
PLANS. You should review these with your Data Base Administrator before going much further.
Here is some background information concerning program preperation in a DB/2 environment:
Developing your Application
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Routing - Explanation for 404 page I use asp.net 4, c# and Routing for my web site.
My Route result like
A) http://mysite.com/article/58/mytitle (result my article all is fine)
58 and mytitle represent in Id and Title Column in DataBase for my Articles table.
I notice that... if I request:
http://mysite.com/article/2000000000/mytitle (a not existing ID)
I receive an Error page.
If instead I try:
B) http://mysite.com/article/58/mytitttttttle (title misspelled)
I still get my page http://mysite.com/article/58/mytitle
I would need to have my website redirect to a 404 page if both the ID or the TITLE do not not represent any record in my DataSource.
PS: I notice that SO website has a similar behavior, apart that they are able to redirect to a 404 page if the ID for a questions does not match.
My questions:
*
*is this a normal behavior?
*how to redirect to 404 pages instead?
*if is not possible to use 404 pages would make use canonical urls?
I asked because I'm concerning on this scenario, lets imagine a website link wrongly to my site like
http://mysite.com/article/58/mytitttttttle (title misspelled)
or
http://mysite.com/article/58/mytitttttttle2222 (title misspelled)
both will be index my Search Engine and resulting in duplicate content (and it is not good).
Please provide me a sample of code if possible. I appreciate your comment on this, thanks!
A: Hi I did this recently and used this blog which helped alot
http://weblogs.asp.net/paxer/archive/2010/05/31/asp-net-http-404-and-seo.aspx
http://searchengineland.com/url-rewriting-custom-error-pages-in-aspnet-20-12234
A: The reason this happens is because it uses the numerical id as the search key (in this case it looks for post 58 no matter what).
What you could do is either
*
*get rid of numerical id, and stick with just text OR
*retrieve the post, and verify the "postslug" is correct based on what you pulled out from database.
By using just text, you get a cleaner url. However you have to rely on your database indexing your strings in order to have high performance lookup on your postslug. And you have to worry about duplicate slugs.
By using the hybrid, you have less clean url (extra info), but you don't need to worry too much about integer lookup performance.
Which ever choice you pick, you verify this information in your controller, then either return View, or return HttpNotFound()
A: Rather than passing the ID and Title, I would recommend saving the Title as a unique value in the database so you can just have:
http://mysite.com/article/title
What happens if there are two titles? Well, then you can create a loop until you find a unique one incrementing an integer at the end like:
http://mysite.com/article/title-2
This gets around the issue of their being an ~infinite number of possible URLs which all point to the same page (which Google will hate you for)
Alternatively, if you wish to keep your URL with both the ID and Title in place, then on your web form run an if statement which returns how many records in the database match the variables.
Something like:
cmd.CommandText = "SELECT COUNT(*) FROM Table WHERE ID=@ID AND Title=@Title"
if ((int)cmd.executescalar == 0){
Response.Redirect("404.aspx");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Anyone that had the aol oauth api working? i'm developing an application with multiple login and information export options like yahoo, google contacts, live contacts etc. I tried to do the oauth wrapper for aol, followed the examples in the http://dev.aol.com/api/openauth page but it doesnt works.
I just only wanted to know if there is anyone that chad succeeded with its specs and got some sample code working, i tried and got the token in response but when i try to do an api request i get the response : Key Used From unauthenticated site
does it have to run in a online server? do i have to get some rsa signed file on my server?
any hint is welcome, thank you very much!
A: I haven't tried it before but I think you have to tell them your the IP you will sent requests from..
I was making project over enom API and I had to send them my IP to authorize my API requests
A: sorry for my late response, have being little busy here. The code in the example finally worked right last time i tried, maybe their servers had some issues or i misconfigured the example, not sure, but in my project it didnt worked, finally i managed the solution by using the CURLOPT_REFERER parameter i found in the example. I am sure that it was the issue in my code, because i was testing in a devel environment with a .loc top level domain.
Finally i want to give a hint to all the people trying to develop 3rd party apps that check the validity of the urls asking for permissions, you could use a testing environment by using the CURLOPT_REFERER paramater by setting the production url you want in the testing environment.
file in the testing environment http://www.mycoolsite.loc.
curl_setopt( CURLOPT_REFERER 'http://www.mycoolsite.com' );
The site that will receive the answer will check the referer and assume the .com one instead the .loc
Thanks to everybody that tried to help me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: ASP.NET LINQ SQL get specific fields I am trying o set textboxes on an ASP.NET webpage using LINQ - SQL. Here is the code I have to perform the select statement:
EQCN = Request.QueryString["EQCN"];
var equipment = from n in db.equipments
where n.EQCN.ToString() == EQCN
select n;
How do I set TextBox1.text to be a specific field in the table?
Thanks so much
EDIT
I need to output every field in the table into different textboxes. So performing a query for ever single one seems a little much. There has to be a way to do this?
Thanks
A: Well you can select the appropriate field to start with:
EQCN = Request.QueryString["EQCN"];
var values = from n in db.equipments
where n.EQCN.ToString() == EQCN
select n.FieldYouWant;
// Or possibly Single, or First...
var singleValue = values.FirstOrDefault();
I think that's what you were after, but if it's not, please clarify your question.
EDIT: To answer your follow-up, you can use:
EQCN = Request.QueryString["EQCN"];
var query = from n in db.equipments
where n.EQCN.ToString() == EQCN
select n;
// Or possibly Single, or First...
var entity = query.Single();
textBox1.Text = entity.Name;
textBox2.Text = entity.Description;
textBox3.Text = entity.Title;
// etc
That's assuming you want to have access to everything in the entity. If the entity is very large and you only need a few fields, you might want to do something like this:
EQCN = Request.QueryString["EQCN"];
var query = from n in db.equipments
where n.EQCN.ToString() == EQCN
select new { n.Name, n.Description, n.Title };
// Or possibly Single, or First...
var projection = query.Single();
textBox1.Text = projection.Name;
textBox2.Text = projection.Description;
textBox3.Text = projection.Title;
I'm not sure I'd actually couple the data access and UI layers so closely, but that's a different matter...
A: You only need to perform the query once, but once that's done, you'll have to assign each field to a TextBox. Start by retrieving only the single item you want:
EQCN = Request.QueryString["EQCN"];
var equipment = (from n in db.equipments
where n.EQCN.ToString() == EQCN
select n).FirstOrDefault();
Then go through and assign each TextBox to the appropriate field:
txtName.Text = equipment.Name;
txtDescription.Text = equipment.Description;
txtValue1.Text = equipment.Value1;
txtValue2.Text = equipment.Value2;
//...
If you have several dozen TextBoxes to assign, you could set up a custom control that can be databound to an equipment object, but even then, you'll still have to write the binding code for your control.
The only way I can think of to totally automate this process is to name each TextBox after a field in your object, then use reflection to match them to values:
var textboxes = Panel1.Controls.OfType<TextBox>();
foreach (TextBox txt in textboxes)
{
string fieldname = txt.ID.Remove(0, 3); //"txtDescription" becomes "Description"
string value = equipment.GetType().GetProperty(fieldname).GetValue(equipment, null) as string;
txt.Text = value;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to stop the avplayer sending a range http header field If you load remote files with the AVPlayer it sends a http request with a range field in the request header, something like
Range: bytes=0-8148096
I like to use the SevenDigital commercial API for streaming songs but they cannot handle this Range header. Is there a way to change the URL requests the AVPlayer sends?
A: Nope, and it is an apple standard that media providers need to support http 1.1 with the range header (check out the iTunes store guidelines for podcasts for example), so I wouldn't expect it anytime soon. You'll need to roll your own here, sorry.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: org/codehaus/plexus/archiver/jar/JarArchiver (Unsupported major.minor version 49.0) - Maven build error Afternoon all,
I am receiving the above error when trying to build my project. I'm pretty sure this has something to do with Maven's latest update being compiled using Java 1.6 and the project we are trying to build is a 1.4 project. The plugin prior to this worked without problems, so I have added the following to the POM.xml file to try to force the existing plugin to be used.
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-archiver</artifactId>
<version>1.2</version>
</dependency>
But it continues to fail.
Any help would be much appreciated
Thanks
A: The error you are experiencing means that org/codehaus/plexus/archiver/jar/JarArchiver was compiled against Java 1.5 whilst you are trying to load using older Java version.
1.2 version of plexus-archiver works under Java 1.4. However 2.0 requires Java 1.5. Are you sure you are using 1.2?
If this is a plugin, it should be defined under <plugins>.
A: Try to add the following plugin for maven. It works for me:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
A: Use:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
A: I was getting this error till I changed my maven-source-plugin version to 2.2.1. I was getting the error with 2.1.1.
A: Including the 'old' version of a plugin in the pom.xml is solving part of the problem. you also need to make sure you are using the right jvm to match.
For a current project i'm working on I had to set JAVA_HOME to java 1.4 with maven 2.0.8. Problem with maven is that it looks for updates in the local and remote repositories (if there is a remote repository set in the maven settings.xml), than tries use version 2.5 for the 'clean' and 'install' plugins for example causing the major.minor 49.0 error (clean and install plugins version 2.5 are compiled with java 1.5 or greater while I tried to execute them in a java 1.4 environment).
With adding in the plugin snippet in the pom.xml of the project forcing it to use version 2.2 combined with the old java version on my path:
(set path=c:\youroldjavadirectory\bin;c:\youroldmavendirectory\bin) everything started working.
Check versions of java before running the maven command:
java -version
mvn -v
A: According to Fred from the m2e-mailing list, this has been fixed with m2eclipse-mavenarchiver 0.17.0. You can install it from http://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.0/N/LATEST/
Just add the repo as an update site, and then upgrade the mavenarchiver component.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can I specify a specific branch on GitHub pull-only (read-only)? Is there a way to set a specific branch on GitHub to pull-only (read-only) or can I only set this for the whole repository?
A: There is no way to do branch level permissions on Github, but the gitolite project supports what you're looking for.
A: You actually can (sort of), since September 2015.
That is because you now have "Protected branches and required status checks" (September 3, 2015), which allows you to protect a branch:
*
*against forced pushed
*against deletion
*against merged changes until required status checks pass
As mentioned in the twitter discussion:
@github nice, what about protect from just push and allow only operating through pull requests?
Adam Roben @aroben @lowl4tency You can do this via the Status API:
create a "success" status only on commits in PRs, then mark that status as required.
Since Nov. 2015, you can protect a branch with the API:
curl "https://api.github.com/repos/github/hubot/branches/master" \
-XPATCH \
-H 'Authorization: token TOKEN'
-H "Accept: application/vnd.github.loki-preview" \
-d '{
"protection": {
"enabled": true,
"required_status_checks": {
"enforcement_level": "everyone",
"contexts": [
"required-status"
]
}
}
}'
How can I try it?
To access this functionality during the preview period, you’ll need to provide the following custom media type in the Accept header:
application/vnd.github.loki-preview+json
Since March 2016, Organizations can now specify which members and teams are able to push to a protected branch.
A: Starting from March 30th 2016, GitHub does support branch permissions without any further tricks like required status checks: https://github.com/blog/2137-protected-branches-improvements
A: This request can now be done with the option Lock branch.
Reference: New Branch Protections: Last Pusher and Locked Branch
Lock branch
This allows for branches to be locked, prohibiting changes. You can lock a branch allowing you to have a maintenance window and prevent changes, or to protect a fork so it only receives changes from its upstream repository.
To use this feature in a branch protection rule, enable Lock branch.
A: Go to the Settings, Add the branch as a protected branch and then there is an option as : Lock Branch (Branch is read-only. Users cannot push to the branch.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Selecting a tag and class (jQuery) Say I the following:
<div id = "thisOne">
<a href = "#" class="ui-state-highlight">abc</a>
<a href = "#'>def</a>
</div>
If i do $(".thisOne a") I get both "a" elements. I just want the one that is highlighted, how do I do this?
A: This two lines of code should help you, give them a try :
$("#thisOne .highlight")
and for the other
$("#thisOne :not(.highlight)")
A: This should do it: $('a.highlight');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the best way to encrypt my connection string in the web.config? I have a web site written in asp.net 4.0. Right now the connection stirng in the web.config is not encrytped. I pushed it to a host with a web farm. I'm tryign to determine the best way to handle encryption. I don't believe I have any authority on the servers.
A: There's an article on the MSDN site that explains how: http://msdn.microsoft.com/en-us/library/dtkwfdky.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python Script, args not transferred to Script I have got a Python Script called "gcc_opt.pyw" and I included its directory to the Windows PATH environment variable.
But not a single commandline argument is passed to the script. Printing out sys.argv tells me there is only the filename in the argv-list.
This command:
gcc_opt HelloWorld.c -o HelloWorld.exe -shared
results in
["C:\\Scripts\\gcc_opt.pyw"]
Can you tell me why there are no other arguments ?
I don't know if it is important, but I've set python.exe to be the default program to execute .pyw files as i don't see any prints using pythonw.exe (why ever this is).
A: The reason why you're not getting parameters is because you broke the .py
association so you could double-click those files to open them in NotePad++,
and subsequently broke the .pyw association to do what .py is supposed to do.
In short, you forgot to include the %* at the end of your Python.exe command
line for your "customized" (mangled) .pyw association.
The ASSOC and FTYPE commands are used to show associations and file types, ie,
what program gets run to handle a file with a particular extension. Here is
what those commands produce on my system:
C:\test>assoc .py
.py=Python.File
C:\test>assoc .pyw
.pyw=Python.NoConFile
C:\test>ftype python.file
python.file="C:\Python27\python.exe" "%1" %*
C:\test>ftype python.noconfile
python.noconfile="C:\Python27\pythonw.exe" "%1" %*
The normal .py association runs python.exe with a console window so that you
can see the output of print statements.
The normal .pyw association runs pythonw.exe with no console window.
You can see at the end of each command line, there is a %*. This is what sends
the parameters to a command. (Actually, %1 is the first parameter, and %*
means "all remaining parameters".)
When you try to run a python file at the command line without typing its
extension or the initial "python" command, a few things happen.
First the PATHEXT environment variable is used to find a matching extension.
In your case it finds that your command name "gcc_opt" + .PYW results in a
matching file.
Then the association for .PYW files is looked up, which finds the filetype
Python.NoConFile, which in your case is set to "python.exe" (supposed to be
pythonw.exe). (You can see these in the registry under HKEY_CLASSES_ROOT.)
The system then creates an actual command line from the command template found
for that filetype, which in your case is probably
"[your-python-path]python.exe" "%1"
This tells it to use just the first parameter, your python script name
"gcc_opt.pyw".
The quick fix is to add the %* to the end of that command.
The CORRECT fix would be to put things back to the correct associations and
open Python files for editing by a more standard method (drop icon onto
NotePad++, or maybe right click and Edit with NotePad++).
A: You should rename it to .py.
.pyw is intended to be used for GUI applications, because they don't need console window.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: sftp connection When I' m trying to connect Sftp from my joomla site
its not connecting:
$c = ftp_connect('ftp.xyz.com') or die("Can't connect");
ftp_login($c, 'username' , 'pwd') or die("Can't login");
in this case msg showing Can't connect
I also tried this code
$connection = ssh2_connect('ftp.xyz.com', 22);
if (!$connection) die('Connection failed');
in this case no error msg showing
Please help me, if there is a proper solution help me please.
Thanks
A: ftp_connect() uses FTP, not SFTP. They're very different. So if your host is providing only SFTP, then no, that function won't work! SFTP is explained in more detail here:
http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol
ssh2_connect() is the right connection method to use, which is why it's probably working. You can see all the SSH2 functions available in PHP here:
http://php.net/manual/en/ref.ssh2.php
You'll probably be most interested in ssh2_scp_recv() and ssh2_scp_send() (for getting and sending files).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to obtain the GPS position of the user and actualice a textview everytime the position has changed? I'm trying to make a simple activity that reads the GPS position of the user and actualices a simple textview everytime the position of the user changes.
I find some examples en google but all of them are not nice examples, because only capture the position of the user ONE time, and i need that the textview get's actualiced everytime the position changes with the new latitude and longitude of the user.
I tryed to do a thread but it fails and i think it is not necesary to do a thread, im in the wrong way.
Code examples are welcome
EDIT: i'm adding the solution proposed by the user NickT. This solution fails. I dont know why but only actualizes two times the textview, with the two first GPS values that i pass to the emulator with DDMS.... after this the thextview isn't getting actualiced more times... ¿why?. I make a breakpoint in onLocationChanged, and it only get's called the first two times i send a gps positiones... but never more. ¿what is happening?
public class GpsMiniActivity extends Activity implements LocationListener{
private LocationManager mLocMgr;
private TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout rl = new FrameLayout(this.getApplicationContext());
LinearLayout ll= new LinearLayout(this.getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(rl);
rl.addView(ll);
tv1=new TextView(getApplicationContext());
ll.addView(tv1);
//setContentView(R.layout.main);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, this);
}
@Override
public void onLocationChanged(Location location) {
tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
A: Absolute minimum example:
public class GpsMiniActivity extends Activity implements LocationListener{
private LocationManager mLocMgr;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, this);
}
@Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.tv1);
tv.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
You'll also need permission ACCESS_FINE_LOCATION in your manifest and a Textview id tv1 in main.xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to close all opened markers? I have this code :
var markers = new Array();
markers[0] = new google.maps.Marker({
position: new google.maps.LatLng(45.910078, 10.838013),
map: map,
title: "Data 1"
});
google.maps.event.addListener(markers[0], 'click', function() {
var infowindow = new google.maps.InfoWindow({
content: $('#map_info_window_id').html()
});
infowindow.open(map, markers[0]);
});
markers[1] = new google.maps.Marker({
position: new google.maps.LatLng(46.176086, 11.064048),
map: map,
title: "Data 2"
});
google.maps.event.addListener(markers[1], 'click', function() {
var infowindow = new google.maps.InfoWindow({
content: $('#map_info_window_id').html()
});
infowindow.open(map, markers[1]);
});
and how you can see, I have a listener for each marker!
Now, when I click on a marker, I'd like to close all marker (in fact only one, the previously opened).
How can I do it on Google Maps API 3?
A: set the map of the marker to null:
marker.setMap(null);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parallel execution in cx-oracle I have recently joined a new company and am new to python (their preferred scripting language) and have been working with cx_oracle to create some ETL processes. The scripts I have built so far have been single-threaded jobs that select the subset of columns I need from an Oracle source DB and write the output to a named pipe where an external process is waiting to read that data and insert it into the target.
This has worked fine until I get to some tables that are in the 500 million -2 billion row range. The job still works, but it is taking many hours to complete. These large source tables are partitioned so I have been trying to research ways to coordinate parallel reads of different partitions so I can get two or more threads working concurrently, each writing to a separate named pipe.
Is there an elegant way in cx-oracle to handle multiple threads reading from different partitions of the same table?
Here's my current (simple) code:
import cx_Oracle
import csv
# connect via SQL*Net string or by each segment in a separate argument
connection = cx_Oracle.connect("user/password@TNS")
csv.register_dialect('pipe_delimited', escapechar='\\' delimiter='|',quoting=csv.QUOTE_NONE)
cursor = connection.cursor()
f = open("<path_to_named_pipe>", "w")
writer = csv.writer(f, dialect='pipe_delimited', lineterminator="\n")
r = cursor.execute("""SELECT <column_list> from <SOURCE_TABLE>""")
for row in cursor:
writer.writerow(row)
f.close()
Some of my source tables have over 1000 partitions so hard-coding the partition names in isn't the preferred option. I have been thinking about setting up arrays of partition names and iterating through them, but if folks have other ideas I'd love to hear them.
A: First of all, you need to make sure that *cx_Oracle* is thread-safe. Since it implements the Python DB API Spec v2.0, all you need to do is check the threadsafety module global.
Values 2 or 3 mean that you can open multiple connections to the DB and run multiple queries at the same time. The best way to do this is to use the threading module, which is pretty easy to use. This is a short and sweet article on how to get started with it.
Of course, there are no guarantees that pipelining your queries will result in a significant performance gains (DB engine, I/O, etc. reasons) but it's definitely worth the try. Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to delay .live() until UI has updated? I am using jQuery and jQuery UI and i am trying to read a checkbox state through the addition of the "aria-pressed" property that jQuery UI Button toggle between false and true.
$('.slideButton').live('click', function() {
alert($(this).attr('aria-pressed'));
});
This code however seems to read the aria-pressed before jQuery UI has updated aria-pressed. So i unreliable values. Can i schedule it to execute after the UI has updated or can i make it wait?
Live example here!
A: Can't you add a listener to the actual checkbox behind the label or span?
$("#days_list li div div div input[type='checkbox']").change(function(){
alert("Someone just clicked checkbox with id"+$(this).attr("id"));
});
This should work since, once you click the label, you change the value in the checkbox.
Alright, I've composed a live example for you that demonstrates the general idea of how it works, and how you retrieve the status of the checkbox.
$("#checkbox_container input").change(function(){
if($(this).is(":checked")) alert("Checked!");
else alert("Unchecked!");
});
In your case, since the checkbox is added dynamically by JQuery you have to use the live event, but it is basically the same thing
$("#checkbox_container input").live("changed"....
Here's an example with some additional scripting and checking, mostly for demonstrative purposes.
A: You can use a callback to execute the alert($(this).attr('aria-pressed')); after the toggle has completed.
$('.slidebutton').toggle(1000, function(){
alert($(this).attr('aria-pressed'));
});
I'm not too sure if your using .toggle() or not but you would need to use a callback either way to ensure sequential execution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how far can nfc on mobile phone read rfid tags I google on the internet and find that nfc on mobile phone is said to be able to read rfid tag (HF tag). Does anybody test how far it can read RFID tag, or what's reading range for RFID tag? Is it possbile to read RFID tags within 1 meters?
A: My informal test just now, with the Nexus S, resulted in a read distance of about 2 cm, maybe a little more, but not much. A larger read distance would probably drain the battery quite fast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Strange result when reading data from browser cache In an experimental extension I am working on I use a function to get the source of a webpage and assign it to a variable. It worked perfectly fine. However I want to change the way it works and get the content from a txt file.
I am hosting a txt file like: http//1.2.3.4/1.txt.
What I want is to assign the contents of this txt file to a variable.
Function is here: http://jsfiddle.net/qumsm/.
(Function is not mine. I got it from another extension xpi which I cant remember right now. Respects to the coder of it.)
The function produces "ÿþP" this result which I dont get.
A: That's a byte order mark, the file you are looking at seems to be using UTF-16 LE encoding. You need to use nsIConverterInputStream instead of nsIScriptableInputStream when reading in that data and specify the correct encoding to convert from. nsIScriptableInputStream is only useful when reading in ANSI data, not Unicode. See code example on MDN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access URL with double slash with HttpClient I'm doing a request on another server like this:
HttpGet req = new HttpGet("http://example.com//foo");
new DefaultHttpClient().execute(req);
However, HttpClient changes example.com//foo to example.com/foo, so the other server (which is not mine) doesn't understand the request.
How can I fix this?
A: A double-slash is not a legal in the path section of a URI (see RFC2396, sections 3.2, 3.4). The '//' sequence has a defined meaning in the URI, it denotes the authority component (server).
I realize this does not answer your question but the HttpClient is, in fact, behaving in accordance with the HTTP and URL standards. The server your are reading from is not. This appears to be previously reported (https://issues.apache.org/jira/browse/HTTPCLIENT-727) and discarded by the HttpClient team.
A: It is an illegal URL in fact.
Did you try passing an URI instead of a String?
Did you try / \ \ / ? Or the URL might be equivalent to /default.asp/, /index.html/, /./, /?/, example.com/foo/ or the like.
Otherwise you will need to hack the sources.
A: I also wanted to do same thing and Apache Http client don't support that.
I managed to get it done using a Netty. I wrote http client using Netty and with that I was able send request with double slash(//) in the path. I used SnoopClient as sample.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Setting different backgrounds for nsview I'm trying to set custom background for an NSView. I need different backgrounds to be set based on some action. So i created 2 CAlayers for this view and trying to fill it using colorWithPatternImage.Is this a right method? If not, how can i do it?
Regards,
LS Developer
A: You could subclass the view that you want, and in its drawRect: method do something like
- (void)drawRect:(NSRect)dirtyRect
{
// Colour the background
[[NSColor orangeColor] set];
NSFillRect (dirtyRect);
// Now draw the parent
[super drawRect:dirtyRect];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drop Down List Event failed to execute In my drop-down list, the SelectedIndexChanged event is not firing. I set AutoPostBack="True" but it's still not firing. Setting EnableViewState to True or False makes no difference either.
Here's my code:
<asp:DropDownList ID="ddlSheerName" runat="server" Width="250" AutoPostBack="True"
OnSelectedIndexChanged="ddlSheerName_SelectedIndexChanged"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
loggedInUserId = Convert.ToString(Session["LoggedInUserId"]);
if (loggedInUserId == "")
{
Response.Redirect("Login.aspx");
}
if (Page.IsPostBack == false)
{
BindCompanyDropDown();
}
}
protected void ddlSheerName_SelectedIndexChanged(object sender, EventArgs e)
{
Bindcolumnname();
}
public void BindCompanyDropDown()
{
try
{
objData = new DBFile();
DataSet dsCompanies = objData.GetCompaniesList(loggedInUserId);
if (dsCompanies != null)
{
if (dsCompanies.Tables[0].Rows.Count > 0)
{
ddlselectcompany.DataSource = dsCompanies;
ddlselectcompany.DataTextField = "CompanyName";
ddlselectcompany.DataValueField = "CompanyID";
ddlselectcompany.DataBind();
}
}
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
}
}
A: The dropdown itself doesn't cause the event to fire.
You must actually change the selected item for the event to fire.
A: Viewstate must be enabled for this particular code to work and Javascript must be enabled for AutoPostBack to function.
A: Is your event registred in the designer?
Select the dropdown and check the events assigned to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Specifying multiple Spring configuration files using ant style pattern in command line app I have a web application with mutiple Spring configuration files. These files are loaded using "contextConfigLocation" in web.xml. Like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:META-INF/*beans.xml
</param-value>
</context-param>
Everything works as desired.
Now I am having to write a command line application that must load the same files as the web application. Currently I am using ClassPathXmlApplicationContext and manually specifying each configuration file name. But sooner or later somebody is going to add another file and expect it to be read by the CLI, just like the web app. Currently that will not happen because each file is explicitly specified in my CLI. So I need my CLI to load configuration files just like the web app i.e. load all configuration files that match a pattern. Is there a way to do this using ClassPathXmlApplicationContext or any other way?
A: I think you can do this using ClassPathXmlApplicationContext, This will load any context file that is in class path ending with name Beans
public class LoadContext {
/**
* @param args
*/
public static void main(String[] args)
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:*Beans.xml");
}
}
A: Why don't you create a new configuration file spring-all.xml and load only this. In this file, use the import element to import all other xml configuration files that you need.
<beans>
<import resource="spring-services.xml"/>
<import resource="spring-daos.xml"/>
<import resource="spring-controllers.xml"/>
...
</beans>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ajax during javascript window.beforeunload: returning error I need to perform an ajax request to send some data server-side every time the user decides to leave the page. However I do not wish to disrupt them in leaving: I do not want popup messages to show up. Currently my code is thus:
window.onbeforeunload=function(){
unloadAjax();
}
This does not work and causes a momentary ajax-error message to show up. However, if I add a return false; statement inside the onbeforeunload function, the ajax works fine. How do I fix this problem?
A: When you add return false, a confirmation dialog shows up, delaying the page unload. Meanwhile, the AJAX request finishes. When no return statement is included, the page will immediately unloads, terminating all active connections (and breaking your AJAX request).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java arrays in Clojure's gen-interface I have this piece of code:
(ns com.example.main)
(gen-class
:name com.example.main.CTest
:methods [ [foo [] "[B"]])
(defn -foo [this]
(byte-array [(byte 1) (byte 2)]))
(gen-interface
:name com.example.main.ITest
:methods [ [foo [] "[B"]])
It creates the foo method in class CTest correctly, with return type byte[]. However, the same thing creates a method with return type [B in the ITest interface. How do I do this correctly? Is it a bug in Clojure?
Thanks, David
A: I don't know if some other solution is preferred, but this works:
(gen-interface
:name com.example.main.ITest
:methods [[foo [] #=(java.lang.Class/forName "[B")]])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In drupal 6, How to process uloaded file in more than one steps? I am writing custom module in drupal.
Aim is to :
1. Upload a csv file
2. Display its content in a tabular layout.
3. On confirmation, save it in database.
Problem I am facing:
*
*I am unable to upload any file. I am not getting any thing in $_FILES, even if I upload or not. >> SOLVED
*How do I split the process ? Suppose I succeed in uploading file [with your help indeed ;) ], and I save the file, suppose in drupal6/uploaded_data directory. How do I redirect to next page where I can read from file and show tabular data for confirmation.
Codes :)
menu hooks and all
function productsadmin_menu() {
$items['admin/settings/product-administration'] = array(
'title' => 'Product Administration',
'description' => 'Upload products data',
'page callback' => 'productsadmin_form',
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function productsadmin_form() {
return drupal_get_form('productsadmin_my_form');
}
This function is passed to drupal_get_form()
function productsadmin_my_form() {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['csv'] = array(
'#type' => 'file',
'#title' => 'Product Catalog',
'#description' => 'Product catalog in specified csv format',
'#required' => FALSE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
Validation (The part which is not working is commented)
function productsadmin_my_form_validate($form, &$form_state) {
if($form_state['values']['csv'] == "") {
form_set_error('csv', t('Please input product catalog csv data'));
}
/* // Check if file is uploaded (Not working)
if ($_FILES['files']['name']['csv'] == '') {
form_set_error('csv', t('Please upload product catalog' . $rahul_vals));
}
*/
}
Submit action
function productsadmin_my_form_submit($form, &$form_state) {
/*
1. Move File to uploaded_dir
2. Change the header so that it is redirected to new page
*/
}
A: you shouldn't use $_FILES in drupal,use drupal api
I made this example for you to explain how to work with cvs
/**
* Form function
*/
function _form_cvs_import($form_state) {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['container'] = array(
'#type' => 'fieldset',
'#title' => t('CVS UPLOAD') ,
);
$form['container']['cvs_file'] = array(
'#type' => 'file' ,
'#title' => t('CVS FILE') ,
'#description' => t('insert your cvs file here') ,
) ;
$form['container']['submit'] = array(
'#type' => 'submit' ,
'#value' => t('SEND') ,
) ;
return $form ;
}
/**
* form validate
*/
function _form_cvs_import_validate($form, $form_state) {
$validators = array(
'file_validate_extensions' => array('cvs'),
);
if(!file_save_upload('cvs_file', $validators)) { // the file is not submitted
form_set_error('cvs_file', 'Please select the cvs file') ;
}else{ // the file is submitted another validation for extension
$file = file_save_upload('cvs_file', $validators, file_directory_path()) ;
if($file->filemime != 'application/octet-stream' ) {
form_set_error('cvs_file', 'Extensions Allowed : cvs') ;
}
}
}
/**
* form submit
*/
function _form_cvs_import_submit($form, $form_state) {
$file = file_save_upload('cvs_file', $validators, file_directory_path()) ; // this is the cvs file in the tmp directory
$file_handler = fopen($file->filepath, 'r') ; // open this cvs file
$line_num = 0 ;
$fields = array() ;
while(!feof($file_handler)) {
$line_num++ ;
$line = fgets($file_handler) ; // this is the line/row
$line_array = explode(",", $line); // array of row fields
$field_num = 0 ;
foreach($line_array as $field) {
$field_num++ ;
$fields[$line_num][$field_num] = str_replace('"', '', $field ); // E.g you can access second row and third field by $fields[2][3]
}
}
fclose($file_handler);
unlink($file->filepath);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Redirection in drupal 7 I am using Drupal 7 for developing a site called http://somesite.com. My requirement is to redirect the site to http://sub.somesite.com if a sub.somesite.com folder exists in my directory at the time of page request itself.
I have a custom module which is linked to a JavaScript file which is being called from hook_init function. This js file contains the redirection script.
But now the http://somesite.com is loaded first and then it is being redirected to http://sub.somesite.com. I need to perform the checking of file and redirecting at the time of bootstrap process itself so that the user is unaware of the site redirection.
Calling drupal_add_js function from hook_boot function throws me a fatal error (drupal_add_js() undefined).
Is there any other method to meet this requirement?
Any help would be greatly appreciated..
Thanks in advance..
A: This won't work, javascript is not evaluated until the page content is built by which time it's too late to redirect the page without anyone noticing. You will always have a delay if you use javascript...instead you want to use header('Location: somewhere') in hook_boot() if your conditions are matched.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Crystal Report's report loading forever I've some Crystal reports in a VS2010 application. They all work fine, but sometimes (happened at least twice), they will stay on the hourglass without ever loading. If I launch another instance of the application and generate the report (while the other instance still loads), it works fine. If the non-working instance generates another report, it works fine. If the form is closed and reopened, it works fine.
So what may go wrong? There should be a timeout if there's an issue accessing the datasource.
Is this a bug or a known issue? I haven't found any info on that.
Is there a way to catch this "error" so the user doesn't waste his time for half an hour and then call me?
Cheers
A: To catch problems like this you may need to add logging code to your app.
Make sure the Log function includes a time stamp, Pseudo code:
Log("pre-DB connect)
...DB connection
Log("post-DB connect)
Log("pre-Load Report...")
...load the report
Log("post-Load Report")
Once you narrow it down to a section of code, you can add more logging code to that section until hopefully, you zero in on the line that is hanging.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: send parameter with jquery ajax I've a php page and I would to send a jquery ajax request to another page for sending email. This new page accept one parameter and then it executes query ecc...
<div id="customer" name="customer" style="visibility: hidden;"><?php echo $customer; ?></div>
<?php echo '<input id="pulsante" type="image" src="includes/templates/theme485/buttons/english/button_confirm_order.gif" onclick="inoltra();"> '; ?>
this is the script
function inoltra(){
var jqxhr = $.ajax({
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: ??????????????
async:true,
success:function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
}
});
}
how can I pass to data value of div "customer"?
A: function inoltra(){
var jqxhr = $.ajax({
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: JSON.stringify({paramName: $('#customer').html()}),
async:true,
success:function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
}
});
}
A: function inoltra(){
var jqxhr = $.ajax({
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: { customer: $('#customer').html() },
async:true,
success:function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
}
});
}
A: On data: { varName: $('#customer').html() }
on Php:
$varName= $_POST['varName'];
For a simpler sintax, you use this (it the same):
$.post("../gestione_di_canio/services.php", { varName: $('#customer').html() } )
.success(function() {
try{
alert("ok");
}catch (e){
alert("correggi");
}
});
A: I hope this will work for ya...
function inoltra(){
({var jqxhr = $.ajax
type: "POST",
url: "../gestione_di_canio/services.php",
datatype: "json",
data: {"parameter1": value1, "parameter2": value2},// e.i data: {"customer": $('div#customer').html() },
async:true,
success:function() {
try{
alert("ok");
}
catch (e)
{
alert("correggi");
}
}
});
}
as many parameters you want to send would be accessable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android context issues from imported package I have a twitter package that runs fine on its own. Now when I import it and try to use it in my main app I hit upon issues of nullpointerexceptions. The first I solved, but immediately ran into another. I now believe it is because I am handling the context incorrectly.
Here is how I have called one method from my included package.
TweetToTwitterActivity twitter = new TweetToTwitterActivity();
twitter.buttonLogin(v, context);
Now in the TweetToTwitterActivity file I have this. The first method runs fine but I am now getting a null pointer exception from this line. I think I am going about this completely the wrong way. Can anyone help me understand how to run methods properly from an imported class?
setContentView(twitterSite);
public void buttonLogin(View v, Context context) {
mPrefs = context.getSharedPreferences("twitterPrefs", MODE_PRIVATE);
// Load the twitter4j helper
mTwitter = new TwitterFactory().getInstance();
// Tell twitter4j that we want to use it with our app
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
if (mPrefs.contains(PREF_ACCESS_TOKEN)) {
Log.i(TAG, "Repeat User");
loginAuthorisedUser();
} else {
Log.i(TAG, "New User");
loginNewUser(context);
}
}
private void loginNewUser(Context context) {
try {
Log.i(TAG, "Request App Authentication");
mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
Log.i(TAG, "Starting Webview to login to twitter");
WebView twitterSite = new WebView(context);
twitterSite.requestFocus(View.FOCUS_DOWN);
twitterSite.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
twitterSite.loadUrl(mReqToken.getAuthenticationURL());
setContentView(twitterSite);
} catch (TwitterException e) {
Log.e("HelloWorld", "Error in activity", e);
Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
}
}
A: To display the web view,
Insure TweetToTwitterActivity twitter is a started and active activity, otherwise it can not setContentView, as it is not in control. This can be done with something like...
TweetToTwitterActivity twitter = new TweetToTwitterActivity();
Intent intent = new Intent();
intent.setClass(context, TweetToTwitterActivity .class);
startActivity(intent);
Then, it is likely best (possibly required) to call your method form the twitter activity onCreate method, rather then from where the activity is created.
If, as mentioned in the comment, you do not want to actually display the webview, but simply call a web page and analyze the results, do not use a webview, but rather an HttpPost (Or possibly an HttpGet, depending on what you are doing.) Here is an example from an app I have that does a web post, and looks at the results rather then displaying the results....
public static void checkWebSite() {
HttpClient httpclient = getClient();
HttpPost httppost = new HttpPost("http://yoursite.com/pathtopage");
try {
//If you need to add name value params you can do that here...
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "value"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String html = InputStreamToString(response.getEntity().getContent()).toString();
//You can now analyze the html string for whatever you are looking for
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to localize a simple HTML website page in my case? I am NOT developing any web service application which contain client side and backend server side (like java EE application or Ruby on Rails).
Instead, I am simply developing a HTML website page, on this page, there are two flag images(USA and China) which is used as a language selection of the page for users.
I am wondering, for this single web page development (without any backend system), is there any efficient way to implement the page localization(that's display the page in different language) based on the flag selection from user?
A: Here's one way around this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Localise</title>
</head>
<body>
<a href="#china" onclick="showthis('contentchina')">China flag</a>|
<a href="#usa" onclick="showthis('contentusa')">USA flag</a>
<div id="contentchina" style="display:none">
Lorem ipsum dolor sit amet...
</div>
<div id="contentusa" style="display:none">
Duis aute irure dolor...
</div>
<script>
function showthis(nation) {
document.getElementById(nation).style.display = "block";
return false;
}
</script>
</body>
</html>
A: You can use the standard HTML lang attribute:
<span lang="en">Scale</span><span lang="de">Maßstab</span>
And then you can hide and show the matching elements:
function select_language(language) {
$("[lang]").each(function () {
if ($(this).attr("lang") == language)
$(this).show();
else
$(this).hide();
});
}
I use a simple selection:
<select onchange="select_language(this.options[this.selectedIndex].value)">
<option value="en" selected>English</option>
<option value="de">Deutsch</option>
</select>
A: Nowadays I would do it without jQuery. First I would hide all nodes with a lang attribute and show only the default language. This can be done in CSS:
[lang] {
display: none;
}
[lang=en] {
display: unset;
}
Without JavaScript enabled the document is not localized but at least readable in the default language.
Next I would use some JavaScript to show the correct language, if it is in the list of supported languages.
function localize (language)
{
if (['de'].includes(language)) {
let lang = ':lang(' + language + ')';
let hide = '[lang]:not(' + lang + ')';
document.querySelectorAll(hide).forEach(function (node) {
node.style.display = 'none';
});
let show = '[lang]' + lang;
document.querySelectorAll(show).forEach(function (node) {
node.style.display = 'unset';
});
}
}
You can either use a select box or the browser language.
localize(window.navigator.language);
A: You can use JavaScript to read the user language and show the right flag/content:
HTML:
<img id="myFlag" src="flag_default.png"/>
and some jQuery (since you tagged your question with jQuery):
var supportedLangs = ['de', 'en', 'cn'];
var userLang = navigator.language;
if($.inArray(userLang, supportedLangs) >= 0){
$('myFlag').attr('src', 'flag_' + userLang + '.png');
}
hjsfiddle
A: I would suggest looking into a template engine for this problem. To me it's not exactly a backend but more of a grey area. Something like Moustache OR smarty would be perfect for you.
Simply put, i agree with the other posters that this is not reasonable to achieve on the client side.
A: Your webpage needs to understand what encoding it should be using when rendering Chinese characters:
<! -- NOTICE THE "charset=UTF-8" !!!! -->
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type"/>
</head>
A: Yes this is possible. Here is one way
Structure you HTML like this in your folders
/root
/Chinese
/English-American
index.html
The root folder would contain your page with the language selection and the Chinese and English-American will contain your language specific pages.
Now on index.html simply direct the user to the correct language folder and all links will reference the correct language folder
A: Easy answer: No, using a backend is the easiest and best way to accomplish this. Backend code is designed for dynamic content, which is what you want.
Hard answer: This is a way to do this without dividing up your pages into two directories. The problem is that you're going to have to use Javascript to generate your page content, and that's generally a bad idea. But you could use a javascript MVC library, plus ajax calls to content folders that pull in the text (you'd still have to have two directories for English and Chinese, but they would only contain content, not HTML). The thing is, there's multiple potential problems with this method that it's only worth using if you know your users will have a modern browser with javascript enabled.
A: If you want your page to be search engine friendly, you have to put both static version in the HTML. You can put them into two div and when user clicks on a flag you shows the correct div.
You can also use a template like Mustache to render content with JavaScript. Then you can write your non-localized content as a template and make localized content as variables.
A: Generally JS generating the code for you is not good.
But, I did one POC for the same using underscore.js. The framework is having an "_template" function that helps us to replace all the keys in the HTML file. The function accepts the key value pair in JSON format.
Based on the language selected, load the corresponding JSON file and then pass it on to the _template function. This will replace all the keys.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: How to minimize whole application in android? I was developed android application. More over i have completed, but i want to minimize option. I have used tab bar. In that i want to minimize tab. When user click minimize tab to minimize whole application.
my tabbar code as..
public class tabbar extends TabActivity implements OnTabChangeListener {
private Context mContext;
TabHost tabHost;
int tabload=0;
private AlertDialog alertDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbar);
//mContext=this;
/** TabHost will have Tabs */
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
/** TabSpec used to create a new tab.
* By using TabSpec only we can able to setContent to the tab.
* By using TabSpec setIndicator() we can set name to tab. */
/** tid1 is firstTabSpec Id. Its used to access outside. */
TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");
/** TabSpec setIndicator() is used to set name for the tab. */
/** TabSpec setContent() is used to set content for a particular tab. */
firstTabSpec.setIndicator("FRIENDS").setContent(new Intent(this,view_friends.class));
secondTabSpec.setIndicator("GROUPS").setContent(new Intent(this,groups.class));
thirdTabSpec.setIndicator("SIGN OUT").setContent(new Intent(this,signout.class));
/** Add tabSpec to the TabHost to display. */
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);
tabHost.addTab(thirdTabSpec);
}
@Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#343333")); //unselected
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#f1a026")); // selected
// if(tabId.equals("tab_id1")){
// LocalActivityManager manager = getLocalActivityManager();
// manager.destroyActivity("tab_id1", true);
// manager.startActivity("tab_id1", new Intent(this, view_friends.class));
// }
}
@Override
protected void onDestroy() {
super.onDestroy();
tabHost.setCurrentTab(2);
System.gc();
}
}
In this code if any correction need please help...
give me a sample code..
A: I'm not sure what you mean by minimize. If you want to hide your app and present the user with the homescreen you can use the following intent.
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
Although the Home button is more than sufficient if a user wants to hide your app
A: Try calling this moveTaskToBack(true); boolean.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: A simple facebook app gets Method Post is not allowed error I tried a very simple helloworld example facebook app. Basically I have a webpage, only contains one file index.php, which only contains one line: echo "helloworld". I have registered this app as an facebook app, configured the setting, canvas url to http://mydomain/..
I can load the page mydomain/index.php. However, when I load the page http://apps.facebook.com/appid, I got the following error:
The requested method POST is not allowed for the URL ...
I checked apache config, there is no or settings to prevent POST method.
Apache error log ad access log does not say anything.
Do you have any clue how to fix this?
Thanks for your kind help!
A: The first request a Facebook app makes is a POST request. It seems your server is not accepting them. A common problem is having something like:
http://mydomain.com/index.html
Instead of
http://mydomain.com/index.php
Either way check your HTTP logs you will probably see an error ( possibly 405 ) with more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What order does PHP read configuration from? PHP configuration can be made in a number of different places:
*
*php.ini
*httpd.conf
*.htaccess
*within a php script via ini_set()
*any more?
Some configuration settings can only be set in certain places and there's certain Apache and PHP settings that would prevent you from doing any PHP config changes in .htaccess or with your PHP script. But assuming that a given PHP setting can be set in all of the above places, in what order is this configuration read? In other words what overrides what? (I'm assuming that ini_set() overrides any of the previous settings).
A: There's compile-time settings before php.ini. The rest of the stages aren't really "configuration". They're more of a way to override settings established in a previous stage. PHP will quite happily run without any other config directives in php.ini/http.conf/.htaccess. php.ini does list (almost?) all the configuration settings available, but that's just a courtesy so you don't have to dig around in the docs to find the one setting you do want to override.
A: You named them in the correct order.
I don't recommend setting configuration in any other place than a php.ini though.
There are also per-directory php.ini configurations and I don't know which comes first, .htaccess or the directory php.ini but I would guess the .htaccess first and php.ini after.
A: Apache loads PHP, so Apache's config is read first. .htaccess is also handled by the webserver, so I'm guessing that will be second. Thirdly PHP is loaded. It checks for PHP.ini's in several locations. Also see here. Finally the ini_set is checked runtime.
A: First, You can use a user.ini file.
I think PHP will read it from the bigger to the smaller, I mean from httpd.conf -> php.ini (and then user.ini if set) -> .htacess -> ini_set()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Make a custom Eclipse builder conditional on the success of another builder I've added a custom builder to my Flex Builder 3 (Eclipse 3.4) project that uploads the built files to a test server for remote debugging, and my custom builder appears after the "Flex" builder in my project properties, and works great after a successful Flex build. However my custom builder runs all the time, even when there was an error in the Flex build. Is there some way I can make the custom builder only run if the main builder built successfully?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Firemonkey float key animation, goto a particular key In a Firemonkey 2d application, I'm using a float key to attempt to move a TLine control around a clock. I've added 60 key frames for the minute hand and 12 key frames for the hour hand (actually it's a lot more keys because I added one on position x, position y, height and width).
So, now I have two questions:
*
*How do I play to a key frame, then start at a key frame and go to the next key frame?
*How do I go to a particular key frame? (i.e. I load a form and I want to show the current time)
Note, I'm doing this just to learn more about Delphi XE2, not to solve any particular business solution.
A: I haven't tried it but.
You could use perhaps use TAnimations procedure
procedure ProcessTick(time, deltaTime: Single);
And call it right after you start your animation from scratch with a deltatime that will place you at the correct key.
Note that the function includes a time parameter too but that one seem to be ignored in code, otherwise you could probably use that to set the current time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to express (5 x 5.4 10-3) in objective-c I am trying to convert from meter to nautical miles.
I need to multiply meters by 5.4x10-3 but I am not sure how express this number in objective-c.
Any help would be greatly appreciated,
A: Like this:
double factor = 5.4e-3;
This means: 5.4 times 10 to the power -3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Optimizing a SQL Query for a Many to One Relationship I've got two tables with a many to one relationship which I'll call Parent_Table and Child_Table (i.e. a parent has zero or more children, but children have exactly one parent). I need to count the number of parents who have at least one child that fulfills some condition. Which query is optimal?
Option 1 (pretty sure it's not this one)
SELECT COUNT(DISTINCT(pt.ID))
FROM PARENT_TABLE pt
JOIN CHILD_TABLE ct
ON pt.ID = ct.PARENT_ID
WHERE <parent meets some condition>
AND <child meets some condition>
Option 2
SELECT COUNT(pt.ID)
FROM PARENT_TABLE pt
WHERE pt.ID in
(
SELECT ct.PARENT_ID
FROM CHILD_TABLE ct
WHERE <child meets condition>
)
AND <parent meets some condition>
Option 3 (my guess as the fastest)
SELECT COUNT(pt.ID)
FROM PARENT_TABLE pt
WHERE EXISTS
(
SELECT 1
FROM CHILD_TABLE ct
WHERE ct.PARENT_ID = pt.ID
AND <child meets condition>
)
AND <parent meets some condition>
Or is it something else entirely? Does it depend on the sizes of each table, or the complexity of the two conditions, or whether the data is sorted?
EDIT: Database is Oracle.
A: The first query is slow, the others should run fast on most DB's.
Without knowing the DB it's hard to say more:
But: count(*) is often faster than count(names_field) and never slower
count(distinct (afield)) is slow
Or is it something else entirely?
That depends on the DB and the exact version of the DB.
Does it depend on the sizes of each table
Yes, that plays a big part
or the complexity of the two conditions
Possible
or whether the data is sorted?
If you want a fast select, all fields used to join must be indexed.
And all fields used in a where clause must either be indexed or low-cardinality.
A: For me the first one seems the best since it's the easiest to read, but that obviously doesn't answer your question.
What you really have to do is generate execution plans for each of the queries and analyze them (I think most of the popular DBMS have a tool to do that). It will give you a cost value for each query.
If you can't do that I guess you could run the queries a bunch of times and compare the execution time.
Or is it something else entirely? Does it depend on the sizes of each table, or the complexity of the two conditions, or whether the data is sorted?
All of that and more.
A: Like the commenters say, the best way to answer this question is to run the queries and measure.
However, in general, database engines optimize joins very, very efficiently - I'm pretty sure you will find almost no difference between the 3 queries, and it's entirely possible the query optimizers will turn them all into the same basic query (2 and 3 are equivalent as it is).
By far the biggest impact on the query will be the "child meet some condition" and "parent meets some condition" clauses. I'd concentrate on optimizing this bit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Help building a list based on a enumeration I have an enumeration:
public enum SomeEnum
{
A = 2,
B = 4,
C = 8
D = 16
}
SomeEnum e1 = SomeEnum.A | SomeEnum.B
Now I want to have a List of enum values, so e1 would be:
2, 4
So I have:
List<int> list = new List<int>();
foreach(SomeEnum se in Enum.GetValues(typeof(SomeEnum)))
{
if(.....)
{
list.Add( (int)se );
}
}
I need help with the if statement above.
Update
How can I build a list of ints representing the flags set in the enum e1?
A: I suspect you want:
if ((e1 & se) != 0)
On the other hand, using Unconstrained Melody you could write:
foreach (SomeEnum se in Enums.GetValues<SomeEnum>())
{
if (se.HasAny(e1))
{
list.Add((int) se);
}
}
Or using LINQ:
List<int> list = Enums.GetValues<SomeEnum>()
.Where(se => se.HasAny(e1))
.Select(se => (int) se)
.ToList();
(It would be nice if you could use e1.GetFlags() or something to iterate over each bit in turn... will think about that for another release.)
A: Do you want to add the value if it's in e1?
Then you can use the HasFlag method in .NET 4.
if(e1.HasFlag(se))
{
list.Add( (int)se );
}
If you're not using .net the equivilant is e1 & se == se
Also by convention you should mark your enum with the FlagsAttribute and it should be in plural form (SomeEnums)
A: if((int)(e1 & se) > 0)
That should do it
A: this would work
if((int)se==(int)SomeEnum.A||(int)se==(int)SomeEnum.B )
{
list.Add( (int)se );
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make a iPhone tester in my site to report if sites are mobile adapted I would like to make a section on my site where users can test if their websites are mobile adapted.
Is any way to do that? I see a lot of sites in the net but I don't like to frame it, I'd like make my own.
Mmmm... the trouble is that link, shows me how can mobilize my site, but what I want to make, is a php/html section of my joomla, where users can input their webs, and shows if are adapted.
Something like this: www.iphonetester.com
But, that site, doesn't use the user agent, so, if you put http://www.kalyma.com.ar shows desktop version, instead of showing http://m.kalyma.com.ar which is the mobile version. (this is because I have a plugin which redirects the site based on user agent!)
A: Let me google that for you :
http://shaunmackey.com/articles/mobile/php-auto-bowser-detection/
A: Right... the only way I can think of (and this is untested...)
You need to curl the content of the page that someone's trying to access and set the useragent as such:
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C25 Safari/419.3');
Then you can output the html into a div on your page using jquery's load() function or similar.
You'll have to look into how to properly do it though, because you're downloading onto your web server any non-absolute links will have to have the base url set properly so images and other things work properly.
That's the only way I can think you can do it.
A: Try the code from Redrome.com. They show how to load the page properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Using data in an associative array as the object fo an event handler Afternoon All
I have some data -
var searchwithin = [
{id:"clearwithin", type:"button"},
{id:"search_radius", type:"select"},
{id:"for_lease" ,type:"checkbox"},
{id:"for_sale", type:"checkbox"},
];
It is going to be showing and hiding informtion dependent on what is clicked (this is only a small fragment of the data.
I have already worked out how to check the type property, what I want to know is the following:
If the type is button, how do I access the id value for that items and then generate a click function so that that uses the id as the name of the button to associate the function with.
Thanks in advance
Phil
A: Concatenate '#' and the id property and use the resulting string as a selector.
$.each($.grep(searchwithin, function(i) { return i.type=='button'; }),
function () {
var item = this;
$('#'+this.id).bind('click', function(e) {
alert('clicked: ' + item.id +' '+ item.type);
});
});
Consider using selectors to find elements rather than ID maps.
$('input[type="button"].search').bind('click', onSearch);
A: First, fix a syntax error in your searchwithin table by removing the comma after the last item in the table. That will cause an error in IE6/IE7.
Then, you can use this code to look through your searchwithin array to find the id for the appropriate type and then set a click event handler for that id.
var searchwithin = [
{id:"clearwithin", type:"button"},
{id:"search_radius", type:"select"},
{id:"for_lease" ,type:"checkbox"},
{id:"for_sale", type:"checkbox"}
];
function findIdByType(target) {
for (var i = 0; i < searchwithin.length; i++) {
if (searchwithin[i].type === target) {
return(searchwithin[i].id);
}
}
}
var id = findIdByType("button");
if (id) {
$("#" + id).click(function() {
// do whatever you want to do on the click function here
}
});
I notice that your table has two entries for type:checkbox. The above code suggestion will return and operate on the first entry only. If you want to set up click handlers for both those IDs, then either the code or table would have to be modified. If this is all the table is used for, it could be changed to be a selector (which can contain more than one id) like this:
var searchwithin = [
{id:"#clearwithin", type:"button"},
{id:"#search_radius", type:"select"},
{id:"#for_lease, #for_sale", type:"checkbox"}
];
function findSelectorByType(target) {
for (var i = 0; i < searchwithin.length; i++) {
if (searchwithin[i].type === target) {
return(searchwithin[i].id);
}
}
}
var selector = findSelectorByType("button");
if (selector) {
$(selector).click(function() {
// do whatever you want to do on the click function here
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does my MVC project throw exceptions on production servers after installing WebMatrix 2 Beta? After installing WebMatrix 2 Beta on my development machine, an MVC project compiled on that machine and deployed to a production server will start throwing a FileNotFoundException looking for System.Web.WebPages.
"...System.IO.FileNotFoundException: Could not load file or assembly 'System.Web.WebPages,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
The system cannot find the file specified. File name: 'System.Web.WebPages, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35'..."
I couldn't find anything on Google to help with this, so I am asking and answering this here for anyone else that runs into this situation. It is a fairly obscure set of circumstances that lead up to this problem.
If you have a fairly old MVC project that you have been upgrading over the various releases, you may have an unversioned project reference to System.Web.WebPages.
<Reference Include="System.Web.WebPages" />
This works fine as long as the version your project finds where compiled matches the version available where it is deployed.
Installing WebMatrix 2 Beta will add a new version of this DLL. Your MVC project will start pulling v2.0.0.0 for compilation. When you move to a system without WebMatrix 2 Beta installed, it will not be able to find v2 and will throw the above exception.
A: I spun up a new MVC 3 project and noticed that there are a couple references that are fully qualified in the new project and much more generic in the problem project.
<Reference Include="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
If you switch to these project references instead of the generic ones (<Reference Include="..." />), you will make sure the project is compiled with the expected version of the DLL rather than picking up the latest one available on the system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Matching everything but a specific word I've got this regex:
.*js/[\bpackaged\b]+\.js
At the moment it matches 'packaged.js' from the list below:
*
*js/foo.js
*js/bar.js
*js/suitcase.js
*js/bootstrap.js
*js/packaged.js
How can I invert this so that it matches all the others except for 'packaged.js'?
A: kent$ echo " js/foo.js
js/bar.js
js/suitcase.js
js/bootstrap.js
js/packaged.js
"|grep -P '.*js/.*(?<!packaged).js'
js/foo.js
js/bar.js
js/suitcase.js
js/bootstrap.js
the example is just showing the expression, if you really use grep, -v could make it easier.
--- updated based on glibdud's comment ---
notice the last 5 lines in input:
kent$ echo " js/foo.js
js/bar.js
js/suitcase.js
js/bootstrap.js
js/packaged.js
js/foo_packaged.js
js/packaged_bar.js
js/foo_packaged_bar.js
js/_packaged.js
js/packaged_.js"|grep -P '.*js/(.+packaged\.js|.+(?<!packaged)\.js)'
output:
js/foo.js
js/bar.js
js/suitcase.js
js/bootstrap.js
js/foo_packaged.js
js/packaged_bar.js
js/foo_packaged_bar.js
js/_packaged.js
js/packaged_.js
A: This does what you want:
.*js/(?!packaged\.js).+\.js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: get return from echo I'm working with some functions that echo output. But I need their return so I can use them in PHP.
This works (seemingly without a hitch) but I wonder, is there a better way?
function getEcho( $function ) {
$getEcho = '';
ob_start();
$function;
$getEcho = ob_get_clean();
return $getEcho;
}
Example:
//some echo function
function myEcho() {
echo '1';
}
//use getEcho to store echo as variable
$myvar = getEcho(myEcho()); // '1'
A: Your first code is correct. Can be shortened though.
function getEcho($function) {
ob_start();
$function;
return ob_get_clean();
}
echo getEcho($function);
A: Your first piece of code is the only way.
A: no, the only way i can think of to "catch" echo-statements it to use output-buffering like you already do. i'm using a very similar function in my code:
function return_echo($func) {
ob_start();
$func;
return ob_get_clean();
}
it's just 2 lines shorter and does exactly the same.
A: Did you write these functions? You can go 3 ways:
*
*Using your wrapper to do capturing via output buffering.
*Extra set of functions calls, wordpress style, so that "somefunc()" does direct output, and "get_somefunc()" returns the output instead
*Add an extra parameter to the functions to signal if they should output or return, much like print_r()'s flag.
A: function getEcho() {
ob_start();
myEcho();
return ob_get_clean();
}
$myvar = getEcho();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can XAML be used with JavaScript in WinRT? Or JavaScript is only restricted to HTML? I've only seen HTML-JavaScript demos at Build 2011
A: XAML is not supported in JavaScript Metro apps - those classes are specifically hidden from JavaScript WinRT projection.
This actually includes not just the stuff under Windows.UI.Xaml, but also some other classes elsewhere, usually when they do something that is already covered by JS standard library (with HTML5 extensions). The easiest way to see what exactly is hidden is to inspect WinRT .idl files (in "C:\Program Files (x86)\Windows Kits\8.0\Include\winrt") and search for webhosthidden. Those interfaces which have [webhosthidden] attribute applied to them are not visible from JS. Sometimes you'll also see comments explaining why a particular interface is hidden.
A: Not yet. XAML is used only from C# or C++, and for JavaScript you need HTML5.
One of reasons is that in case of HTML + JavaScript the same engine as in IE10 is used for rendering. (By the way, Metro version of IE10 doesn't support plugins like Silverlight.)
The other currently missing area is that you cannot use ASP.NET / ASP.NET MVC to build metro style applications, which would allow combining C# and HTML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: GPS on Android problem I have been trying for about 3 days to solve this problem and I haven't found a solution so far. I am trying to get my location through GPS.
It doesn't seem to receive the coordonates that I try to send through cmd.exe or the Emulator Control in the DDMS. Moreover, it restarts the emulator. The code that I have been trying is below. If someone can help me then please do because I don't find any solution to this problem. Thank you!
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class Check_Location extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText(location.getLongitude()+" "+location.getLatitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
Another method that I have tried and also didn't work is below:
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}/* End of Class MyLocationListener */
}
The permisssions set for both are:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"></uses-permission>
A: I managed to solve my problem. I have read on other forums. Both codes are working but try on an Android platform that is Less than level 10. For example make an emulator for level 8. It works!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Internal working of a vector in C++? Im working on an exercise in C++ but im getting unexpected output I hope someone can explain. The exercise asked that I make a class called rock which has a default constructor, a copy constructor and a destructor all of which announce themselves to cout.
In the main method I am to try and add members of this class to a vector by value:
vector<Rock> byValue;
Rock r1, r2, r3;
byValue.push_back(r1);
byValue.push_back(r2);
byValue.push_back(r3);
cout << "byValue populated\n\n";
The output I expected (and shown in the exercise solutions) is:
Rock()
Rock()
Rock()
Rock(const Rock&)
Rock(const Rock&)
Rock(const Rock&)
byValue populated
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
However the output I get is:
Rock()
Rock()
Rock()
Rock(const Rock&)
Rock(const Rock&)
Rock(const Rock&)
~Rock()
Rock(const Rock&)
Rock(const Rock&)
Rock(const Rock&)
~Rock()
~Rock()
byValue populated
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
~Rock()
Can anyone explain why there seems to be extra calls to the copy constructor and destructor?
A: When the vector gets resized, the elements have to be moved to their new location.
This is normal.
If you call
byValue.reserve(10);
before any calls to push_back, the extra copies should disappear.
A: A vector stores its elements contiguously. In order to avoid always re-allocating memory each time an element is inserted, it does allocate a bunch of memory. That is why vector has two methods regarding its "size": size() which tells the number of elements stored, and capacity() which indicates the amount of memory allocated.
Usually (but that is dependent on the STL implementation), it grows by doubling its precedent capacity. When it allocates more memory, and because data has to be stored contiguously (compared to a list), it has to move its internal data; and the STL copies data, which is why you have so many calls to the constructor/destructor.
If you know how many elements will be stored in your vector, you can use reserve to indicate how much memory it should allocated at first.
A: std::vector has a limited amount of memory to store elements. You can query just how much with capacity. You can also tell the vector to grab extra memory, with the reserve method.
When you push an element onto the vector and its capacity is zero (it has used up all of it extra memory) it allocates a new larger array and copies the elements from the original. That is where all the extra copies are coming from.
Looking at your output it looks like the vector had to grow twice. If you changed to code to call reserve before pushing anything the vector would never need to grow and there would be no extra copies.
Here is a verbose code snippet that shows how all of this comes together: ideone.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to model >1 ways of doing the same thing in event tables? Suppose there are >1 ways of doing something, in use case diagrams, I could use generalize, include, then in event table? Do I separate them?
Suppose "Buy Book" a customer could do it online or through the counter. In this case, I suppose the source is different? eg. "Buy Book Online" the "Customer" is the source interacting with the online system. Through the counter, its the "Cashier" interacting with the POS?
I suppose I separate these into different events in an event table?
A: First off, generalization is not usually used for use cases; <<extend>> is probably what you're after although it isn't quite the same.
Secondly, if there are multiple ways of doing the same thing, then that's a question for the design, not the analysis. The analysis deals what what the system will be used for, not the different ways it can achieve those goals.
Most importantly, however, in the example you mention you are in fact talking about two different systems. A use case represents an interaction between one or more actors and exactly one system.
A POS system for a book store might include a use case "Buy Book", involving the actors Cashier and Customer. A web system for an on-line book store might also include a use case "Buy Book" (involving just the Customer actor), but they just happen to have the same name and the same purpose.
The fact that an actual, physical person can shop for books both in stores and on-line has no bearing, because the focus of the analysis is on the system, not the actors.
In event tables, the source would be the same (Customer) and the event would be the same (Customer wants to buy book), but there would be two different tables and quite possibly two different documents, because we are talking about two different systems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JQuery show/hide panel on hover
Possible Duplicate:
JQuery slideToggle timeout
I have simple html page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("div").hide();
$("button").hover(function() {
$("div").slideDown("slow");
});
setTimeout(hidepanel, 4000);
function hidepanel() {
if ($('div').is(':hover') === false) {
$('div').slideUp();
}
}
$('div').mouseleave(function() { setTimeout(hidepanel, 4000); });
$('button').mouseleave(function() { setTimeout(hidepanel, 4000); });
});
</script>
<style>
div { width:400px; }
</style>
</head>
<body>
<button>Toggle</button>
<div style="border: 1px solid">
This is the paragraph to end all paragraphs. You
should feel <em>lucky</em> to have seen such a paragraph in
your life. Congratulations!
</div>
</body>
</html>
I need:
*
*Show the panel (div) while mouse cursor is over the button or over the panel (div)
*Hide panel when mouse is not over button or panel for 4 seconds
*Hide panel immediately when I click on the page on any place outside the panel or button.
What should I change im my code?
Thanks a lot!
A: http://jsfiddle.net/TQp9C/1/
The interesting part is hiding the panel when clicking outside of the panel/button.
$(document).click(function (e) {
if (e.target.id !== "btn" && e.target.id !== 'panel' && $(e.target).parents('#panel').length === 0)
{
hidepanel();
}
});
A: http://jsfiddle.net/AWM44/4/
Obviously, you'll want to be more specific with the selectors than "DIV" and "button" but you get the idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problems with an NHibernate LINQ query in loosely coupled project hope you can help!
I've started a project in MVC 3 and set the business domain model in another assembly, the interfaces define the contract between this assembly and all projects that will use it. I'm using Ninject to inject the dependencies into the project. I've hit a brick wall at the moment with a specific LINQ query.
public IEnumerable<ITheInterface> DoMyQuery()
{
using (ISession session = _sessionFactory.OpenSession()) {
var query = (
from c in session.Query<IMyInterface>()
where something == anotherthing
group c by new { c.TheGrouper } into grp
select new IMyInterface() {
Property = grp.Key
}
);
return query.ToList();
}
}
Now obviously I can't instantiate an interface, but this is my problem! The only way around it is to instantiate the concrete class, but that breaks my rules of being loosely coupled. Has anyone else ran into this before?
I suppose my question is, how do I use "select new Object" in a LINQ query by using the interface and NOT the concrete class?
Note: just for the record, even if I do use my concrete class to just get it to work, I get an NHibernate error of "Could not resolve property: Key of: "... but that's another issue.
Any help appreciated!!
A: Just using interfaces and DI container does not mean that you writing loosely coupled code. Interfaces should be used at application Seams, not for Entities:
A seam is a place where you can alter behaviour in your program
without editing in that place
From Mark Needham:
... we want to alter the way that code works in a specific context but we
don’t want to change it in that place since it needs to remain the way
it is when used in other contexts.
Entities (domain objects) are the core of your app. When you change them you change them in place. Building Seam around your data access code however is a very good idea. It is implemented using Repository pattern. Linq, ICreteria, HQL is just an implementation detail that is hidden from consumers behind domain driven repository interface. Once you expose one of these data access technologies your project will be coupled to them, and will be harder to test. Please take a look at these two articles and this and this answers:
*
*How To Write A Repository
*The Generic Repository
A: I believe the call session.Query<IMyInterface>() is invalid because NHibernate is not aware of your intention that "some mapped class (implemented somewhere) is the right class to query".
To stay loosely coupled (new operator is a dependency) you should use factory pattern (DAO objects) responsible for creating (querying) concrete entities you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ctypes and passing a by reference to a function I'm trying to use libpcap in python3 using ctypes.
given the following function in C
pcap_lookupnet(dev, &net, &mask, errbuf)
in python I have the following
pcap_lookupnet = pcap.pcap_lookupnet
mask = ctypes.c_uint32
net = ctypes.c_int32
if(pcap_lookupnet(dev,net,mask,errbuf) == -1):
print("Error could not get netmask for device {0}".format(errbuf))
sys.exit(0)
and the error i get is
File "./libpcap.py", line 63, in <module>
if(pcap_lookupnet(dev,net,mask,errbuf) == -1):
ctypes.ArgumentError: argument 2: <class 'TypeError'>: Don't know how to convert parameter 2
how do you deal with &blah values ?
A: You need to create instances for net and mask, and use byref to pass them.
mask = ctypes.c_uint32()
net = ctypes.c_int32()
pcap_lookupnet(dev, ctypes.byref(net), ctypes.byref(mask), errbuf)
A: You probably need to use ctypes.pointer, like this:
pcap_lookupnet(dev, ctypes.pointer(net), ctypes.pointer(mask), errbuf)
See the ctypes tutorial section on pointers for more information.
I'm assuming you've created ctypes proxies for the other arguments as well. If dev requires a string, for example, you can't simply pass in a Python string; you need to create a ctypes_wchar_p or something along those lines.
A: ctypes.c_uint32 is a type. You need an instance:
mask = ctypes.c_uint32()
net = ctypes.c_int32()
Then pass using ctypes.byref:
pcap_lookupnet(dev,ctypes.byref(mask),ctypes.byref(net),errbuf)
You can retrieve the value using mask.value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: iPhone - Get user interaction event and automatic logout In my iPhone app I want to logout the user if nothing happens till about 2 minutes (e.g. the user puts down the phone). Does anybody has such issue? What is the best way to implement this feature? I think I save the date of last event to NSUserDefaults, then on the next event first I check the current date. If the difference is larger than 2 minutes go to login screen, else refresh the stored date. But how can I get the touch event generally?
Thanks, madik
A: There's a method in UIApplicationDelegate for that:
- (void)applicationWillResignActive:(UIApplication *)application
{
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
Note that it also will be called when the app is going to background state. That will help you store the data whenever the app is going to inactive state. If you want to check if a certain amount of time has passed, you will have to use a NSTimer and store the last touch event. I think it cannot be done because you can't intercept all the touch events (Maybe it's over an object managed by the system. The status bar is an example). I guess is better to let the system to manage all the activity/inactivity stuff and store your data when necessary.
EDIT: I didn't understand what you mean the first time. Check this accepted answer, it accomplish what you need. Basically you have to subclass UIApplication and override sendEvent method.
A: 'NSTimer'
When you say "how can I get the touch event generally?", if you mean how can you tell if the user is idle or not, you'll have to set up some system to gather all touch events at a higher level in your app. You could update the last touch time you mentioned in NSUserDefaults but that may be inefficient during the run of the app, so you could just post the touch event to your main app delegate and have it save the time of last touch. Which would also be where you could set up the 2 minute timer.
Something like:
- (void) someAppDelegateMethodThatYouCallForAnyUserEvent
{
[self.idleTimer invalidate];
self.lastEvent = [NSDate now];
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(logoutAndGotoLogin) userInfo:nil repeats:NO];
...
}
You'll also have to do some cleanup in your app delegate methods when the app goes to background etc if you support that behavior.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deleting an aliased pointer Doing this:
union{
int * integer;
char * character;
} u;
u.integer = new int;
delete u.character;
u.integer = new int[5];
delete [] u.character;
I assume this wouldn't work if any of these types have non trivial destructors, but is this ok?
A: This doesn't work in any case, if we assume work means having well-defined behavior rather than appearing to work (i.e. not crashing)
A: No, this is undefined behavior regardless of whether or not the item has a trivial destructor. If the destructor is trivial it may appear to "work" when in fact it's leaking memory, etc.
A: I'm going to say this is somewhere between implementation defined and undefined.
5.3.5/2: "In the first alternative (delete object), the value of the
operand of delete may be ... a pointer to a
non-array object created by a previous new-expression ... .
The value of the pointer does not change when used the way you did so, so this should work as expected, provided sizeof(char*) == sizeof(int*). The result of that particular comparison is implementation defined, and if the assumption is false then the behavior is undefined.
So it really really isn't particularly safe.
A: It is easy to see this is a dangerous error. The two types might have completely different and incompatible ways of memory allocation and deallocation. This includes padding, garbage collection, bookkeeping, class-specific memory manipulation, etc. Just don't do it.
#include <cstddef>
#include <cstdlib>
#include <iostream>
using namespace std;
class A
{
public:
void* operator new (size_t size)
{
cout << "A::operator new (size_t)" << endl;
return malloc(size);
}
void* operator new [] (size_t size)
{
cout << "A::operator new [] (size_t)" << endl;
return malloc(size);
}
void operator delete (void* ptr)
{
cout << "A::operator delete (void*)" << endl;
free(ptr);
}
void operator delete [] (void* ptr)
{
cout << "A::operator delete [] (void*)" << endl;
free(ptr);
}
};
class B
{
public:
void* operator new (size_t size)
{
cout << "B::operator new (size_t) with some B-specific stuff" << endl;
return malloc(size);
}
void* operator new [] (size_t size)
{
cout << "B::operator new [] (size_t) with some B-specific stuff" << endl;
return malloc(size);
}
void operator delete (void* ptr)
{
cout << "B::operator delete (void*) with some B-specific stuff" << endl;
free(ptr);
}
void operator delete [] (void* ptr)
{
cout << "B::operator delete [] (void*) with some B-specific stuff" << endl;
free(ptr);
}
};
int main (int, char**)
{
union{
A* a;
B* b;
} u;
u.a = new A();
delete u.b;
u.a = new A[5];
delete [] u.b;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rspec controller test fails i'm trying to run such test:
it "render form to update an bundle with a specific id" do
bundle = mock_model(Bundle)
Bundle.stub!(:find).with("1") { bundle }
get :edit, :locale => "en", :id => 1
Bundle.should_receive(:find).with("1").and_return(bundle)
end
Code from a Controller:
class BundlesController < ApplicationController
# GET /bundles
# GET /bundles.json
.....
# GET /bundles/1/edit
def edit
@bundle = Bundle.find(params[:id])
end
.....
end
But test fails with message:
BundlesController Bundle update render form to update an bundle with a specific id
Failure/Error: Bundle.should_receive(:find).with("1").and_return(bundle)
().find("1")
expected: 1 time
received: 0 times
# ./spec/controllers/bundles_controller_spec.rb:60:in `block (3 levels) in '
Can anyone helps me?
Thanks!
A: There are a couple of problems here, and maybe more as you post more of your code.
First of all, you're setting up stubs and expectations on Bundle and then showing us code that loads a Role instead.
Second, you're calling #should_receive at the end of your test. This method sets up an expectation for code that comes after it in your test. Unless you have some hidden callback that you're not showing us, this is always going to fail. Reverse the order.
Bundle.should_receive(:find).with("1").and_return(bundle)
get :edit, :locale => "en", :id => 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to manage dates in shell I have a file containing 14000 dates . I wrote a script to find the last 5 days ,
26/03/2002:11:52:25
27/03/2002:11:52:25
29/03/2002:11:30:41
30/03/2002:11:30:41
26/03/2002:11:30:41
02/04/2002:11:30:41
03/04/2002:11:30:41
04/04/2002:11:30:41
05/04/2002:11:52:25
06/04/2002:11:52:25
suppose this is the file , now I have date 02/04/2002:11:30:41 as an out put . I want to put the dates from 02/04/2002 till the end of the file in another file .
start-date = 02/04/2002 (this is my start date)
while [start-date lt end-date] do (while start date is less than end date )
start-date++ ( add one day to start day so if its 2/4/2002 it will become 3/4/2002)
echo $start-date|tee -a file1 (put it in a file)
this code suppose to do so but it has problem ! why?
grep -n $SDATE thttpd.log | cut -d: -f1 (pattern=$SDATE)
sed '/$SDATE/=' thttpd.log
awk '/$SDATE/{ print NR }' thttpd.log
$ sed -n "$(awk '$SDATE/ { print NR }' input),$ p" thttpd.log
$ awk 'NR >= line_number' line_number=$(grep -n $SDATE -m 1 thttpd.log | cut -d: -f1) thttpd.log
A: Assuming that the file is sorted by date-time:
sed -n '\.^02/04/2002.,$p' dates.list > results.list
Prints from the first line starting with 02/04/2002 to the end of the file.
A: I haven't used it myself, but the gawk command (GNU's AWK) has the ability to manipulate date/time strings. And, gawk is the Linux version of the awk command.
You can also rewrite your whole program as a single awk script. That might make things a lot easier. Remember awk is a full blown programming language that simply assumes a read loop on the file and processes each line of a file.
A: programmatically, you can find the 5th last day like this:
startdate=$( cut -d: -f1 filename | sort -u -t/ -k3 -k2 -k1 | tail -5 | head -1 )
Then, you can print all days greater than or equal to this day:
awk -F: -v start="$startdate" '
BEGIN { split(start, s, "/"); sdate=s[3] s[2] s[1] }
{ split($1, d, "/"); if (d[3] d[2] d[1] >= sdate) print }
' filename
A: awk -F"/|:" '{print $3$2$1}' File_Name|sort -u| tail -5
A: I wrote a whole set of tools (dateutils) to tackle these kinds of problems. In your case it's simply:
dgrep -i '%d/%m/%Y:%H:%M:%S' '>=02/04/2002:11:30:41' < FILE
where the -i option specifies the input format and >=02/04/2002:11:30:41 is your cut-off date (>= means dates younger than the one specified of course).
A: Is this what you want?
#!/bin/bash
# presumes GNU date
# input date format won't be understood by GNU date
# reformat, then return date as seconds
reformat_date(){
year=$(cut -d/ -f3<<<$(cut -d : -f1 <<<"$1"))
month=$(cut -d/ -f2<<<$(cut -d : -f1 <<<"$1"))
day=$(cut -d/ -f1<<<$(cut -d : -f1 <<<"$1"))
hour=$(cut -d : -f2 <<<"$1")
min=$(cut -d : -f3 <<<"$1")
sec=$(cut -d : -f4 <<<"$1")
date +%s -d "$(printf '%s-%s-%s %s:%s:%s' "$year" "$month" "$day" "$hour" "$min" "$sec")"
}
from=$(reformat_date "$1")
flag=
while IFS= read -r d ; do
d_s=$(reformat_date "$d")
if [ -z $flag ] && [ $(expr "$d_s" - "$from") -gt 0 ] ; then
flag=1
fi
if [ ! -z $flag ] ; then
printf '%s\n' "$d"
fi
done < "$2"
Save as a script, pass your input date as the first argument and a filename to process as the second argument. Outputs lines from the file which appear after the first line to be later than the input date and time (including the first line).
So
./dates_from.sh '2/04/2002:11:30:41' dates.list > results.list
The pseudo-code you posted doesn't seem to do what the preceding sentence described, so I ignored it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How are GWT client side and server side deployed? I have a question related to the GWT deployment of client side and server side. I am wondering, are they deployed in the same computer? Or they can be deployed to different computers?
For example, on the client side, I need to upload a file. Can I just pass the URL of this file to the GWT server side, and read the data on the server side? For the moment, I am using FileUpload Widget, but this passes the inputstream of the file to the server side.
Thanks in advance!
A: Usually the client part of a GWT application - which is compiled to JavaScript - and the server part (e.g. Servlets which are called by the client part) are deployed to the same HTTP server. As a simple example this can be a Tomcat or Jetty.
When the user directs his browser to your GWT application, the client side part (the JavaScripts) are loaded via the hostpage and your GWT application is running inside the user's browser.
So if you want your users to be able to upload a file you have to use the FileUpload widget. It's the same as simple HTML form with an input field with type "file".
On the server side you have to deal with fileuploads separately. If you are using Java for the server side, I recommend the Apache FileUpload library. There is an excellent user guide on the project home page.
A: Your GWT client - static HTML, JS, CSS, and images - can be deployed to any HTTP server. If you use a Java backend, that needs to be deployed on a Java app server, such as Jetty. Those can be the same server software or different software, same hardware or different hardware.
Your question about file uploads is really orthogonal to your deployment strategy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Automatic form-positioning I want my application to have an auto form-positioning behaviour, similar to the WinAmp MP3 player. I'd like windows to stick to each other, so that if you move one window the other windows follow the movement. How can I do that?
I tried something like this.
if (this.Size.Width + this.Location.X >= 1270)
this.Location = new Point(1280 - this.Width, this.Location.Y); } //right x
if (this.Size.Height + this.Location.Y >= 750)
this.Location = new Point(this.Location.X, 760 - this.Width); } // bottom y
if (this.Location.X <= 5)
this.Location = new Point(0, this.Location.Y); } //left x
if (this.Location.Y <= 5)
this.Location = new Point(this.Location.X, 0); } // top y
A: May be using StartPosition property: FormStartPosition Enumeration
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Tablet connecting to smb and get a list of files im a complete noob to android and java but have wanted to learn for a while.
im trying to build a file browsing app which can view files and directories in a samba server or other file shares.
I'm trying to use uri.parse to initialize the uri of my samba server and then i want to convert the uri into a File type so i can essentially do file.list() to get a list of files/folders from the server.
heres what i found so far but im having issues with getting this running:
String[] list = null;
Uri uri = Uri.parse("smb://AG-24640/Users/Public/");
File file = new File(new URI(uri.toString()));
list = file.list();
Is there anything im doing wrong or is there an easier way of doing this? Is there anything i need to do to get the build of android to understand smb:// ?? im running android honeycomb 3.2
Thank you,
A: I don't think Android supports Samba/CIFS out of the box, you'll probably need to use a 3rd party java library like: http://jcifs.samba.org/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make javadoc comments in overriden methods visible I'm using Eclipse. I want the comments made in the overridden method to appear instead.
Here's an example -
enum Foo{
ITEM{
/**
* Arguments must be received in the following order...
*/
@Override
void bar(String[] args){...}
};
/**
* Bars the specific args
* @param args the specific args
*/
abstract void bar(String[] arags);
}
When I have something like the following Foo.ITEM.bar(...) and I hover over it, I want to read
Bars the specific args
Arguments must be received in the following order...
@args the specific args
Is this possible?
A: If I understand what you want correctly, this is what {@inheritDoc} is for. Place it in the comment body or appropriate tag to get the comment from the superclass/interface declaration.
Source and relevant excerpt:
Automatic Copying of Method Comments The Javadoc tool has the ability
to copy or "inherit" method comments in classes and interfaces under
the following two circumstances. Constructors, fields and nested
classes do not inherit doc comments.
Automatically inherit comment to fill in missing text - When a main
description, or @return, @param or @throws tag is missing from a
method comment, the Javadoc tool copies the corresponding main
description or tag comment from the method it overrides or implements
(if any), according to the algorithm below. More specifically, when a
@param tag for a particular parameter is missing, then the comment for
that parameter is copied from the method further up the inheritance
hierarchy. When a @throws tag for a particular exception is missing,
the @throws tag is copied only if that exception is declared.
This behavior contrasts with version 1.3 and earlier, where the
presence of any main description or tag would prevent all comments
from being inherited.
Explicitly inherit comment with {@inheritDoc} tag - Insert the inline
tag {@inheritDoc} in a method main description or @return, @param or
@throws tag comment -- the corresponding inherited main description or
tag comment is copied into that spot.
A: If it's an interface, add the javadoc to the interface, and then use the @Override tag, and it should show up.
A: I don't think you can really have Javadocs for individual enum constants' methods.
So, either put the important information into the general method (i.e. Foo.bar), or into the documentation of the individual constant (i.e. Foo.ITEM). The methods for the individual constants shouldn't be that different that they require individual comments anyways.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Logging boost::exception while avoiding file/line/function and the nagging In my in-house logging library, I am trying to change the custom exception class to derive from boost::exception instead of std::exception. I am doing this so that I can use a single catch block for both boost exceptions and my application exceptions. But I am running into an issue while logging it.
While logging the exception using boost::diagnostic_information(), I get the whole 9 yards about the throw location. This information is redundant for me since my custom class already collects and uses this info in a way I want. I don't want to print source code file/line/function info in the log.
If I define BOOST_EXCEPTION_DISABLE or don't use BOOST_THROW_EXCEPTION, it prints "Throw location unknown (consider using BOOST_THROW_EXCEPTION)" every time I log the exception.
But how do I escape this nagging?
A: Alright, I think I found the answer myself. First of all, I don't have to derive my class from boost::exception, I can still continue to derive from std::exception. However, I should throw my std::exception derived class using BOOST_THROW_EXCEPTION. So it becomes boost::exception as it takes off. :-)
In between, I can add more info if required by catching and rethrowing.
typedef boost::error_info<struct tag_errmsg, std::string> exceptionInfo;
catch (boost::exception &e)
{
e << exceptionInfo("some more exception data");
throw;
}
And then I can finally catch it and print it this way:
catch (boost::exception &e)
{
std::exception const * se = dynamic_cast<std::exception const *>(&e);
if(se)
{
// will enter here only for my application exception and not for pure boost exception
std::cout << "STD: " << se->what();
}
std::cout << " BOOST: " << *boost::get_error_info<exceptionInfo>(e); }
}
This way I will get both the what() string from std::exception and the error message from boost::exception. Am I on the right track?
A: Do not you want to use exception::what() instead of boost::diagnostic_information()?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What version of PHP was ReflectionClass introduced in? What version of PHP was ReflectionClass introduced in?
for example:
$objMetaData = new ReflectionClass('Direction');
$arrValidDirections = $objMetaData->getConstants();
A: According to the changes log for PHP5, the reflection API was introduced in the second beta of PHP 5.0.0.
i suppose that ReflectionClass was introduced in the same time, but I'm not sure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What account should I use when hosting WCF service in a Windows Service on Server 2008? OK, it seems like a simple thing, but I'm unfamiliar with the various accounts and privileges / roles each has.
I want to host my WCF services in a Windows Service on Server 2008 R2, and to do that I need to create an installer class. In there, when I instantiate a new ServiceProcessInstaller I need to specify the Account used to run the service. Given the choices are LocalSystem, LocalService, NetworkService and User, I am inclined to pick LocalService. Is this the right choice?
This is an internal application providing database access and some business logic, available from anywhere on our intranet but not visible to the outside world, if that makes any difference.
Thanks in advance for your comments or references to where this question has already been addressed.
Dave
A: Sometimes specific credentials are required if certain privileges are going to be executed by service operations that require authentication for file system locations etc, however if no such permissions are required, you should use Network Service.
The NetworkService account is a predefined local account used by the service control manager. It has minimum privileges on the local computer and acts as the computer on the network.
From Microsoft's example on hosting a WCF service in a Windows Service, they also use Network Service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL next row in sequence I have a query like this:
SELECT id, name, town, street, number, number_addition, telephone
FROM clients
WHERE ((postalcode >= 'AABB' AND postalcode <= 'AACC') OR (postalcode >= 'DDEE' AND postalcode <= 'DDFF'))
ORDER BY town ASC, street ASC, number ASC, number_addition ASC
LIMIT 1
This way I can get first client.
Then I want to get next client (let's say I know that my current client has ID 58 and I want to get next client in the sequence - I'll have one client that's tagged as current and I want to get next/previous) and I already know ID of first client, can you please give me a hint how to achieve this? (With the same ordering)
I found this http://www.artfulsoftware.com/infotree/queries.php#75 but I dont know how to transform these examples to the command when I need to order by multiple columns.
Thanks for your time.
A: You can use the two values of LIMIT X,Y, where X is the offset and Y is the number of rows. See this for info.
That will, however, make your list order every time you query for just one row. There are different ways to do this.
What you could do is get a good portion of that list, maybe as much as is practical for you (say maybe 20, it depends). Keep the result in an array in your program, and itterate through those. If you need more, just query again with an offset. The same way a forum will show only a certain quantity of posts in each page on a search.
Another approach is to get all the client IDs you need, keep that in an array, and query for each one at a time.
A: SELECT
c1.id, c1.name, c1.town, c1.street, c1.number, c1.number_addition, c1.telephone
FROM clients c1
INNER JOIN clients c2
ON (c1.town,c1.street,c1.number,c1.number_addition) >
(c2.town,c2.street,c2.number,c2.number_addition)
WHERE ((c1.postalcode BETWEEN 'AABB' AND 'AACC')
OR (c1.postalcode BETWEEN 'DDEE' AND 'DDFF'))
AND c2.id = '$previous_id'
ORDER BY c1.town, c1.street, c1.number, c1.number_addition
LIMIT 1 -- OFFSET 0
Here it is assumed that id is the primary key for this table.
You need to add the id to the select list, or you will not know the id to put in $previous_id for the next one in line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: no callbacks work with my new universal app I believe that I did everything necessary to change my app for ipad (was for iphone at start). I can toggle the build status to either iphone (only), ipad (only) or iphone/ipad - and the app launches either in ipad or iphone simulator. I can do that forth and back at will (I am saying this because I had no questions from xcode asking me to "upgrade to ipad" and have no new "mainwindowxib-ipad" like I read somewhere...)
I added the idiom to check for ipad and basically for one of my xib, instead of using the string of my xib to create the controller, I use the one for the ipad. So it is a new xib for ipad with all same graphical objects ( enlarged ;-) ) . I added the callbacks to function correctly with IB.
I can see everything fine and arrive on my new ipad view BUT when I click on a button... nothing happened like if my callbacks don't work. It is very surprising and actually I have no idea where to look as I compared most of the parameters between my iphone and ipad view and they are identical as far as I can see.
It must be something damn obvious so if one of you had the same issue and it was a very simple answer ... I guess that would be what I missed!
Thanks for your help in advance
Cheers,
geebee
A: this issue was caused because of that : answer in that post:
2 XIB and 1 viewcontroller but functions don't work in the ipad XIB
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sort product listings in Spree based on created_at I'm using spree and I want to sort product listing based on created_at of the product.
I tried to find the way to override the spree default scope under lib/scopes/product.rb but couldn't find it.
I want to list recently created products on public panel. How can I do it with spree?
A: First answer will break admin panel product edition and maybe other stuff in spree 1.1-stable.
ambiguous column name: created_at
You may fix this by specifying the table name with :
Product.class_eval do
default_scope order("spree_products.created_at DESC")
end
But I think best solution would be to patch the public products controller or view, not the model itself as the default_scope may not be expected everywhere and to switch/remove an order defined in a default_scope you must call .reorder()
Probably because of this, SpreeCommerce documentation specifically do not recommend you add order in product scopes :
Source : http://guides.spreecommerce.com/scopes_and_groups.html#modifying-available-scopes
So I think the proper way of doing this without screwing the Spree core product model is to overwrite the products template :
Overwrite views/spree/shared/_products.html.rb
replace
<% products.each do |product| %>
with
<% products.descend_by_updated_at.each do |product| %>
Source : https://groups.google.com/forum/#!topic/spree-user/lW5sGsbMTfM
Works for me™
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Inverse black and white / monochrome bitmapdata in AS3 I'm wondering if there are any nice ways of inversing a black and white / monochrome bitmapdata in AS3 which don't involve going through and setting each pixel by pixel?
A: There's also another solution. Every display object has a blendMode property and has the capability to alter the color of the background objects according to that blend mode. All you have to do is to cover the bitmap object with another display object and set its blend mode. It works pretty similar to masks but applies to color instead of shape.
colorCoverObject.blendMode = BlendMode.INVERT;
The colorCoverObject should be a transparent object.
A: Look up bitmapData.colorTransform() [docs] and the ColorTransform class [docs]
You'll probably want to apply something like:
var bd:BitmapData;
var invertTransform:ColorTransform = new ColorTransform(-1,-1,-1,1,255,255,255,0)
db.colorTransform(db.rect, invertTransform)
Which will multiply each pixel by -1 and then add 255. so 255 will become 0 and 0 will become 255.
A: For ActionScript 2.0:
colorCoverObject.blendMode="invert";
The movie clips behind the colorCoverObject displayin inverted color.
A: for monochrome effect i just created a tutorial below
the preview of monochrome effect:
required:
*
*understanding Bitmap and Bitmap data
what is threshold
This adjustment takes all the pixels in an image
and…pushes them to either pure white or pure black
what we have to do
here is a Live Demo of this example with some additional
changes like using a UI to changing threshold level in runtime.
threshold in action script 3
from as3 official documentation
Tests pixel values in an image against a specified threshold and sets
pixels that pass the test to new color values. Using the threshold()
method, you can isolate and replace color ranges in an image and
perform other logical operations on image pixels.
The threshold() method's test logic is as follows:
*
*If ((pixelValue & mask) operation (threshold & mask)), then set the
pixel to color;
*Otherwise, if copySource == true, then set the pixel to
corresponding pixel value from sourceBitmap.
i just commented the following code with exactly names as quoted description.
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import flash.geom.Point;
var bmd:BitmapData = new wildcat(); // instantied a bitmapdata from library a wildcat
var bmp:Bitmap = new Bitmap(bmd); // our display object to previewing bitmapdata on stage
addChild(bmp);
monochrome(bmd); // invoking threshold function
/**
@param bmd, input bitmapData that should be monochromed
*/
function monochrome(bmd:BitmapData):void {
var bmd_copy:BitmapData = bmd.clone(); // holding a pure copy of bitmapdata for comparation steps
// this is our "threshold" in description above, source pixels will be compared with this value
var level:uint = 0xFFAAAAAA; // #AARRGGBB. in this case i used RGB(170,170,170) with an alpha of 1. its not median but standard
// A rectangle that defines the area of the source image to use as input.
var rect:Rectangle = new Rectangle(0,0,bmd.width,bmd.height);
// The point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle.
var dest:Point = new Point();
// thresholding will be done in two section
// the last argument is "mask", which exists in both sides of comparation
// first, modifying pixels which passed comparation and setting them all with "color" white (0xFFFFFFFF)
bmd.bitmapData.threshold(bmd_copy, rect, dest, ">", level, 0xFFFFFFFF, 0xFFFFFFFF);
// then, remaining pixels and make them all with "color" black (0xFF000000)
bmd.bitmapData.threshold(bmd_copy, rect, dest, "<=", level, 0xFF000000, 0xFFFFFFFF);
// Note: as we have no alpha channel in our default BitmapData (pixelValue), we left it to its full value, a white mask (0xffffffff)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: with out dead php script I wanna run one php script by while(true){ }.
It will get pm which has been sent to me by other and answer them.(something like yahoo robot)
now if I set set_time_limit(0) and use while(true) and run this page on my server http://ip-address/yahoo.php and close my browser , Is it running for ever?
A: No, it's not running forever, script is terminated once you close your browser. Your whole approach is wrong, you create a daemon that runs in the background listening on a socket, it doesn't run while(true) because that's CPU cycle waste, a huge one at that.
Research about websockets and node.js, it sounds like you need similar to what's been created already.
A: ignore_user_abort(true) will probably do it
ignore_user_abort — Set whether a client disconnect should abort script execution
A: This is not a good idea to do it this way, and should not work.
You'd better run the script from within a shell and background it or run it in a screen.
A: No.
If you want a script to run forever run it in terminal (or Command Prompt).
If you close the terminal script will also stop.
A: Try php cli, so you can run php over your Command line.
Than you can create a Bash File which starts it, and so the Script will run "forever".
But if you start it over the Browser it will not run forever.
A: No, PHP only exists as long as the request does. If you close you're browser the request will die as well.
[edit]
As other commenters clarified the ignore_user_abort function could help you out though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java coding convention about static method It is a very simple question, but I think it is a little bit controversial.
When I code Java classes I use the following order.
class Foo {
// static fields
// instance fields
// constructors
// methods (non-static and static methods are mixed but sorted based on their functionalities)
}
I read an article that says:
(From http://code.google.com/webtoolkit/makinggwtbetter.html#codestyle)
Java types should have the following member order:
Nested Types (mixing inner and static classes is okay)
Static Fields
Static Initializers
Static Methods
Instance Fields
Instance Initializers
Constructors
Instance Methods
If I follow the article, the order above should be
class Foo {
// static fields
// static methods
// instance fields
// constructors
// instance methods
}
In the case of the latter, I feel uncomfortable having some methods before constructors.
Which one is the more widely-used convention?
A: Personally I use option 2 (static fields and methods prior to instance elements and constructs). To me this makes sense when scanning a file because from a user of a class, I can access the static stuff without needing an instance. Therefore it is nice to see them prior to the constructors because I don't care about constructors when using static stuff.
A: Just for the record, this is from the GWT article you linked:
We acknowledge that plenty of great approaches exist out there. We're simply trying to pick one that is at least somewhat consistent with Sun's Java coding conventions...
So the style they use
*
*is proposed for GWT not for general usage
*deviates somewhat from the standard conventions
*is acknowledged to be one of many good standards
So I'd say, if there's no reason not to stick with your current conventions, why change them?
A: I believe Sun's (now Oracle's) Java coding standards are more widely used. This is what you are currently using too.
From Code Conventions for the Java TM Programming Language :
3.1.3 Class and Interface Declarations
The following table describes the parts of a class or interface declaration, in the order that they
should appear.
*
*Class/interface documentation comment ( /*.../)
*class or interface statement
*Class/interface implementation comment ( /.../), if necessary
*Class (static) variables
*Instance variables
*Constructors
*Methods
A: The Java Code Conventions suggest the following (which is basically what you already do):
*
*Class (static) variables: First the public class variables, then the protected, then package level (no access modifier), and then the private
*Instance variables: First public, then protected, then package level (no access modifier), and then private
*Constructors
*Methods: These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.
A: I don't know, but for what it's worth, I do what you do. Constructors on top, methods grouped by functionality (with no regard to staticness) below. Static methods tend to group.
The exception is static factory methods that I intend for you to use instead of constructors -- if so, they are before constructors, and the ctors are private/protected.
A: It's all a matter of preference, of course...
Your convention is more consistent with the default ordering in Javadoc (i.e. static and non-static methods mixed together). This is what I normally do, too.
However, inner classes are often placed at the bottom of a class as they are often 'secondary' or 'helper' classes, and it seems odd to put them before the main meat of the outer class.
A: I put static initializers and methods before constructors, so I guess I'm following your citation.
Why the discomfort? It seems like a small thing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Struts2 Form Submit error When i call an action through form i am getting the following error.
No result defined for action com.______.actions.UserAction and result input
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:375)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:277)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
I am getting this error in invocation.invoke()
If i hit the action through URL it is working fine.
Please help...
Here's the relevant struts.xml fragment:
<action name="*Link" method="{1}" class="com.______.actions.UserAction">
<interceptor-ref name="loggingStack"></interceptor-ref>
<result name="userInfo" type="tiles">userInfo</result>
<result name="sessionout" type="tiles">sessionOut</result>
</action>
if i remove <interceptor-ref name="loggingStack"></interceptor-ref> it work's fine.
A: The above issue has been solved?
In my action class i was using ArrayList<Integer> where as my form submiting String.
I changed ArrayList<Integer> to ArrayList<String>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.