text stringlengths 8 267k | meta dict |
|---|---|
Q: Equivalent of this SQL query in LINQ using Lambda What is the correct lambda syntax for the following query?
SELECT a.Title, Count(b.Id) FROM a INNER JOIN b on a.Id = b.FK_Id GROUP BY a.Title
I know how to use join, but don't have any idea how to use aggregate and group by in this situation.
Thank you.
A: Looks to me like:
var query = from a in TableA
join b in TableB on a.Id equals b.FkId
group b by a.Title into g
select new { Title = g.Key, Count = g.Count() };
Or in non-query syntax:
var query = TableA.Join(TableB, a => a.Id, b => b.FkId, (a, b) => new { a, b })
.GroupBy(z => z.a.Title, z => z.b)
.Select(g => new { Title = g.Key, Count = g.Count() });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I compose a function that has an implicit argument? I'm playing around with higher kinds, and I'm trying to use compose. I've got the following code:
def p2( a : Int) = a + 2
def p3( a : Int) = a + 3
val p5 = p2 _ compose p3
def pn3[T](n : T)(implicit ev : Numeric[T]) = ev.plus(n, ev.fromInt(3))
val pn5 = p2 _ compose pn3
It all works until the last line:
error: could not find implicit value for parameter ev: Numeric[T]
Which makes sense but how do I tell it, "I want Numeric[Int]!"
A: Trial and error ;)
val pn5 = p2 _ compose pn3[Int]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: ASP.NET MVC: How to show a specific view as result of failed authorization in IAuthorizationFilter I have IAuthorizationFilter filter that checks for specific roles. In case user doesn't have specified roles, I'd like to show a specific view that says something along the lines of "You don't have privileges to view this page".
I'd also like to show this view on specific url, so redirect is not an option.
Here is what I want:
1) User goes to /Admin/Payments
2) /Admin/Payments requires Admin rights
3) User is not an admin.
4) User is show page that says that he cannot access this page, yet url is /Admin/Payments
Thanks.
A: public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
// TODO: do your authorization or if you want to keep the default
// simlpy invoke the base method
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/Unauthorized.cshtml"
};
}
}
and then:
[MyAuthorize(Roles = "Admin")]
public ActionResult Payments()
{
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: vb.net 2003 Arraylist of structure which have an arraylist I have two structures
Public Structure myResearchData
Public batchName As String
Public arraylistRData As ArrayList
End Structure
Public Structure myResearchSubData
Public researchDescription As String
Public recordingDate As Date
Public book As String
Public page As String
Public year As String
Public fee As String
End Structure
I initialize them in a sub
Dim MyResearchDataAList As New ArrayList
Dim MyResearchData As myResearchData
MyResearchData.arraylistRData = New ArrayList
Dim MyResearchSubData As myResearchSubData
I have an arraylist of myResearchSubData which is MyResearchData.arraylistRData and added it inside MyResearchDataAList. But when I cleared MyResearchData.arraylistRData the arraylist inside MyResearchDataAList is also cleared. I thought that once it is added to MyResearchDataAList it will hold the arraylist but it is also clered. Below is the process that I have done.
MyResearchSubData.recordingDate = Date.Parse(Date)
MyResearchSubData.book = Book
MyResearchSubData.page = Page
MyResearchSubData.year = Year
MyResearchSubData.fee = Fee
Put data in the structure of MyResearchSubData
MyResearchData.arraylistRData.Add(MyResearchSubData)
Added it in MyResearchData.arraylistRData
MyResearchDataAList.Add(MyResearchData)
Added it in MyResearchDataAList
MyResearchData.arraylistRData.Clear()
Cleared MyResearchData.arraylistRData for new data to be put in but it also clears the arraylist inside MyResearchDataAList and didn't old the contents of the arraylist
Thanks in advance for those who can help me with this problem
A: That is happening because it is actually the same items being added to the array list, as they are added by reference. You want to actually add a COPY of each item to your arrayList.
I generally find the easiest way to do something like that is to add a clone of the object during a loop.
To do that you may need to implement ICloneable to get the proper copy. At the level of the myResearchSubData however, it appears that you can just use the memberwiseClone Method.
If you change the to a class instead of a structure you can use the clone like this:
Public Class myResearchSubData
Implements ICloneable
Public researchDescription As String
Public recordingDate As Date
Public book As String
Public page As String
Public year As String
Public fee As String
Public Function Clone() As Object Implements System.ICloneable.Clone
Return Me.MemberwiseClone
End Function
End Class
Then you would want to loop through your original list of myResearchSubData and add its clone to the second list. Something like:
For Each item as myResearchSubData in MyResearchData.arraylistRData
MyResearchDataAList.Add(CType(item.Clone, myResearchSubData))
Next
If you want to continue to use the structures then I would use the same loop type and make a function that creates a new myResearchSubData and copies the data from the original over to the new one.
For Each item as myResearchSubData in MyResearchData.arraylistRData
MyResearchDataAList.Add(CloneStructure(item))
Next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Moving from Flash to HTML5/CSS/ etc Some years ago I decided I could bypass all the browser inconsistencies by producing sites entirely in Flash. Doesn't look such a good decision now so I'm re-writing my semi-CMS framework in php, javascript/jQuery and HTML. One aspect of my Flash sites which I am very pleased with is the ability to load all pages or states in the background so the user rarely requests a page that isn't already loaded. When that does happen I can display a progress bar. In AJAX I can't display progress but I also found a significant difference I hadn't anticipated. In Flash I load the .swf for page 1 completely, before starting to load page 2. That means everything including images etc. In AJAX I can't see a way to do that. I can check that the HTML file itself has completed loading, but not that all its images have loaded before loading the next HTML file. Is it possible?
A: If you're looking for an HTML5 solution rather than just an AJAX solution you might want to investigate the Application Cache. There is a progress event which you could hook into, though it possibly doesn't get into the level of detail you need. As far as I'm aware, resources will start downloading in the order they're listed in the manifest file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Excel VBA: Variants in Array Variables A question on variants. Im aware that variants in Excel vba are both the default data type and also inefficient (from the viewpoint of overuse in large apps). However, I regularly use them for storing data in arrays that have multiple data types. A current project I am working on is essentially a task that requires massive optimistaion of very poor code (c.7000 lines)- and it got me thinking; is there a way around this?
To explain; the code frequently stores data in array variables. So consider a dataset of 10 columns by 10000. The columns are multiple different data types (string, double, integers, dates,etc). Assuming I want to store these in an array, I would usually;
dim myDataSet(10,10000) as variant
But, my knowledge says that this will be really inefficient with the code evaluating each item to determine what data type it is (when in practise I know what Im expecting). Plus, I lose the control that dimensioning individual data types gives me. So, (assuming the first 6 are strings, the next 4 doubles for ease of explaining the point), I could;
dim myDSstrings(6,10000) as string
dim myDSdoubles(4,10000) as double
This gives me back the control and efficiency- but is also a bit clunky (in practise the types are mixed and different- and I end up having an odd number of elements in each one, and end up having to assign them individually in the code- rather than on mass). So, its a case of;
myDSstrings(1,r) = cells(r,1)
myDSdoubles(2,r) = cells(r,2)
myDSstrings(2,r) = cells(r,3)
myDSstrings(3,r) = cells(r,4)
myDSdoubles(3,r) = cells(r,5)
..etc...
Which is a lot more ugly than;
myDataSet(c,r) = cells(r,c)
So- it got me thinking- I must be missing something here. What is the optimal way for storing an array of different data types? Or, assuming there is no way of doing it- what would be best coding-practise for storing an array of mixed data-types?
A: I'm not sure your bottleneck comes from the Variant typing of your array.
By the way, to set values from an array to an Excel range, you should use (in Excel 8 or higher):
Range("A1:B2") = myArray
On previous versions, you should use the following code:
Sub SuperBlastArrayToSheet(TheArray As Variant, TheRange As Range)
With TheRange.Parent.Parent 'the workbook the range is in
.Names.Add Name:="wstempdata", RefersToR1C1:=TheArray
With TheRange
.FormulaArray = "=wstempdata"
.Copy
.PasteSpecial Paste:=xlValues
End With
.Names("wstempdata").Delete
End With
End Sub
from this source that you should read for VBA optimization.
Yet, you should profile your app to see where your bottlenecks are. See this question from Issun to help you benchmark your code.
A: Never optimize your code without measuring first. You'll might be surprised where the code is the slowest. I use the PerfMon utility from Professional Excel Development, but you can roll your own also.
Reading and writing to and from Excel Ranges is a big time sink. Even though Variants can waste a lot of memory, this
Dim vaRange as Variant
vaRange = Sheet1.Range("A1:E10000").Value
'do something to the array
Sheet1.Range("A1:E10000").Value = vaRange
is generally faster than looping through rows and cells.
My preferred method for using arrays with multiple data types is to not use arrays at all. Rather, I'll use a custom class module and create properties for the elements. That's not necessarily a performance boost, but it makes the code much easier to write and read.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: BLAST Database allocation error I asked this question on the bioinformatics version of stackexchange, but since I think it is a computer problem I thought I should try my luck here.
When running local BLAST (v2.2.24+) on a big database (all human proteins) I get the following error:
proteinsApplicationError: Command 'blast-2.2.24+/bin/blastp.exe -query "query.fasta" -
db "human-proteins.fasta" -out blastOutput.xml -evalue 0.01 -outfmt 5'
returned non-zero exit status 2, 'BLAST Database error: CSeqDBAtlas::MapMmap:
While mapping file [human-proteins.fasta.psq] with 5550749 bytes allocated, caught
exception:'
When googling I only got to the source code of seqdbatlas: http://www.ncbi.nlm.nih.gov/IEB/ToolBox/CPP_DOC/lxr/source/src/objtools/blast/seqdb_reader/seqdbatlas.cpp in which I found:
1214 if (expt.length()) {
1215 // For now, if I can't memory map the file, I'll revert to
1216 // the old way: malloc a chunk of core and copy the data
1217 // into it.
1218
1219 if (expt.find(": Cannot allocate memory") == expt.npos) {
1220 expt = string("CSeqDBAtlas::MapMmap: While mapping file [") +
(*m_Fname) + "] with " +
1221 NStr::UInt8ToString(atlas->GetCurrentAllocationTotal()) +
1222 " bytes allocated, caught exception:" + expt;
1223
1224 SeqDB_ThrowException(CSeqDBException::eFileErr, expt);
1225 }
1226 }
My knowledge of C++ is limited, but what I get from this is that there isn't enough memory on the PC to run BLAST over that size of a database. Is this correct and if so, is there a way to run this BLAST without getting a computer with a bigger memory? If it's not correct, what is the error that I'm getting?
Thanks in advance, Niek
A: Fixed it by breaking the query file up in two and using blast 2.2.25 instead of 2.2.24
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: LINQ to SQL vs. Enterprise Library I have 1 million records inserted per day. My front end is C# 4.0 and my back end is MS SQL Server 2008 R2.
What method should I use to gain the best performance? Should I use LINQ To SQL or Enterprise Library 5.0 or something else?
A: If you're going to be inserting that many rows into a database, you should consider using SQL Server Bulk Insert. It was designed to handle these kinds of loads. I love Linq to SQL, but it won't handle this sort of load too well.
A: Is that 1 million in one batch, or a million times 1 record at a time?
If you are looking for batch, you can forget about Linq2sql with these kind of volumes. Have a look at the SqlBulkCopy class, that is magnitues faster.
So you can opt for a hybrid solution - use SqlBulkCopy for your batch and you can still use linq2sql for queries and CRUD actions on single entities (or small batches).
It it is only one record at a time distributed evenly, i think you will still manage with Linq2sql.
A: I agree with the others on how to do batch operations, however I would not suggest LINQ to SQL at all. Use Entity Framework instead. It is much more flexible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Action and Action Parameters in Controller.OnException We're using the OnException virtual method in BaseController to log our exception.
But how can we get the controller action and parameters that the exception originated from?
A: You can get all these data from ExceptionContext object.
For example using this code you can get controller, action and all other routing parameters:
context.RouteData.Values
Using this code you can get query string parameters:
context.HttpContext.Request.QueryString
And finnaly form parameters:
context.HttpContext.Request.Form
A: protected override void OnException(ExceptionContext filterContext)
{
string action = filterContext.RouteData.Values["action"].ToString();
string controller = filterContext.RouteData.Values["controller"].ToString();
}
A: As far as Action Parameters go, you will need to pass them explicitly.
We don't provide the action arguments on ExceptionContext because it would most often be empty.
Source: https://github.com/aspnet/Mvc/issues/6154
Which is stupid IMO.
UPDATE: You could have your error handler class implement ActionFilterAttribute, which implements:
public virtual void OnActionExecuting(ActionExecutingContext filterContext)
where filterContext.ActionParameters are what you are looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Problem with putting in the right parameters I have problem with putting in the right parameters from an eventListener into a function.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
images[0][i].addEventListener('click', function() {showImage(this)
}, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage( here is the problem ) {
var preview = document.getElementById('preview');
preview.innerhtml = image.innerhtml;
// I want to put the image into the preview element.
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams</div>
<div>trams</div>
<div>trams</div>
<div>trams</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
A: Try this code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var images = galleryContainer.getElementsByTagName('div');
//console.log(images);
for(var i = 0; i < images.length; i++) {
images[i].addEventListener('click', showImage, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage(ev) {
ev=ev||event; // ev now point to click event object
var preview = document.getElementById('preview');
preview.innerHTML = this.innerHTML; // this point to DIV(trams)
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams1</div>
<div>trams2</div>
<div>trams3</div>
<div>trams4</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
Working example http://jsfiddle.net/Cp6HJ/
A: window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
var callback = function(item){ return function(){ showImage(item); }; }(images[0][i]);
images[0][i].addEventListener('click', callback, false);
};
};
function showImage( item ) {
var preview = document.getElementById('preview');
preview.innerHTML = item.innerHTML;
}
A: Use this for the function definition statement :
function showImage(image) {
...
}
And correction in the inner html statement:
(note the capitalized 'H')
preview.innerHTML = image.innerHTML;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to avoid duplicate entries of a record when Exporting SQL server data to an Excel in C#? I have requirement to export SQL Script data to an excel using C#.Net.
Currently I face issue in avoiding duplicat values for columns, when a record has multiple values for a column it should look like as in the bellow, the entire record should not repeated for each values of the column.
should I handle it in application level or in Sql script. please advice me.
Currently I get data set and bind it to a grid view and then do the export to excel function.
for example Sql Data could be
select B.BID, B.BName, M.Year
from tbl_B B
inner join tbl_Master M ON B.BID = fm.BIDFK
where B.BName = 'B9'
Group By B.BID, B.BName, M.Year
And the Result
A: I have cleared out this issue on C# side, I use nested grid-view to bind multiple valued columns for a record, when exporting to excel clear controls inside the parent grid-view to export data from all grid-view.
A: I think it need to be done in SQL script.
It's not complicated logic to apply .
A: I would seriously look at using the Report Viewer control and a local report rather than trying to build the Excel sheet by hand. Check out GotReportViewer.com and the examples on the right cover exporting to Excel, and using the control from a console application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Visual Studio 11 Developer Preview - Breaking FxCop Static Analysis After installing the Developer Preview our Custom FxCop rules project won't build as the following Dll's can't be found:
FxCopSdk.dll & Microsoft.Cci.dll
It turns out that this is a red herring, looking at the project for the custom rules on other's machines, it doesn't build without re-referencing the aforementioned dll's correctly (so that's normal) the real problem is that our existing build is using the VS11 code analysis.
I've now removed VS11 but it's still not working!
Any ideas?
Update:
Since installing vs11 my build batch is defaulting to the VS11 version, this isn't happening on other who have installed the preview [and they are also using x64 windows 7]
A: I've seen problems with VS2012 interfering with VS2010 on a few machines so far it's been easy to flatten the machine and rebuild from scratch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to change TTNavigator (for a web url) bottom bar color? Here is a code i made to open a website via TTNavigator-
- (IBAction)btnTemp_Click{
TTNavigator* navigator = [TTNavigator navigator];
navigator.supportsShakeToReload = YES;
navigator.persistenceMode = TTNavigatorPersistenceModeAll;
[navigator openURLAction:[[TTURLAction actionWithURLPath:@"http://www.google.com"] applyAnimated:YES]];
}
and here i was able to manage its navigation bar items, color etc-
- (void)addSubcontroller:(UIViewController *)controller animated:(BOOL)animated transition:(UIViewAnimationTransition)transition
{
[self.navigationController addSubcontroller:controller animated:animated transition:transition];
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
[btnBack setImage:[UIImage imageNamed:@"navback.png"] forState:UIControlStateNormal];
[btnBack addTarget:self action:@selector(popThisView) forControlEvents:UIControlEventTouchUpInside];
[btnBack setFrame:CGRectMake(0, 0, 32, 32)];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
[controller.navigationItem setLeftBarButtonItem:backBarButtonItem animated:YES];
[btnBack release];
TT_RELEASE_SAFELY(backBarButtonItem);
}
but i am not able to change color of bottom bar that has back, fwd, stop and refresh bottons.
Anybody please help. It must be done because i saw this in different colors on many applications.
A: changing the colors and style of the toolbars should be done using a TTStyleSheet class.
First, you should extend the TTDefaultStyleSheet to your own class and include these functions to change the colors for both the UINavigationBar and the lower UIToolbar:
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark TTDefaultStyleSheet
///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)navigationBarTintColor {
return RGBCOLOR(0, 60, 30);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)toolbarTintColor {
return RGBCOLOR(0, 60, 30);
}
Then you should load your style sheet class into your app delegate:
[[[TTStyleSheet setGlobalStyleSheet:[[[StyleSheet alloc] init] autorelease]];
A: Thanx aporat,
Here is the stuff i did-
*
*Created a new class (simply as new viewcontroller is created) with
name Stylesheet.h and Stylesheet.m
*imported #import <Three20Style/Three20Style.h> in .h file
*replaced UIViewController with TTDefaultStyleSheet
*in .m file i put the methods navigationBarTintColor and toolbarTintColor
*in project delegate file first i imported Stylesheet.h then on the 1st line of - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions i placed [TTStyleSheet setGlobalStyleSheet:[[[Stylesheet alloc] init] autorelease]];
THATS IT :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scrolling parallax background, infinitely repeated in libgdx I'm making a 2D sidescrolling space shooter-type game, where I need a background that can be scrolled infintely (it is tiled or wrapped repeatedly). I'd also like to implement parallax scrolling, so perhaps have one lowest background nebula texture that barely moves, a higher one containing far-away stars that barely moves and the highest background containing close stars that moves a lot.
I see from google that I'd have each layer move 50% less than the layer above it, but how do I implement this in libgdx? I have a Camera that can be zoomed in and out, and in the physical 800x480 screen could show anything from 128x128 pixels (a ship) to a huge area of space featuring the textures wrapped multiple times on their edges.
How do I continuosly wrap a smaller texture (say 512x512) as if it were infinitely tiled (for when the camera is zoomed right out), and then how do I layer multiple textures like these, keep them together in a suitable structure (is there one in the libgdx api?) and move them as the player's coords change? I've looked at the javadocs and the examples but can't find anything like this problem, apologies if it's obvious!
A: I have not much more to say regarding to the Parallax Scrolling than PFG already did. There is indeed an example in the repository under the test folder and several explanations around the web. I liked this one.
The matter with the background is really easy to solve. This and other related problems can be approached by using modular algebra. I won't go into the details because once shown is very easy to understand.
Imagine that you want to show a compass in your screen. You have a texture 1024x16 representing the cardinal points. Basically all you have is a strip. Letting aside the considerations about the real orientation and such, you have to render it.
Your viewport is 300x400 for example, and you want 200px of the texture on screen (to make it more interesting). You can render it perfectly with a single region until you reach the position (1024-200) = 824. Once you're in this position clearly there is no more texture. But since it is a compass, it's obvious that once you reach the end of it, it has to start again. So this is the answer. Another texture region will do the trick. The range 825-1023 has to be represented by another region. The second region will have a size of (1024-pos) for every value pos>824 && pos<1024
This code is intended to work as real example of a compass. It's very dirty since it works with relative positions all the time due to the conversion between the range (0-3.6) to (0-1024).
spriteBatch.begin();
if (compassorientation<0)
compassorientation = (float) (3.6 - compassorientation%3.6);
else
compassorientation = (float) (compassorientation % 3.6);
if ( compassorientation < ((float)(1024-200)/1024*3.6)){
compass1.setRegion((int)(compassorientation/3.6*1024), 0, 200, 16);
spriteBatch.draw(compass1, 0, (Gdx.graphics.getHeight()/2) -(-250 + compass1.getTexture().getHeight()* (float)1.2), Gdx.graphics.getWidth(), 32 * (float)1.2);
}
else if (compassorientation > ((float)(1024-200)/1024*3.6)) {
compass1.setRegion((int)(compassorientation/3.6*1024), 0, 1024 - (int)(compassorientation/3.6*1024), 16);
spriteBatch.draw(compass1, 0, (Gdx.graphics.getHeight()/2) -(-250 + compass1.getTexture().getHeight()* (float)1.2), compass1.getRegionWidth()/200f * Gdx.graphics.getWidth() , 32 * (float)1.2);
compass2.setRegion(0, 0, 200 - compass1.getRegionWidth(), 16);
spriteBatch.draw(compass2, compass1.getRegionWidth()/200f * Gdx.graphics.getWidth() , (Gdx.graphics.getHeight()/2) -(-250 + compass1.getTexture().getHeight()* (float)1.2), Gdx.graphics.getWidth() - (compass1.getRegionWidth()/200f * Gdx.graphics.getWidth()) , 32 * (float)1.2);
}
spriteBatch.end();
A: Hey I am also making a parrallax background and trying to get it to scroll.
There is a ParallaxTest.java in the repository, it can be found here.
this file is a standalone class, so you will need to incorporate it into your game how you want. and you will need to change the control input since its hooked up to use touch screen/mouse.
this worked for me. as for repeated bg, i havent gotten that far yet, but i think you just need to basic logic as in, ok one screen away from the end, change the first few screens pos to line up at the end.
A: You can use setWrap function like below:
Texture texture = new Texture(Gdx.files.internal("images/background.png"));
texture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
It will draw background repeatedly! Hope this help!
A: Beneath where you initialize your Texture for the object. Then beneath that type in this
YourTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
Where YourTexture is your texture that you want to parallax scroll.
In Your render file type in this code.
batch.draw(YourTexture,0, 0, 0 , srcy, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
srcy +=10;
It is going to give you an error so make a variable called srcy. It is nothing too fancy.
Int srcy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: jquery nested form plugin I am looking for a jQuery form plugin that can recive XML or json as an input to dynamiclly generate a nested form.
For example:
<root>
<book>
<title>title 1</title>
<price>30</price>
</book>
<book>
<title>title 2</title>
<price>50</price>
</book>
</root>
Will be converted to:
<form>
<fieldset>
<input type="text" name="title[0]"/>
<input type="text" name="price[0]"/>
</fieldset>
<fieldset>
<input type="text" name="title[1]"/>
<input type="text" name="price[1]"/>
</fieldset>
</form>
A: Try jQuery Tmpl (http://api.jquery.com/category/plugins/templates/)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: return confrm delay problem For starters, here is my markup:
<form action="/People/_Delete/AUG0003/10?searchType=IdentityCode&Filter=a&searchOption=StartsWith" method="post" onsubmit="return confirm('Are you sure you want to delete AUG0003?')">
<input id="rowcount" type="hidden" value="10" />
<button alt="Delete" class="g-button user_delete.png" title="Delete AUG0003" type="submit" value="Delete"></button>
</form>
When, i press the button, i receive the confirmation dialog, after i press OK, there is a 2-3 second delay before anything happens.
If i remove the confirmation, it happens fast and instantaneously.
Has anyone encountered this before? It is a real pain.
Thanks,
Nick
A: I've tested this behaviour in Chromium ("Chrome"), and cannot reproduce your issue. JavaScript functions properly:
<script>var time=0;</script>
<form action="javascript:alert((new Date).getTime()-time)" method="post" onsubmit="return confirm('Are you sure you want to delete AUG0003?')&&(time=(new Date).getTime())">
<input id="rowcount" type="hidden" value="10" />
<button alt="Delete" class="g-button user_delete.png" title="Delete AUG0003" type="submit" value="Delete"></button>
</form>
(Link: Fiddle)
When I hit the button, an alert box appears. This alert box shows the delayed time between return confirm(""), and the following of the action targer. I have hit the button multiple times, each time getting 0 (indicating that the issue is not caused by the use of onsubmit.
The "delay" is very likely caused by coincidence, impatience or a server-side issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I execute an SQL command on a DBContext connection before the first EF entity is loaded? I'm pretty new to EF, and have searched around for an answer to this without luck.
In essence, when I get a connection to the db in EF, I need to execute a stored procedure to setup some internal security, which will then limit the data that is brought back in the EF interactions.
Searching around, I have found information that says the following should work:
String currentUser = "Name";
_db = new DBContext();
if (_db.Database.Connection.State != ConnectionState.Open) {
_db.Database.Connection.Open();
}
DbConnection conn = _db.Database.Connection;
DbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "storedproc";
DbParameter user = cmd.CreateParameter();
user.DbType = DbType.String;
user.Direction = ParameterDirection.Input;
user.Value = currentUser.ToUpper();
cmd.Parameters.Add(user);
cmd.ExecuteNonQuery();
var customer = (from c in _db.Customer where c.ACCOUNT == inputAccount select c);
response = customer.First<Customer>();
However when I try this, I get the "EntityConnection can only be constructed with a closed DBConnection." when I hit the LINQ query.
Does anyone know if this is even possible?
I'm using EF4.1, and the Oracle ODP.NET Beta for my DB access, which is connecting to a 10.2.0.3.0 server.
Thanks in advance for any help!
[EDIT]
I managed to work through this from what Craig mentioned, and by doing the following:
*
*Supplying a connection to the DbContext
*Opening the connection before I did any work
This allowed me to execute my security stored proc, and also forced EF to keep the connection open so my security setup was still valid.
Code as follows:
OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["DBConnect"].ConnectionString);
_db = new DBContext(conn);
_db.UnderlyingContext().Connection.Open();
_db.UnderlyingContext().ExecuteStoreCommand("execute storedproc");
_db.SaveChanges();
var customer = (from c in _db.Customer where c.ACCOUNT == inputAccount select c);
response = customer.First<Customer>();
A: Don't bust through to the connection like that. Use ObjectContext.ExecuteStoreCommand.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to set numeric virtual keyboard only for LWUIT TextField that constraint with Password and Numeric? I want to set LWUIT TextField constraint to Number and Password. I make TextField by
TextField tf=new TextField();
tf.setConstraints(TextArea.NUMBER|TextField.PASSWORD);
tf.setInputModeOrder(new String[ ] {"123"} );
I use virtual keyboard for input to this textfield. When I press this textfiled, alphabat virtual keyboard appear and can type alphabat like a to z and other symbol.
How can I set this textfield that only appear numeric virtual keyboard?
A: Use like this for both numeric and password in the TextField,
textField.setConstraint(TextArea.NUMERIC | TextField.PASSWORD);
textField.setInputModeOrder(new String[]{"123"});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to unzip a zip file shared through iTunes from the Application Programmatically? I need to unzip file synced through itunes in the documents directory programmatically. There are open source frameworks available like ZipArchive and ZipKit but I am not able to use them in the project. Is there a decent tutorial where I can see how to use these frameworks.
A: you can use SSZipArchive.
It is so simple way to unzip file. please read Readme.markdown (usage).
Simple three lines and that's it.
A: For ZipKit, you need to use the Better Way of Installing the Framework and follow the Static Library section of the ZipKit Documentation because iOS doesn't allow you to use to embed the Frameworks directly. You need to include it as a Static Library.
Alternatively you could use something lightweight like iZip
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to work out what the filename of the index of a website is with PHP? Take this scenario for an example:
*
*User types "http://example.com/index.html" into my form
*Form is sent to backend script which does file_get_contents("http://example.com/index.html")
*PHP script saves the returned html to a file with the name "site.html" (file extension based on the extension of the given address)
Now consider this second example:
*
*User types "http://example.com" into my form
*Form is sent to backend script which does file_get_contents("http://example.com")
*PHP script saves the returned html to a file with the name "site.com" (file extension based on the extension of the given address)
Clearly this method is not ideal because the file "site.com" is now pretty useless.
My question is, is there a way for PHP to work out what type of file it is getting? In the second example, it could be anything from "index.html" to "default.asp" depending on the server settings.
A: You can look at the Content-Type HTTP header to figure out what type of file you are getting — but you can't find out what the filename used on the server is (or even if there is a filename), and (in most cases) both index.html and default.asp will return an HTML document.
A: If example.com is a different server than the one PHP is running on, you can't.
OPTION : you can bruteforce, that is trying different possible filenames (index.htm, index.html, index.php, index.asp, default.html, etc...)
A: Two points here:
*
*Firstly, no it is not possible to work out the name of the file that was served if you just requested the root of a directory. This is handled internally by the web server, and it doesn't tell the client how it was handled. Sorry.
*Secondly - surely you can just give all the files a .html extension if no file name was specified? In 99% of cases the default file that is served is HTML, even if it is a .asp or .php extension, all that it spits out is dynamically generated HTML. You don't get the source code, only the result.
EDIT
This is the best solution I can come up with for determining a sensible file extension based purely on the URL:
$urlParts = parse_url($url);
if (!isset($urlParts['path'])) $ext = 'html'; else {
$pathParts = explode('/',$urlParts['path']);
$ext = (count($fileParts = explode('.',array_pop($pathParts))) > 1) ? array_pop($fileParts) : 'html';
}
A: Well, anyway it will be HTML file. So always use HTML extension.
A: You can't really use the URL to determine the type of response you get. What you need is the MIME type from the Content-Type response header.
You can extract this header from the automatically populated $http_response_header variable. Here's an example which will get the contents of a URL, and maps the Content-Type of the response to a file extension....
$typeMap=array(
'text/html' =>'.html',
'text/plain' =>'.txt',
'image/jpeg' =>'.jpeg',
#you get the idea...
);
$html=file_get_contents("http://www.google.com");
$ext='.html';//assume html, and prove otherwise....
//examine the headers
foreach($http_response_header as $hdr)
{
list($name,$value)=explode(':', $hdr, 2);
if ($name=='Content-Type')
{
#naive parse of content type
list($type,$extra)=explode(';', $value, 2);
if (isset($typeMap[$type]))
$ext=$typeMap[$type];
//no need to look at more headers
break;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVC3 Model property bound to Html.DropdownListfor not updated on selecting dropdown by Jquery I have a MVC3 application with ASPX view engine. My page is having a dropdownlist created by
Html.DropdownListFor(m=>m.EmpId,(selectlist)Model.EmpDetails).
I update this dropdown on a situation where it would have only one item and make that disabled, by Jquery. Now when I go to form post, my model's 'EmpId' property is not updated with the corresponding value of its selected item in dropdown list. I suspect, since the dropdownlist is not manually selected (updated by Jquery), I'm not getting 'EmpId' in my model. Is there a way to overcome this issue?
With regards,
Saravanan
A: Disabled form fields are not posted to the server. you can make it readonly if u want to stop users from manually changing it
A: disabled form fields do not participate in form values sent to server. That is why your EmpId is not populated on server - it does not exist there. Making that readonly instead of disabled may help you. Do not disable form field if you need it on server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cross join not recognized in HSQL I am using HSQL ver 1.7. There is a part where I have a HQL like the following
String hql = "from ProductInv prodInv where prodInv.product.id in (:prodList)";
prodList contains list of product ids and the above hql is to get product inventories of the required product ids in prodList.
This hql is translated to a native sql query with "cross join". When this works against my actual db2, it works fine. But my unit tests based on HSQL fails. It says "cross join" is not a recognized keyword.
A: You need to upgrade to one of the latest versions of HSQLDB (HSQLDB Versions 1.7.x are at least 7 years old).
If your version of Hibernate is 3.6 or later, use the latest HSQLDB (2.2.8 or later). For older versions of Hibernate, use 1.8.1.3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to avoid image is Hidden by Button I have kept an TImage component at the Top-right corner of a bitbutton.While loading of Form some part of image is Hidden by Button as like in image .How to avoid this.? and also tell me how to find corner of a Button such that i can place my image correctly to show notification correctly in case of Dynamically loaded buttons.
Yours Rakesh.
A: A TImage cannot be brought in front of a TBitButton since a BitButton is a windowed control (TWinControl). Instead of a TBitBtn or a TButton, you can use a control which does not descend from TWinControl, like a TSpeedButton.
The top-right corner of a button is at (Button.Left + Button.Width, Button.Top).
A: A TBitButton owns a window handle and only controls with an own window handle can be placed in front of it. You could place your bitmap on a TPanel (TPanel inherits from TWinControl and has a window handle), and this panel you can bring in front of any other control. Set the BorderStyle of the panel to bsNone, so it only works as a container and is not visible.
P.S. If your bitmap is as simple as the one in your example, you could directly write onto the panel and set the colors accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recipe finder in PHP/MySQL that allows filtering by ingredients I have a MySQL database which looks like this:
Recipes (rid, name)
Ingredients (iid, name)
Relationship (rid, iid)
And I have a front end web page which displays the ingredients in a grid. When a user clicks on the first ingredient, all recipes which contain that ingredient are returned.
On the second click, the recipes are filtered to include only the first ingredient, and this new one. On the third click, the same filter system applies.
Imagine the following scenario (even though the database doesn't look like below)
Recipes (1,2,3,4,5,6) and Ingredients (A,B,C,D,E,F)
1 A B C
2 C D F
3 A B E
4 A D E
5 B C E
6 D E F
First Click: (A) returns --> 1, 3, 4
Second Click: (B) returns --> 1, 3
Third Click: (C) returns --> 1
How would I do this using PHP and MySQL?
A: SELECT re.*
FROM recipes re
WHERE
(
SELECT COUNT(1)
FROM relationships sh
WHERE
sh.rid = re.rid
AND sh.iid IN (A, B, C)
) >= 3
This solution works for me. However the nature of the application I am developing requires hundreds if not thousands of recipes to be stored for it to run nicely, ie. without returning zero results. Quite a simple concept, but tricky to get right.
A: It's quite simple that you need to return the rid where rid in (list of rids in relations where iid= given iid).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: passing value by sms can I passing a value to another device by sms?
usually when i passing a value to another, i'm using putextra and getintent method, but i don't know when passing to another device...
my code to send sms is like this :
private void sendSMS(String phoneNumber, String message)
{
/*
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, test.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
*/
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
retrieve sms :
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
i'm doing an android project which i can add someone to my friend list, and it required confirmation from the other party, so when i click add button, my device will send a sms and notification to another device, wait for confirm, and when the other device has confirm, it will be automaticaly added to my friends list, anyone can help me? thanks before
A: I really don't think you can put extras to SMS, just the sms text. Maybe you should put the extras in SMS as text with your structure and read them with your app on reciever phones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get max x rows plus all row info per group by in mysql to linq A while ago I found a handy query for mysql to get the top X per group by.
This is what I mean:
if this is the table:
rid id1 id2 id3 value
1 1 1 1 10
2 1 1 2 11
3 1 1 3 9
4 1 2 1 20
5 1 2 2 18
6 1 2 3 23
7 1 3 1 30
8 1 3 2 34
9 1 3 3 31
10 1 3 4 27
11 1 3 5 32
12 1 4 1 41
13 1 4 2 40
14 1 4 3 43
15 1 5 1 53
16 1 5 2 51
17 1 5 3 50
18 2 1 1 11
19 2 1 2 9
20 2 1 3 12
I want to get this result:
rid id1 id2 id3 value
2 1 1 2 11
6 1 2 3 23
8 1 3 2 34
14 1 4 3 43
15 1 5 1 53
I can get this by running the following mysql query:
SELECT * FROM
(SELECT * FROM idsandvalue
WHERE id1=1 AND
(SELECT COUNT(*) FROM idsandvalue AS helper
WHERE helper.id1 = idsandvalue.id1
AND helper.id2= idsandvalue.id2
AND helper.value > idsandvalue.value
) < 1
)a;
if I change < 1 to lets say 2, 3 or x I can get the top x per id2 where id1=1 (so, two of the same id2's with different id3's) like this:
rid id1 id2 id3 value
1 1 1 1 10
2 1 1 2 11
4 1 2 1 20
6 1 2 3 23
8 1 3 2 34
11 1 3 5 32
12 1 4 1 41
14 1 4 3 43
15 1 5 1 53
16 1 5 2 51
two questions.
A) the query is not really fast in MySQL. Takes a while (runs a table with 3207394 rows). Can I get the same result with the use of a different query (I was not able to get it).
B) How can I translate this to linq? Due to the strange where statement, I have no clue how to translate this into linq.
(later I added this extra question as well)
in MySQL I use this query:
SELECT *,COUNT(*) AS Counter FROM idsandvalue GROUP BY id1,id2;
to get this result:
rid id1 id2 id3 value Counter
1 1 1 1 10 3
4 1 2 1 20 3
7 1 3 1 30 5
12 1 4 1 41 3
15 1 5 1 53 3
18 2 1 1 11 3
I'm also having difficulties translating this to Linq.
(extra info was too big for comment)
Hi John (thanks for the quick respond).
with this mysql query
SELECT * FROM
(SELECT * FROM idsandvalue
WHERE id1=1 AND
(SELECT COUNT(*) FROM idsandvalue AS helper
WHERE helper.id1 = idsandvalue.id1
AND helper.id2= idsandvalue.id2
AND helper.value > idsandvalue.value
) < 1
)a
I try to get the rows for each grouped id1 and id2 with it's biggest value. That's why in this case I get for instance row with id 2. 11 is the biggest of 10,11 and 9 where id1=1 and id2=1. and that's why I get the row with id 8, because where id1=1 and id2=3 the biggest value for column value is 34. If I change the query to < 2, I get the top two. for id2=1 and id2=3 this would give the rows with id 8 and 11. Is this better explained?
A: Recreated your table in SQL Server and ran your query against it, than converted the query via linqer:
from a in ((from idsandvalue in db.idsandvalue whereidsandvalue.id1 == 1 &&
(from helper in db.idsandvalue
where
helper.id1 == idsandvalue.id1 &&
helper.id2 == idsandvalue.id2 &&
helper.value > idsandvalue.value
select new {
helper
}).Count() < 1
select new {
idsandvalue
}))
select new {
a.idsandvalue.rid,
a.idsandvalue.id1,
a.idsandvalue.id2,
a.idsandvalue.id3,
a.idsandvalue.value
}
A: How's this:
var takeRows = 2; // or whatever value you want
var q = from i in idsandvalue
group i by new { i.ID1, i.ID2 } into g
orderby g.Key.ID1, g.Key.ID2
select new { g.Key.ID1, g.Key.ID2, TopValues = g.OrderByDescending(i => i.Value).Take(takeRows) };
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Silverlight navigation problems under IIS I’m totally confused.
I’ve hosted my app under IIS on my machine (windows 7). If then I open IE and enter "http://localhost/MyApp.aspx#SomePage" it will really open the app and then navigate to that “SomePage” page. If then I’ll navigate to another page, address bar updates accordingly (i. e. "http://localhost/MyApp.aspx#SomeOtherPage"). So everything is fine.
But if I enter in browser "http://mypcnetworkname/MyApp.aspx#SomePage" it simply opens my app with the default page and doesn’t navigate to SomePage. If then I'll navigate to another page, address bar also doesn’t update. Navigating through screens doesn’t update nor history frame not address bar and vice verca — looks like browser navigation is disconnected from silverlight navigation (but I’m still able to navigate through application using hyperlinkbuttons in it).
What can I do to make it work? I guess it’s more iis configuration problem (however everything is default, except mime type for silverlight) than related to silverlight.
P. S. It’s an silverlight 4 app but I do have silverlight 5 installed on my machine.
A: one way to get around this would be use asp.net to write SomeOtherPage to the launch paramters of the html object.
You then can parse these values when you launch the application and make the switch your self in silverlight
heres a link on passing paramerters: Link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: run time layout manipulation I have a grid type of layout. When the app first loads, there are 3 buttons. I am using "Adapter" for the layout.
ONCLICK of the button, I want to refresh the same activity but with different set of 9 buttons.
Do I start a new Activity in all? OR Make a temporary activity to start the previous activity (and how)?
Since the ONCLICK event is written in the "Adapter" part of the code, starting new activity on click of the button is difficult. (is out of my knowledge).
A: if you are using adapter i.e., like baseadapter then you can try:
adapter.notifyDataSetChanged();
directly without starting activity again.
A: If you want the user to go back to the 3 button view on click of Back button, it will be easier to have the 9 buttons in a different Activity.
Otherwise, you can have the 3 buttons and 9 buttons within two different LinearLayouts in the same activity and hide the second layout using setVisibility(LinearLayout.GONE);
On Click of the button, you can hide the first layout and enable the second one using setVisibility(LinearLayout.VISIBLE);
A: In the adapter class, we can start an activity using context.startActivity(intent) I did not know that we can access "start Activity" from adapter...
but now it's working just fine!!
Thanks a lot for your recommendation...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSOrderedSet for iPhone? For some odd reason NSOrderedSet does not appear to be implemented in iOS. Is there another object that gives similar functionality -- basically the ability to insert/remove objects randomly and access the first/last in sort order?
It seems to me that something like this would be needed in order to implement basic FIFO queues and the like.
Edit: I ended up doing an RYO solution.
A: One option is this open source data structures library:
http://dysart.cs.byu.edu/CHDataStructures/index.html
In that library is a CHOrderedSet
http://dysart.cs.byu.edu/CHDataStructures/interface_c_h_ordered_set.html
It's only dependency is NSMutableSet so it should work across all your iOS versions.
EDIT:
As Bourne pointed out above, it's also in iOS5 (reference):
The new NSOrderedSet collection class offers the semantics of sets,
whereby each element occurs at most once in the collection, but where
elements are in a specific order.
CHOrderedSet is a good option if you don't have a hard dependency on iOS5.
A: NSOrderedSet and NSMutableOrderedSet are not available in iOS 5. Here's the reference for anyone curious:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSMutableOrderedSet_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableOrderedSet
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to stop Gson parsing? I just noticed Gson performances are not what I expected and some parsing processes are taking a lot of time. I'm not looking for another solution, my app is quite big and I don't want to alter its structure with something else like jackson.
My Android app allows the user to stop an http request with the back key. My code abort the request and basically stops the task. The thing is, it needs to wait for the method gson.fromJson(result) to abort the task. That instruction can last for a couple of seconds.
Is there any way to tell the gson object to abort the parsing process?
A: I am not familiar with GSON but you could close the underlying stream of JSON data (Inpustream) to end the parsing process with an exception, which you could catch. That should work in case the input data can be a Stream. I have just taken a look at the GSON API and the fromJson method takes a Reader parameter, which can be closed.
A bad way could be also to run it in a thread and call thread.stop().
A: Maybe you could try to split the single gson call to several subcalls (since the parsed data seems to be huge when the request performs for seconds).
Basically I mean to parse every array element on it's own or parse attributes of class one by one instead doing the complete work in a single call. So you could interrupt that process more easily.
A: AFAIK `Gson.fromJson()’Is a blocking method call which in Java can not be stopped.
Run parsing in the background thread. In this case youn can just leave it to run as it does not affect the UI part of your app.
Use AsynTask for this. Add a field cancelled to notify the task that it was cancelled so that it does not update UI at the end.
A: You can probably do this by buffering response, and only doing parsing when everything is complete; or, stopping handling is cancelled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Null Exception was unhandled - IdleDetectionMode.Disabled Whenever I debug my windows phone app, whether it be on my phone or emulator I always get this Exception. How can I resolve this issue?
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
I'm still a beginner with this.
A: I've had same issue. Clearing the \bin and \obj folders and then recompile solved it for me.
A: That's not a exception.
What I guess is the exception, is that the PhoneApplicationService isn't created. So you're getting a NullReferenceException.
Either add PhoneApplicationService = new PhoneApplicationService() on the line above, or ensure following XAML are in your App.xaml
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: CakePHP: Check if user is already logged in I'm trying to forbid multiple logins by the same user at the same time to my CakePHP (1.2) driven site. However, that's not as easy as I thought since I have no idea how to get the information if a user is already logged in or not.
I'm using Cake's Auth-component to authenticate users. The sessions are handled by the php installation and php stores the session data in files. So I guess it is not possible to access the session data from a controller (for, of course, these files aren't saved in the webroot). I thought about checking if a user is logged in or not by using a special database field but there is no way to find out if a user is logged out or not if he doesn't use the logout-method but simply closes his browser and so ends the session.
Can anyone think of another way to manage that? I don't need to know all data about every logged in user. The only thing I need to know is if the given username is logged in at the moment.
Thanks in advance.
A: I think CakePHP will have this behaviour automatically if you set Security.level to high in your core config file, as it regenerates the session ID each time.
Configure::write('Security.level', 'high');
Alternatively, the logic behind it is that you could save a hash of the users IP/User Agent in the user table when they login, and if a computer with a different hash to the one you have saved tries to do something, logout the user. This way only the latest user will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to hide over x chars in a string it's very common to substring an item description if it's too long,
But how could show it back?
i was thinking
if string length is > x
insert after position x a <span classs="more"> //probably i'd do this through php
insert at the end of the string </span>
hide ".more" //css & javascript to hide and show
and then you can simply use a technique like: toogle parent's element with parent
Do you see any alternative for this?
A: You can do it without JavaScript assuming you don't care about support for old browsers that don't understand the CSS :hover pseudo-class (e.g., IE6 only does :hover for <a> elements).
Something like this:
<style>
.full { display: none; }
.shortened:hover .full { display: inline; }
</style>
<span class="shortened">This is some text that <span class="full">has been cropped.</span></span>
In case it's not obvious what this is doing, the first CSS selector hides all elements with the class "full". The second selector shows elements with the class of "full" if they are a child of an element with class "shortened" that also has the mouse over it.
If there are other elements after the outside span they'll temporarily move over to make room while the extra text is visible - a simple way to avoid this is as follows (tweak to suite your taste):
.shortened { position: relative; }
.full { display: none; position: absolute;}
.shortened:hover .full { display: inline; z-index: 100; background-color: white;}
A: Well you could have a php script file that returns the full text and then use ajax to fetch the rest of the description and replace the shortened text.
A: Pure CSS in modern browsers: text-overflow: ellipsis; will cut the text and show … in the end of box. You must specify width / height, so the text would overflow rather than make the container bigger. (Supported in IE7+, FF4+, modern Webkits and Opera)
Edit: noticed, you need exact per character cut. Then, to use my suggestion,e you will need mono-space font (and, possibly, em specified box width).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: caching google maps api v2 is it possible to cache geocodes on google maps api v2?
because i need to get 6.5k marks on my map and with this script it would take around 20 minutes to load them all. and we don't want to use lat and lng if it isn't needed.
and if it isn't possible does anyone know another way to load them faster? my knowledge of javascript isn't very good since this is my first script.
this is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxTPZYElJSBeBUeMSX5xXgq6lLjHthSAk20WnZ_iuuzhMt60X_ukms-AUg"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
//load Google Map
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
var geocoder = new GClientGeocoder();
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
//hier .xml bestand plaatsen voor de adressen
GDownloadUrl("test.xml", function(data, responseCode) {
var xml = GXml.parse(data);
//store markers in markers array
var markers = xml.documentElement.getElementsByTagName("marker");
//loop voor het ophalen van markers
function placeMarker(i) {
//hier die dingen invullen waar hij naar moet zoeken in het .xml bestand
var address = markers[i].getAttribute("address"),
html = markers[i].getAttribute("html");
showAddress(map,geocoder,address,html);
if (++i <= markers.length) {
setTimeout(
function() {
placeMarker(i);
},
//snelheid van de loop hoe hoger het getal hoe langer de loop erover doet om rond te gaan (miliseconden)
210
);
}
}
placeMarker(0);
//Create marker and set up event window
function createMarker(point,html){
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//showAddress zorgt voor het omzetten van de adressen naar lengte en breedte graad
function showAddress(map,geocoder,address,html) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " niet gevonden, laad de pagina aub opnieuw als het adress van toepassing is.");
} else {
map.setCenter(point, 12);
var marker = createMarker(point,html+'<br/><br/>'+address);
map.addOverlay(marker);
}
}
);
}
}
); //close GDownloadUrl
} //close GBrowserIsCompatible
} //close load
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 1000px; height: 700px"></div>
</body>
</html>
A: Google's terms of service is pretty restrictive when it comes to caching data:
10.1.3 Restrictions against Data Export or Copying.
...
(b) No Pre-Fetching, Caching, or Storage of Content. You must not
pre-fetch, cache, or store any Content, except that you may store: (i)
limited amounts of Content for the purpose of improving the
performance of your Maps API Implementation if you do so temporarily,
securely, and in a manner that does not permit use of the Content
outside of the Service; and (ii) any content identifier or key that
the Maps APIs Documentation specifically permits you to store. For
example, you must not use the Content to create an independent
database of “places.”
You could possibly use a free geocoding service like the University of Southern California's webgis service to geocode all of your markers and store them. Then you could retrieve that data and plot it on a Google map.
Also, unless there is a specific reason to use Google Maps v2, I would recommend switching to Maps v3 since v2 is no longer supported.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a 16 bit section using BitVector32.CreateSection I am working on a project where I need to write arrays of bits onto a network connection. The data to be written are 32 bit aligned, i.e. all data is a multiple of 32 bits. My first thinking was to use Bitvector32 to create 32 bit words and then create sections in these bitvectors to reference my data. I do have fields in my data that are 3 or 6 bits, so all data fields are not byte aligned.
BitVector32 on msdn:
http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx
This all seems fine, but problem arise when I am to create a section of 16 bits (2 bytes).
The API has: CreateSection(Int16) where the argument is the largest number to be held by the section. Since I am supposed to pass a signed 16 bit int to this the largest numer I can pass is 0x7FFF. To represent this we will need... 15 bits. So, using the API, I cannot create a 16 bit section of a BitVector32.
Or can I?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Please help move WPF trigger behavior to Silverlight The WPF code:
<TextBox>
<TextBox.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Text" Value="1">
<Setter Property="Background" Value="Red"/>
</Trigger>
<Trigger Property="Text" Value="2">
<Setter Property="Background" Value="Green"/>
</Trigger>
<Trigger Property="Text" Value="3">
<Setter Property="Background" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Resources>
</TextBox>
Can you write the same in Silverlight? Please dont vote to close this question.
Thanks!
A: Or... you can install the "Blend SDK" (it's free), which extends Silverlight's triggers and allows you to do exactly that.
A: Triggers are not supported in Silverlight. You can use a IValueConverter to change the value to the correct color.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: spinner adapter and Listview adapter I have a ListActivity with a setListAdapter call so that I can dynamically hide buttons in the listview. This was working fine till I introduced a spinner which now works fine but somehow stops the listview adapter from working without producing any debug issues or crashes so the buttons are no longer being hidden where they should.
Has anyone come across this and resolved it before?
...oncreate() {
...
ArrayAdapter<CharSequence> spinadapter = ArrayAdapter.createFromResource(
this, R.array.order_by_array, android.R.layout.simple_spinner_item);
spinadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinadapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
private void updateData() {
...
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, mp3, titles, artists);
setListAdapter(adapter);
}
A: I discovered what was happening here, there was no conflict, I just forgot to call the pertinent method after the spinner was selected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jetty 8 GzipFilter does not apply sometimes I just updated my web server from Jetty 6.x to Jetty 8.0.1, and for some reason, when I do the exact same request, sometimes the response has been Gzipped and sometimes not.
Here is what the request and response look like at the beginning of the service() method of the servlet:
Request: [GET /test/hello_world?param=test]@11538114 org.eclipse.jetty.server.Request@b00ec2
Response: org.eclipse.jetty.servlets.GzipFilter$2@1220fd1
WORKED!
Request:[GET /test/hello_world?param=test]@19386718 org.eclipse.jetty.server.Request@127d15e
Response:HTTP/1.1 200
Connection: close
FAILED!
Here is my GzipFilter declaration:
EnumSet<DispatcherType> all = EnumSet.of(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.FORWARD,
DispatcherType.INCLUDE, DispatcherType.REQUEST);
FilterHolder gzipFilter = new FilterHolder(new GzipFilter());
gzipFilter.setInitParameter("mimeTypes", "text/javascript");
gzipFilter.setInitParameter("minGzipSize", "0");
context.addFilter(gzipFilter, "/test/*", all);
The Javadoc says that:
GZIP Filter This filter will gzip the content of a response if:
The filter is mapped to a matching path ==>
The response status code is >=200 and <300
The content length is unknown or more than the minGzipSize initParameter or the minGzipSize is 0(default)
The content-type is in the comma separated list of mimeTypes set in the mimeTypes initParameter or if no mimeTypes are defined the content-type is not "application/gzip"
No content-encoding is specified by the resource
It looks to me that all those conditions are met in my case, except maybe the last one "No content-encoding is specified by the resource". How can I verify that?
Plus, for a reason I ignore too, when the response is not filtered with GzipFilter, response.getWriter() throws an IO Exception. Why is that?
A: I had the same problem, and found 2 causes:
*
*If any of your servlets prematurely calls response.getWriter().flush(), the GZipFilter won't work. In my case both Freemarker in Spring MVC and Sitemesh were doing that, so I had to set the Freemarker setting "auto_flush" to "false" for both the Freemarker servlet and the Spring MVC Freemarker config object.
*If you use the ordinary GzipFilter, for some reason it doesn't let you set any headers in the "including" stage on Jetty. So I had to use IncludableGzipFilter instead.
After I made these changes, it works for me. Hope that helps you as well.
A: May I suggest you to use Fiddler to track you HTTP requests?
Maybe, a header like Last-Modified indicates to your browser that the content of your request /test/hello_world?param=test is still the same... So your browser reuses what is in its cache and simply close the request, without reading its content...
What happens with two different requests?
*
*/test/hello_world?param=test
*/test/hello_world?param=test&foo=1
A: You can use another GzipFilter. Add it to your maven or download the jar file http://mvnrepository.com/artifact/net.sourceforge.pjl-comp-filter/pjl-comp-filter/1.7
And then just change a bit your code:
EnumSet<DispatcherType> all = EnumSet.of(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST);
FilterHolder gzipFilter = new FilterHolder(new CompressingFilter());
gzipFilter.setInitParameter("includeContentTypes", "text/javascript");
context.addFilter(gzipFilter, "/test/*", all);
I've had the same issue and this fixed the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: multitouch swipe not working in my flex mobile project, developed for Ipad, I implemented swipe gestures to switch between views. After some time I realized it did'nt work from itself with multitouch, so I tried to implement a multitouch statement before the eventlistener. But it's not working, it only registers the swipe when I use one finger.
//multitouch
Multitouch.inputMode = MultitouchInputMode.GESTURE;
//gesture navigation
this.stage.addEventListener(TransformGestureEvent.GESTURE_SWIPE, handleSwipe)
private function handleSwipe(evt:TransformGestureEvent):void
{
//do something
}
A: I've never done multitouch before as my things are normally very simple utilities on the phone. With that said, I recommend you read this and this.
You should also check if the gestures are supported (var supportedGesturesVar:Vector.<String> = Multitouch.supportedGestures;) which I think they are for iPad. I think the problem here is that the swipe built in gesture is only for 1 finger. You can access the raw multitouch data and create your own gesture (like 2 finger or more swiping) or you can use an open source library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ANTLR Parser Rules With String Literals Say if my parser rules look like this:
rule1 : 'functionA' '(' expression-inside-parenthesis ')';
expression-inside-parenthesis: ....;
But I never defined any lexer rule for 'functionA', '(' and ')'. Would these be considered tokens by the parser? For '(' and ')', there is only 1 character anyway and I suppose there would be no difference. But for 'functionA', if I never defined it as a token in my lexer rules, how could the parser see it as a token?
A:
JavaMan wrote:
how could the parser see it as a token?
ANTLR creates a token for you behind the scenes.
The rule:
rule1 : 'functionA' '(' expression-inside-parenthesis ')';
// parser rules ...
// lexer rules ...
is equivalent to:
rule1 : FA '(' expression-inside-parenthesis ')';
// parser rules ...
FA : 'functionA';
// lexer rules ...
In case of tokens that only consist of 1 character and do not occur within other tokens, like '(' and ')', it is okay to define them "on the fly" inside your parser rule, put as soon as your lexer grammar also contains identifier-like tokens, it's best to explicitly define a token like 'functionA' yourself inside the lexer grammar. By defining them yourself explicitly, it is clearer in what order the lexer tries to tokenize your input.
EDIT
And in case you've used a literal-token and defined a lexer rule that matches the same, like this:
parse : 'functionA' ID;
FA : 'functionA';
ID : 'a'..'z'+;
then ANTLR interprets the parse rule as this:
parse : FA ID;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Writing Hindi language on UILabel in Xcode I have written a code where I need to display hindi numbers on the UILabel. I used devanagari font to show that value but it doesn't work. It just changes the look but not the language.
I was using:
UIFont *font = [UIFont fontWithName:@"DevanagariSangamMN" size:16];
myLabel.font = font;
But it's not working. Can anyone please help me with this?
A: You have got the font name wrong. The font name is DevanagariSangamMN not DevanagarSangamMN (note the missing 'i' in your name). Your code should therefore be:
UIFont *font = [UIFont fontWithName:@"DevanagariSangamMN" size:16];
myLabel.font = font;
To find more information about the iOS Fonts. I recommend this website which has all the fonts available in iOS
Also, if you type English characters into the Label, you will get returned the English version NOT the Hindi translation. It doesn't do the translation for you. Using the DevanagariSangamMN only allows you to show the Hindi Characters because the fonts such as Helvetica which are normally used do not include the Hindi glyphs. For example:
UIFont *font = [UIFont fontWithName:@"DevanagariSangamMN" size:16];
myLabel.font = font;
myLabel.text = @"Testing";
This will return 'Testing' in English, Not in Hindi. However if you do:
UIFont *font = [UIFont fontWithName:@"DevanagariSangamMN" size:16];
myLabel.font = font;
myLabel.text = @"परीक्षण";
Then you will get 'परीक्षण' which is the Hindi for 'Testing' (I used Google Translate so it could be wrong). So to get the number '4' with the Hindi version (४), you need to do the following:
UIFont *font = [UIFont fontWithName:@"DevanagariSangamMN" size:16];
myLabel.font = font;
myLabel.text = @"४";
A: are you assigning your UILabel text in unicode? Try this -
myLabel.text = [NSString stringWithFormat:@"String with unicode %C", 0x207F];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net mvc - inconsistent rendering of ActionLink I have a controller which accepts URLs in the following two formats:
*
*Network/AddOrEdit -> renders a blank form on a page to add a new network object
*Network/AddOrEdit/[id] -> renders a page with prepopulated form to edit the network object
with ID [id]
Obviously it's the same view being used in each instance - one of my design goals is to use the same view for adding and editing purposes.
The master page contains a link to the add page like this:
@Html.ActionLink("Add", "AddOrEdit", "Network")
Ordinarily this renders correctly as /Network/AddOrEdit.
However, when I am on the edit page (i.e. the current URL is in the format Network/AddOrEdit/[id]), then the Add link renders with that ID on the end - so the add link actually points to the edit page. This is not what I want!
So for some reason MVC seems to be allowing the current ID from the query string to interfere with the rendering of the ActionLink.
Any suggestions what I can do about this? :(
A: Your guessing is right. MVC routing mechanism may reuse route variables from the current request to generate outgoing route data. That's why the id parameter is populated from the current request. You should explicitely specify id when generating link
@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = String.Empty }, null)
And when routing system sees route with optional id parameter, and route value with string.Empty, it generates link without id in the end
A: Tried this myself:
@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = UrlParameter.Optional })
Apparently, this one works too.
@Html.ActionLink("Add", "AddOrEdit", "Network", new { id = String.Empty })
Hopefully this works for you too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: android facebook connectivity on a button click
Possible Duplicate:
How to Integrate Facebook Connect with Android
I am making an android application in which I want to login through facebook id on the click of fbconnect button.
Can anyone tell me how to do this?
Thanks.
A: Although the question is quite generic and I'm not quite sure what your fbconnect button should be - have you tried going through the Android Tutorial of the facebook developers page?
A: Refer to http://developers.facebook.com/blog/post/385/. Download the sample application and play around with it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert Object into XML element (and viceversa) in AS3 Is there any way to convert an object into an XML element in AS3?
I found this tutorial to serialize them:
http://cookbooks.adobe.com/post_Serializing_object_to_XML-11988.html
But I also need a way to unserialize to get the original object (with its own properties) and ready to stage.addChild
A: disclaimer: In the following message, when I write (un)serialize I talk about XML
You can (un)serialize a data object with properties such as numbers, arrays, objects or strings. But you can't (un)serialize a graphic object if you don't have all the instructions needed to rebuild it.
The last part of your question (adding to stage the unserialized object) made me think you want to (un)serialize a DisplayObject. If the construction of your DisplayObject can be summarize with some properties (the URL of an image in a Loader, or the size and color of a rectangle in a Shape) you can develop an ad hoc serializer. But this won't work for any custom Sprite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Select all if parameter is null in stored procedure I want to create a procedure in SQL Server that will select and join two tables. The parameters @company, @from and @to are always set but @serie_type can be NULL. If @serie_type is not NULL i just want to include the specified types, simple AND S.Type = @serie_type, but if @serie_type is NULL i want to include all types, simple, just dont include the AND statement. My problem is that i dont know if @serie_type will be set therefore i would like o have something like this:
/* pseudocode */
??? = AND (IF @serie_type IS NOT NULL S.Type = @serie_type)
Here is a simpifyed version of procedure:
CREATE PROCEDURE Report_CompanySerie
@company INT,
@serie_type INT,
@from DATE,
@to DATE
AS
BEGIN
SELECT
*
FROM Company C
JOIN Series S ON S.Company_FK = C.Id
WHERE C.Id = @company
AND S.Created >= @from
AND S.Created <= @to
/* HERE IS MY PROBLEM */
AND ???
END
GO
Don't want to duplicate the select becaust the real select is way bigger then this.
A: The common approach is:
WHERE
C.Id = @company
AND S.Created >= @from
AND S.Created <= @to
AND (@serie_type IS NULL OR S.Type = @serie_type)
A: There is no need to do AND (@serie_type IS NULL OR S.Type = @serie_type) as SQL Server has a built in function to do this logic for you.
Try this:
.
.
AND S.Type = isnull( @serie_type, S.Type)
This returns
true if @serie_type is null or the result of @serie_type = S.Type if @serie_type is not null.
From the MSDN:
IsNull Replaces NULL with the specified replacement value.
ISNULL ( check_expression , replacement_value )
The value of check_expression is returned if it is not NULL;
otherwise, replacement_value is returned after it is implicitly
converted to the type of check_expression, if the types are different.
A: You can also use case statement in the where clause
where e.ZoneId = case when @zoneid=0 then e.zoneid else @zoneid end
A: The very clean approach will be define your @serie_type to be 0. Take a look below:
CREATE PROCEDURE Report_CompanySerie
@company INT,
@serie_type INT = 0,
@from DATE,
@to DATE
AS
BEGIN
SELECT
*
FROM Company C
JOIN Series S ON S.Company_FK = C.Id
WHERE C.Id = @company
AND S.Created >= @from
AND S.Created <= @to
/* HERE IS MY PROBLEM */
AND (@serie_type = 0 OR S.SerieType = @serie_type)
END
GO
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: C# Word Interop, Pasting Clipboard into Paragraph I have a report builder I'm making that builds the start of a report in word. Word is then kept open for the user to carry on with the report. The report builder gets rtf from a database that is to be used as paragraphs. For each rtf a paragraph is created within the document and the rtf added to it.
What I've read seems to imply that if I want to insert rtf into a word document then I place it in the clipboard then paste it from the clipboard into word. This works fine except this doesn't actually put it into the paragraph how I want it. When the paste method is called it doesn't actually place the rtf in the paragraph range, it just pastes it where the paragraph starts. It doesn't overwrite the paragraph, the paragraph still exists below the block of rtf I pasted is. Moving the range by one to accomodate the paragraph marks doesn't work it just pastes it below the paragraph instead. What I think it needs to use is an Insert() method somehow rather than a Paste() method however I don't know how to go about this and I can't find any information how to go about it. I can insert from building blocks or inserting plain text fine, but what is being inserted here needs to be formatted text. The formatted text has a mix of styles etc that a different user makes.
The code for copying to the clipboard and pasting is as follows:
Clipboard.SetText(richTextBox1.Rtf, TextDataFormat.Rtf);
oPara[i].Range.Paste();
I know you can insert building blocks into paragraphs, which keeps the paragraph formatting, with the following:
tTemplate.BuildingBlockEntries.Item(foundList[i]).Insert(oPara[i].Range.FormattedText);
but I can't find how you would achieve this in my scenario.
The reason I'd like to insert it into a paragraph is to edit certain aspects of the format and ensure things such as don't break lines across pages etc.
The code I have currently for the creating and inserting is this:
Word.Paragraph[] oPara = new Word.Paragraph[foundList.Count];
for (int i = 0; i < foundList.Count; i++)
{
oPara[i] = oDoc.Content.Paragraphs.Add();
Clipboard.SetText(foundList[i].Paragraph, TextDataFormat.Rtf);
oPara[i].Range.InsertParagraphAfter();
oPara[i].Range.Paste();
oPara[i].KeepTogether = -1;
oPara[i].Range.Font.Size = 10;
oPara[i].Range.Font.Name = "Arial";
}
I checked to see where a paragraph was exactly visually with the line
oPara[0].Range.Select(); //To see first paragraph
The result has the rtf pasted where the paragraph begins and the paragraph is just below the rtf pasted.
How would you go about inserting rtf the way I want to into a paragraph in MS-Word?
EDIT: calling the collapse method doesn't do what I want to happen
A: Found the solution, the paste method does actually paste inside the paragraph tags, the problem is that when text is entered into a rich text box, the rich text box automatically adds paragraph tags whether there was any to begin with or not. As the rtf had paragraph tags it counted it as a different paragraph. So the rtf from the database had paragraph tags that were added by a rich text box and not the user. To fix this I just removed the paragraph tags from the rtf taken from the database. Heres the code I ended up with:
for (int i = 0; i < foundList.Count; i++)
{
oPara[i] = oDoc.Content.Paragraphs.Add();
string tempS = foundList[i].Paragraph;
tempS = tempS.Replace("\\pard", "");
tempS = tempS.Replace("\\par", "");
Clipboard.SetText(tempS, TextDataFormat.Rtf);
oPara[i].Range.InsertParagraphAfter();
oPara[i].Range.Paste();
oPara[i].KeepTogether = -1;
oPara[i].Range.Font.Size = 10;
oPara[i].Range.Font.Name = "Arial";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is there a method string.TryFormat that works similar to string.Format? Is there anyway to check if a string.format argument is valid argument something like string.TryFormat .
try
{
string.Format(Format, new string[Selectors.Count]); //
}
catch (Exception)
{
return false;
}
I am using this method in my UI and its slow and noticable when an Exception is catched, so i was wondering if there is a better method to use.
I could always write my own method but i wanted to know if there is a pre defined one.
An invalid string Format would be something like this string.Format("Format{0}{1}{2}",new string[]{"a","b" })
A: The only way a System.String.TryFormat method could work would be to catch any exceptions that might be thrown from various implementations of IFormattable.ToString (although a String.TryFormat could replace some of its own exceptions with an error-flag return, doing that while letting exceptions from TryFormat escape wouldn't be very helpful).
Worse, a TryFormat method wouldn't have any way of knowing whether any of the exceptions thrown by IFormattable.ToString might be things which shouldn't be caught. Even if the IFormattable.ToString contract required that implementations should not leak anything other than FormatException if a format specifier was invalid, one would probably want a String.TryFormat method to return false (rather than throwing) if some of the input objects were invalid but attempting to format them hadn't made anything any worse, while leaking an exception if the act of trying to format items had itself caused corruption. Unfortunately, the way the exception hierarchy is set up, there's no way a String.TryFormat could even begin to approach such semantics.
Simply put, there's not much that a String.TryFormat method could do other than use a try/catch block to stifle exceptions thrown by interior methods. There's a normal implication that TryXX methods are supposed to work better in the failure case than would be a consumer routine which just did XX in a try-catch block. If the TryFormat method is simply going to work by stifling exceptions anyway, it may as well let the consumer handle that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: PHP SQLite3 Query INSERT, DELETE & Redirect I've spent the last couple of days grappling wit the simple concept of using a php script as Save button. When pressed from a webpage the button will INSERT data from table A to table B then delete table A and redirect to back to my main index.html.
<?php
try {
$db = new PDO('sqlite:/srv/db/data.db');
}
$db->exec("INSERT * INTO Archive FROM resultstbl");
$db->exec("DELETE * FROM resultstbl")
unset($db);
?>
So far I could use some help with this PHP query, as well as any guidance.
A: I would do something like this:
<?
if(isset($_POST['but1'])) // this checks if the button is clicked
{
$db = new PDO('sqlite:/srv/db/data.db'); // I assume this is working fine
$db->exec("INSERT INTO Archive SELECT * FROM resultstbl"); // tables must be equivalent in terms of fields
$db->exec("DELETE FROM resultstbl") // You want to delete the records on this table or the table itself? This deletes the records
header("Location: index.php?page=home"); // This will only work if you didn't output anything to the screen yet. If you displayed something it will fail
die();
}
?>
<form action="sql.php" method="POST"> <!-- Assuming this page is sql.php -->
<input type="submit" name="but1" value="GO!"/>
</form>
You can check the syntax for the insert and delete statments for SQLite here:
http://www.sqlite.org/lang_insert.html
http://www.sqlite.org/lang_delete.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Launch my app from Calendar Notes with Custom URL Scheme I'm trying to get my application launched by clicking on a link in the Calendar's notes section, but I just can't do it ...
The URL schemes for http:// and mailto: are working in the notes section (Safari and Mail are started, respectively), but myapp:// does not work, and neither does skype:
myapp:// is working fine when I put it into the address field in Safari, so the custom URL scheme did install successfully.
Is the Calendar only implementing some standard URL schemes and not able to recognize any installed custom URL scheme? Or am I doing something wrong?
A: Ok, found it myself ...
Apparently it is not enough to just write
myapp://
but it has to be
myapp://<sometexthere>
in order for the calendar to recognize it as a custom URL scheme. Safari also accepts the version without text after the two slashes.
One never learns enough ...
A: I keep forgetting to open my Science News E-Zine and there's no other 'reminder'... so:
In CALENDAR I created a monthly-repeating event called: ScienceNewsOpen and it's ‘Alert’ is ‘Open File: SCIENCE NEWS OPENER.APP’
In AUTOMATOR I created that application which began as a Calendar Event but was saved as an app:
FIND CALENDAR EVENTS where ALL is true, "Date Starting" is "Today" and "Any Content" contains Science News.
GET SPECIFIED URLs, "Remove" the existing default Apple.com, "Add" ScienceNews.org
DISPLAY WEBPAGES:
The Science News Website opens in my default browser (FFox) in its own tab, i.e., not a new window once a month - but it can open any URL you put in the Application at any time you want to program into the Calendar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: didReceiveRemoteNotification - call function in the current view controller How can i fire a function of a current view controller(currently user viewing) when i receiving a push notification.
thanks in advance..
A: The best method is to, in your app delegate's method to handle the remove notification, send out a notification using NSNotificationCenter
[[NSNotificationCenter defaultCenter] postNotification:@"remoteNotification" withObject:whateverYouWantHere];
Then use the NSNotificationCenter to add any interested UIViewController's as an observer for the "remoteNotification" name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: newbie asking suggestion for gem structure I plan to write a gem that create a zip file by download from a link or get from filesystem or from a string and upload to s3. Is it a good idea I hijack the Zip module from rubyzip?
Zip::Voidzip.upload! do |zip|
zip.add "http://example.com/example.png", :as => "image/zzz.png"
zip.add "asdasdasdads"
zip.add "asd/asd.png"
end
Since the code most probabily will be like this.
module Zip
class Voidzip
def initialize zipname
t = Tempfile.new(zipname)
ZipOutputStream.open(t.path) do |zos|
end
end
end
end
Any suggestion for newbie that want to contribute?
A: Best practice is to name your gem voidzip.
If you are intending your gem to be a plugin for zip, and if zip actually supports a plugin architecture, then practice would be to name your gem zip-voidzip (but I don't think that's the case here).
Your module/namespace structure should mirror your gem's name.
If your gem is named voidzip, then I expect all of your code to be within Voidzip and I expect to be able to require "voidzip".
If your gem is named zip-voidzip, then I expect all of your code to be within Zip::Voidzip and I expect to be able to require "zip-voidzip" or require "zip/voidzip" at my choice.
A: // Off topic, what the OP's trying to do isn't monkeypatching per-se (see @Beerlington's comment)
I generally try to stay away from monkey-patching, unless I cannot do otherwise. It's always painful to debug something and find out that a gem creator thought it was a good idea to override functionality you're depending on.
But don't trust me, trust him, he's much more experienced that I am.
// Off topic end
You could try to be a little creative and come up with a nice gem name :-) .
Couldn't you just go with the Voidzip name, without nesting it into Zip?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Which LINQ expression is better? I was wondering which of the following LINQ expressions is better (especially in terms of performance).
Notes:
*
*length of SearchKeywords is usually around 50
*length of keywords is usually around 3
*this method is called around 100,000 times
this one?
keywords.All(a => SearchKeywords.Contains(a));
or this one
keywords.Except(SearchKeywords).None();
Note: .None() is my extension method which simply returns !.Any()
Is there any better way to write this?
Regards
A: Except will be approximately a gazillion times faster because it uses a hashtable to find the set difference¹ and thus will give O(n) performance.
The Contains/All combo would have to do a naive linear search² over SearchKeywords for each element in keywords, so we are talking O(n²) performance (actually n * m, but the numbers you give are in the same range and take any excuse I can to type exponents).
Update: as expected, it's not even close unless you explicitly create a HashSet.
¹Unless of course SearchKeywords already is a HashSet<string>, as flq very rightly points out in a comment.
²At least if we 're talking about an IEnumerable, which uses the LINQ to objects standard implementation. An IQueryable could theoretically detect this and implement it any way it likes.
A: Not sure but I think
keywords.Except(SearchKeywords).None();
is faster than previous one because it may require to scan throught once for the collection of SearchKeywork.
A: The first option is far more readable and is compatible with LINQ to SQL if SearchWords is a local collection
The second option is not compatible with Linq To SQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Assign value to People Picker programatically in Infopath As we can assign any field in infopath form using (Eg:TextBox)
MainDataSource.CreateNavigator().SelectSingleNode("//my:RequestedHardware",
NamespaceManager).SetValue("Test");
But when i am assigning the same for the PeoplePicker field it is giving an exception means which we can't add the value like this.
Please suggest how can we programatically do this....
Thanks
A: How are you setting the value ? Contact selector control requires three values to be set as shown below
*
*gpManager/Person/DisplayName = PrinciplaInfo/DisplayName
*gpManager/Person/AccountId = PrinciplaInfo/AccountName
*gpManager/Person/AccountType = "User"
Make sure you are setting all three values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem in Export csv file in php I need to export csv file in php using mysql query .But when i export filename like this "yourfilename.csv_".
My code is
header("Content-type: application/csv");
header("Content-Disposition: \"inline; filename=yourfilename.csv\"");
$query = "SELECT * FROM login";
$result = mysql_query($query) ;
echo "username ,password \r\n";
while($row = mysql_fetch_array($result))
{
echo "$row[user],$row[pass]\r\n";
}
I need file name "yourfilename.csv".
A: You can have MySql return a query result to file directly with
SELECT * INTO OUTFILE 'result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM my_table;
and then just do (also see Example #1 Download dialog)
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="yourfilename.csv"');
readfile('result.csv');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Loop through custom post type based on value of taxonomy I have a custom post type FAQ and custom taxonomy Category.
I want to loop through the taxonomy Category, take its values, and then loop through custom post type FAQ and grab all the posts that have the same taxonomy values.
Can anyone shed some light on this ?
Can't find any decent samples online that are trying to do what I want, only the opposite.
Cheers,
Dave
A: Figured it out :) Would just like to share the answer :)
$taxonomy_loop = new WP_Query( array( 'taxonomy_name_here' => $taxonomy_value ) );
Where $taxonomy_value represents the value you are searching for. Regards, Dave
A: You can do it on this way also
<?php query_posts(array('post_type' => 'post type name', 'Taxonomy slug' => $term->slug ) ); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
Get from http://techsloution4u.com/code-snippet/how-to-create-custom-taxonomy-loop.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to select a single row a 100 million x I would like to generate the following output, using a single row from a select.
SELECT max(t1.id)+1 as new_id FROM t1;
-> 101
However I want to do
SELECT s.last_id, sequence(1..100000000) as new_id
FROM (SELECT max(table1.id)+1 as last_id FROM table1) s;
-> 101,1
-> 101,2
-> 101,3
......
-> 101,100000000
In postgreSQL I can do this using:
SELECT s.last_id, generate_series(1,100000000)
FROM (SELECT max(table1.id)+1 as last_id FROM table1) s; -- returns 100,000,000 rows
How do I do this in MySQL without using a temp-table?
A: Slight amend to Bruno's solution
SELECT (SELECT COALESCE(max(id),0)+1 FROM table1),
@rownum:=@rownum+1 new_id
FROM
(SELECT @rownum:=0) r,
(SELECT 1 UNION ALL SELECT 2) t1,
(SELECT 1 UNION ALL SELECT 2) t2,
(SELECT 1 UNION ALL SELECT 2) t3,
(SELECT 1 UNION ALL SELECT 2) t4,
(SELECT 1 UNION ALL SELECT 2) t5,
(SELECT 1 UNION ALL SELECT 2) t6,
(SELECT 1 UNION ALL SELECT 2) t7
LIMIT 100
Or another version without the variables
SELECT (SELECT Coalesce(MAX(id), 0) + 1
FROM table1),
t1.n * 10 + t2.n + 1 AS new_id
FROM (SELECT 0 AS n UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) t1,
(SELECT 0 AS n UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) t2
ORDER BY new_id
A: Thanks to @harper89 I found the answer here:
http://use-the-index-luke.com/blog/2011-07-30/mysql-row-generator#mysql_generator_code
CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL
SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL
SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL
SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL
SELECT 15;
CREATE OR REPLACE VIEW generator_256
AS SELECT ( ( hi.n << 4 ) | lo.n ) AS n
FROM generator_16
CROSS JOIN generator_16 hi;
CREATE OR REPLACE VIEW generator_4k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
FROM generator_256 lo
CROSS JOIN generator_16 hi;
CREATE OR REPLACE VIEW generator_64k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
FROM generator_256 lo
CROSS JOIN generator_256 hi;
CREATE OR REPLACE VIEW generator_1m
AS SELECT ( ( hi.n << 16 ) | lo.n ) AS n
FROM generator_64k lo
CROSS JOIN generator_16 hi;
Now I can generate the result I want using:
SELECT s.last_id, g.n as new_id FROM (SELECT max(table1.id)+1 as last_id FROM table1) s
CROSS JOIN generator_256 g
WHERE G.N BETWEEN 1 AND 100
ORDER BY g.n ASC;
Using LIMIT is a bad idea, because than up to a million+ rows will be stored in a temp-table. With the where you don't need the temp-storage.
A: There is nothing in MYSql that is equal to generate_series. And after reading the below link it seems everything SQL does except MySQL.
Confirmed Here
It seems you will have to take a more complicated route, but I am not experienced enough to give an answer, the link and answers there may lead you in the right directiom.
Side Note:
You can use LIMIT 100 to only return 100 rows, but it seems you want something slightly different.
A: Johan,
You use this form:
SELECT max(t1.id)+1, @rownum:=@rownum+1 rownum
FROM (SELECT @rownum:=0) r, t1;
Test this sql I think the code was resolve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: sql developer connect to Timesten database When I try to connect to the timesten databse using the SQL developer, I am getting following error message.
Unrecognized JDBC URL subtype: TimesTen
I kept the classes13.jar in system classpath and also included in the Tools - > preferences -> Database -> third party drivers.
Is there anything I am missing in the setup?
Thanks in advance.
A: You can add the ttjdbc5/ttjdbc6 depending on the jdk version selected during the timesten setup.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# How to Verify Digital Signature from email ( Encoding SeveBit ) I get the message body and the smime.p7s file that contains the digital signature. And I want to verify if the mail is signed by that signature.
I'm using the following code.
private bool VerifyCommand(string text, byte[] signature, string certPath)
{
// Load the certificate file to use to verify the signature from a file
// If using web service or ASP.NET, use: X509Certificate2 cert = new X509Certificate2(Request.ClientCertificate.Certificate);
X509Certificate2 cert = new X509Certificate2(certPath);
// Get public key
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
// Hash the text, the text is the expected command by the client application.
// Remember hased data cannot be unhash. It is irreversable
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
// Verify the signature with the hash
return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
}
byte[] signature is the signature from mail after Convert.FromBase64String(mailsignature).
string certPath is the path tot the smime.p7s file. ( the smime.p7s is attached to the mail)
This is the part where the body mail is:
------=_NextPart_001_0039_01CC77C1.AFC97230
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
FINAL TEST SIGNED
------=_NextPart_001_0039_01CC77C1.AFC97230
This is a part of the Signature attachment:
------=_NextPart_000_0038_01CC77C1.AFC4B740
Content-Type: application/x-pkcs7-signature; name="smime.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"
MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIWADCCA7Ew
ggKZoAMCAQICEBErBTlXKN63QvT+VRPTt1EwDQYJKoZIhvcNAQEFBQAwQzEXMBUGA1UEChMOQWxj
YXRlbCBMdWNlbnQxKDAmBgNVBAMTH0FsY2F0ZWwgTHVjZW50IEludGVybmFsIFJvb3QgQ0EwHhcN
MDgxMTAzMTU0MTE2WhcNMjgxMTAzMTU0MTE2WjBDMRcwFQYDVQQKEw5BbGNhdGVsIEx1Y2VudDEo
MCYGA1UEAxMfQWxjYXRlbCBMdWNlbnQgSW50ZXJuYWwgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAL5IGBVth8afQdnpuLDI0Z37GgIcPWznOOzFJUV1gVbztqQ5CIxkVL4K
...................
Is the method that I'm using correct? is the Encoding write? or I have to use a 7-bit?
enter code here
Thnx Henning Krause. I searched, and I'm stuck again :( .
public static bool Verify(byte[] signature, X509Certificate2 certificate)
{
X509Certificate2 cert=new X509Certificate2(@"D:\Work\Digital Signature\smime.p7s");
certificate = cert;
if(signature == null)
throw new ArgumentNullException("signature");
if(certificate == null)
throw new ArgumentNullException("certificate");
//the text from the body of the mail
string text = "FINAL TEST SIGNED";
//hash the text
// Methode 3 for Hashing
System.Security.Cryptography.SHA1 hash3 = System.Security.Cryptography.SHA1.Create();
System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding();
byte[] combined = encoder.GetBytes(text);
byte[] hash3byte = hash3.ComputeHash(combined);
//Adding the text from the email, to a contentInfo
ContentInfo content = new ContentInfo(hash3byte);
// decode the signature
SignedCms verifyCms = new SignedCms(content,true);
verifyCms.Decode(signature);
// verify it
try
{
verifyCms.CheckSignature(new X509Certificate2Collection(certificate), false);
return true;
}
catch(CryptographicException)
{
return false;
}
}
I get the CryptographicException "The hash value is not correct."
I tried only verifyCms.CheckSignature(true); (same error)
I tried to add in ContentInfo the whole mail (Sender , Subject , Body, HTML Sectione ...) (same error)
Can you please be more specific how can I use the SignedCms for my problem?
A: You should look into the SignedCMS class. You can use that class to validate signatures according to the PKCS#7 standard.
If you have the message and the signature, you'll do the following:
var cmsMessage = new SignedCms(new ContentInfo(message), true)
cmsMessage.Decode(signature);
// if no CryptographicException is thrown at this point, the signature holds up. Otherwise it's broken.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: AppWidgetProvider handle touch event problem i am adding installed AppWidgetViews to my application as AppWidgetHostView. The problem is they don't handle any touch events as they were added to home screen. Here is part of my code;
AppWidgetHost host = new AppWidgetHost(getContext(), HOST_ID);
AppWidgetManager manager = AppWidgetManager.getInstance(getContext());
int id = host.allocateAppWidgetId();
AppWidgetHostView view = host.createView(getContext(), id, info);
Lets say AppWidgetProviderInfo object "info" belongs to "com.android.alarmclock.AnalogAppWidgetProvider", which is the default analog clock widget of android. This view has to launch clock setting when a click performed on it as it performed on home screen, still i have no response from it. Is there a way to solve this problem? Thanks in advance...
A: I am not sure this will answer your question.
To handle onClick event in android homescreen, I use PendingIntent to setOnClick behavior.
Intent iText = new Intent(this, urTargetActivity.class);
PendingIntent pendingText = PendingIntent.getActivity(context,0, iText,0);
views.setOnClickPendingIntent(R.id.textView1,pendingText);
I am not sure about using it with AppWidgetHostView but the way I have done before is using it in the service to call the configuration activity page which is working without any problem.
Hope this could help you somehow :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change fonts color in Installshield 2011? How can I change fonts color in the the default dialogs in Installshield 2011?
I have created a new entry (with the new color) into TexStile Table, but when selects the new "test style" in the Dialog editor, the colour does not change.
This works fine in InstallShield 2010.
Any suggestion?
A: Have you tried running the setup. Selected color does not reflect immediately in dialog designer view. You have to build the project and start installation and then verify it on corresponding dialog.
A: Add new "test style", then save your project or close your project and re-open it.
A: Here goes
*
*Change the TextStyle property of the text control from default to
any font example Arial10White
*Save the and close the project.
*open the project >> Installation Designer >> Expand Additinal Tools
*
*Select the Direct Editor Table
*Choose the Text Style Table
*Select the Fonts need to change the color set the color code generated from RGB Formula ( narrated in textstyle topic help ) for example for white i choose 16777215 save the table .
Open the wizard and click edit layout you can see the Color is reflected :)
Below is the Screen shot
Text Style font color editing from Install Sheild 2010
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to display the contents of a return array from model to view in codeigniter How to display the contents of a return array from model to view in codeigniter?
Code: model
$arr_data[] =$query2;
return $arr_data[];
how to display the array contents in view page using codeigniter
A: You get data from model, specify an array key element on controller, then while loading view you specify that array as second parameter. And in view, that key becomes your variable.
Sample model:
Class Your_model Extends CI_Model {
function get_stuff() {
//do stuff
$stuff[0] = 'data1';
$stuff[1] = 'data2';
return $stuff;
}
}
Sample Controller:
Class Your_controller Extends CI_Controller {
function __construct() {
parent::__construct();
}
function public_controller() {
$this->load->model('your_model');
$output['model'] = $this->your_model->get_stuff();
$putput['otherstuff'] = 'other stuff';
$this->load->view('your_view',$output);
}
}
Sample view:
foreach ($model as $eachmodel) {
?><b><?php echo $eachmodel; ?></b><?php
}
A: replace "return $arr_data[];" with "return $arr_data", the assign the variable to the view.
$this->load->view('viewName', array('modeldata' => $arr_data);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android AsyncTask and SQLite DB instance I have a problem and I am not sure how to approach it. An activity in my app has multiple AsyncTasks which access single SQLiteOpenHelper. I initialize and open the helper in onCreate() and I am closing it in onStop(). I also check if it has been initialized in onResume().
Since I have published my app I received number of errors with Null Exception in doInBackground where I try to access the DB helper. I know that this is happens because the DB is closed ( onStop() ) just before the doInBackground is called, fair enough.
My question is, where should I close the DB connection? Is it right to use a single instance of the DB helper in the Activity and access it from multiple threads(AsyncTasks)? Or I should use separate DB helper instance for each AsyncTask?
This is a simplified skeleton of my activity:
public class MyActivity extends Activity{
private DbHelper mDbHelper;
private ArrayList<ExampleObject> objects;
@Override
public void onStop(){
super.onStop();
if(mDbHelper != null){
mDbHelper.close();
mDbHelper = null;
}
}
@Override
public void onResume(){
super.onResume();
if(mDbHelper == null){
mDbHelper = new DbHelper(this);
mDbHelper.open();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
DbHelper mDbHelper = new DbHelper(this);
mDbHelper.open();
}
private class DoSomething extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... arg0) {
objects = mDbHelper.getMyExampleObjects();
return null;
}
@Override
protected void onPostExecute(final Void unused){
//update UI with my objects
}
}
private class DoSomethingElse extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... arg0) {
objects = mDbHelper.getSortedObjects();
return null;
}
@Override
protected void onPostExecute(final Void unused){
//update UI with my objects
}
}
}
A: It is good to use a single DB Helper.
The problem is that when the user leaves the Activity the DB is closed but the AsyncTask may still run. So you should check that the DB is not null when you are trying to access it, and if it is null this may mean that your Activity was destroyed and cancel that task.
A: You don't need to manage db connection for each activity. You can do it in an instance of android.app.Application and access db using this instance.
Something like this:
public class MyApplication extends Application {
// Synchronized because it's possible to get a race condition here
// if db is accessed from different threads. This synchronization can be optimized
// thought I wander if it's necessary
public synchronized static SQLiteDatabase db() {
if(self().mDbOpenHelper == null) {
self().mDbOpenHelper = new MyDbOpenHelper();
}
return self().mDbOpenHelper.getWritableDatabase();
}
public static Context context() {
return self();
}
@Override
public void onCreate() {
super.onCreate();
mSelf = this;
}
private static MyApplication self() {
if (self == null) throw new IllegalStateException();
return mSelf;
}
private MyDbOpenHelper mDbOpenHelper;
private static MyApplication mSelf;
}
This way you can be sure you Db is always accessible.
And yes, having one instance of Db helper is a good practice. Thread syncronisation is made for you by default.
A: You mentioned that you cancel the AsyncTask before closing the DB. But you should keep in mind that cancelling the AsyncTask just signals the task to be cancelled and you need to check isCancelled() in doInBackground() and do the needful to stop DB operations.
Before closing the DB, you then need to check getStatus() to be sure that the AsyncTask has stopped.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Overiding same method in Super Class and Interface I am extending a Class as well as implementing an interface, both contain a method called doFilter , it is a final method in my super class and off course an abstract method from my interface . So, now I am getting compiler error.
How should i resolve this.
My filter class is :
public class MyCacheFilter extends CachingFilter implements Filter {
// here is error, as compiler is thinking I am overriding dofilter of
// CacheFilter, although I have not specified any @Override annotation
public doFilter() {
}
}
A: If the method is provided by CachingFilter you don't have to provide an implementation in MyCacheFilter. (In fact, as you've discovered, you can't.)
If you really want a different behavior of doFilter than what is provided by CachingFilter then inheritance is not an option. In that case, consider using composition:
public class MyCacheFilter implements Filter {
CachingFilter cachingFilter = ...
@Override
public void doFilter() {
...
possibly refer to cachingFilter...
...
}
public String otherMethod() {
// delegate to cachingFilter
return cachingFilter.otherMethod();
}
}
[...] although I have not specified any @Override annotation
Whether or not you explicitly provided @Override doesn't make a difference.
A: The problem is that the method is declared final in the superclass. That means, literally, "this method can't be overridden". If you need to put your own logic in doFilter(), you can't extend the CachingFilter.
There is no concept in Java of where you override a method from. The interface is the contract which tells others what your class can do. The complete contract is the sum of all interfaces implemented. It doesn't matter if an identical method signature is present in more than one interface. The class is the implementation of the contract.
Inheritance starts from the top (ie Object) and each overridden method replaces any pre-existing definitions from any parent as the publicly exposed method - except if a method is declared final. That tells the compiler that this method implementation is not allowed to be overridden, this is the final version of it.
EDIT: I don't know what the CachingFilter you are using is coming from, but a common pattern in frameworks layered on top of other frameworks or java standard API is to create a final implementation of the API-required method (doFilter() in this case), but add another "internal" method (like internalDoFilter()) that gets called from the doFilter(). Extending classes can then safely override the "internal" method while still guaranteeing that any essential logic in doFilter() is still executed properly.
A: Unfortunately there is no way to resolve such conflicts directly, other than by rethinking your class design. You could
*
*rename the method in the interface, or
*change MyCacheFilter to contain a CachingFilter rather than inherit from it, or
*if the superclass implementation suits your needs, you can (as @aioobe mentioned) leave the method out of your subclass altogether.
A: If CachingFilter.dofilter() is available, it will be a method in your child class. So you don't need to override it. If you want to override, method shouldn't be final.
A: Try implementing the interface as anonymous.
public class MyClass extends MySuperClass implements MyInterface{
MyInterface myInterface = new MyInterface(){
/* Overrided method from interface */
@override
public void method1(){
}
};
/* Overrided method from superclass*/
@override
public void method1(){
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Workflow persistence by single start of workflow for various states of a project i am using workflow 4.0, silverlight 4.0, in my project.
there are 5 sequences considering states of my project which have to be initiated according to a field called status from database. Actually each sequence should not require parameter.
i want to intiate the workflow once by calling initial sequence with cancreateinstance=true. Other sequence must correlate with the same(uniqueID) and need to be carry on by it own according to status change in database.
Currently i have to call each and every sequence in a workflow as it is contain correlation parameter.
Is there any solution to correlate the variable for workflow persistence without receive send sequence ? If yes how could i do this? Anything i can do with InitializeCorrelation from toolbox.
A: Correlation with a Receive activity is a requirement for your scenario. There is no way to reconnect the workflow instance to the particular silverlight client app on the server side without it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Input needed for my program structure/design I've tried to describe the application I'm building in a much detail as needed, so I apologise in advance for the essay!
I'm in the process of designing and building a fairly large music application, using the C++ Juce framework, that in a nutshell takes in OSC messages and turns them into audio and MIDI data. The application has three 'modes', each defining what kind of sound will be produced by the OSC messages. The user can apply a mode and a further bunch of mode settings to define the sound that each OSC message 'triggers'.
Below is a basic block diagram overview of the programs' class relationship and hierarchy, or at least how I theoretically imagine it to be. To clarify the Juce terminology, a 'Component' class is basically a GUI object/class that displays things on screen and allows user interaction.
Basic block diagram http://liamlacey.web44.net/images/Software_block_diagram.jpg
I'm an experienced C programmer, however I'm fairly new to C++ and OOP design. I'm understanding most if it fine but the major problem I'm having is in terms of structuring all the classes to have the correct relationships and hierarchy so that they can all communicate properly in order for the application to do what it needs to do.
Here is a brief description of what each class does:
*
*OscInput - this base class uses the oscpack library to listen for OSC messages. Only 1 class can inherit from this base class as the application will crash if there are multiple listeners on the same UDP port.
*Main - application start-up. Inherits from OscInput so that every time an OSC message is received a callback function is called within this class
*MainWindow - the apps main document window - default to Juce apps.
*MainComponent - the main/background component/GUI of the app - default to Juce apps.
*Mode1Component / Mode2Component / Mode3Component - a single instance of each of these component classes is called and displayed from MainComponent which are used by the user to change the settings of what each OSC message does.
*SubComponent1 - a single instance of this component class is called and displayed from MainComponent.
*SubComponent2 - 48 instances of this component class are called and displayed from SubComponent1. Each instance is used to display the value of a different OSC message being received.
*Mode1/Mode2/Mode3 - a single instance of each of these classes is called from Main. Each class is used to actually convert the OSC messages into audio or MIDI data, based on values/variables within the Settings class.
*Settings - a single instance of this class that is used to store settings that control what sound is produced from each different OSC message.
I'm fairly happy I have all the component/GUI classes laid out and connected in the right way. I have also got incoming OSC messages working fine. But it is the relationship of the Settings class instance that I'm not quite sure how to implement. Here are the relationships I need help with:
*
*The single instances of Mode1, Mode2, and Mode3 all need to retrieve values from the Setting class instance
*The single instances of MainComponent, Mode1Component, Mode2Component, Mode3Component all need to send values to the Settings class instance, as well as retrieve values from the instance.
*All 48 instances of SubComponent2 need to retrieve OSC messages
Therefore I have the following questions:
*
*Where should the Settings class instance be called from so that all the relevant class instances mentioned above can communicate with it? I only want a single instance of this class that needs to be accessed by many other classes, so should it be a global, Singleton, or static class? I've been studying the Singleton design pattern which seems to be what I'm looking for, but I get the impression I should avoid it if I can and consider alternative methods.
*Should it be the Main class that listens for OSC messages? How can I get SubComponent2 to receive OSC messages as well as the Mode1, Mode2, and Mode3 class instances?
*Should the functionality classes (Mode1, Mode2, and Mode3) be called from Main? I'm trying to keep all functionality and GUI code separate as I have someone else dealing with GUI programming while I'm dealing with the functionality programming of the application.
*Can anyone spot any major flaws in the design pattern of my program?
Any help would be greatly appreciated!
Thanks
A: Concerning your questions on "Main": you should not mix "application startup" with the responsibility for the message processing in the same class / component ("separation of concerns"). What you are describing smells like an application of the publisher/subscriber pattern
http://en.wikipedia.org/wiki/Publish/subscribe
And if you want to make your architecture really message-oriented, where not everything depends on "Main", and "Main" does not depend on everything, I suggest you have a look at "Flow Design". Look here
http://geekswithblogs.net/theArchitectsNapkin/archive/2011/03/19/flow-design-cheat-sheet-ndash-part-i-notation.aspx
http://geekswithblogs.net/theArchitectsNapkin/archive/2011/03/20/flow-design-cheat-sheet-ndash-part-ii-translation.aspx
Implementing a settings class instance as a singleton is ok, when you need those settings almost everywhere in your program. At least it is better testable than a static class. But you should avoid putting too much things in there, since a lot of things may depend on the settings, which may have a negative impact on the maintainablility later on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Does Android app needs to request again for registration on SERVICE_NOT_AVAILABLE message in C2DM? I have implemented C2DM in one of the applications and its working properly. Sometimes, what happens that when registering for C2DM the error message comes as SERVICE_NOT_AVAILABLE. Now, in C2DM docs its mentioned that the application should back off and try later. I wanted to know that whether its mobile application that should back-off and again try to register or will the server back-off and send the registration id whenever it can.
A: That message means no registration id could be provided, and the solution is for your app to retry. It's recommended that when requesting a registration ID that you keep trying, because if your app doesn't have one, core features that rely on push messaging will not work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL error in CodeIgniter My model:
function version()
{
$this->load->database();
$this->db->select('location_id');
$this->db->from('geo_blocks');
$this->db->where("2057793231 BETWEEN `ip_start` AND `ip_end`");
echo $query=$this->db->get()->row();
}
The error I'm getting:
A Database Error Occurred
Error Number: 1054
Unknown column ' ip_start <= 2057793231 AND ip_end >= 2057793231' in 'where clause'
SELECT `location_id` FROM (`geo_blocks`) WHERE ` ip_start <= 2057793231 AND ip_end >= 2057793231
Line Number: 93
But the query works fine in PHPMyAdmin:
SELECT * FROM `geo_blocks` WHERE 2057793231 BETWEEN `ip_start` AND `ip_end`
I also tried different queries which produce the same output in PHPMyAdmin, but not in CodeIgniter:
$this->db->where("ip_start <= 2057793231 AND ip_end >= 2057793231");
What am I doing wrong?
A: Based on this,
SELECT `location_id` FROM (`geo_blocks`) WHERE ` ip_start <= 2057793231 AND ip_end >= 2057793231
There's an unmatched ` in between WHERE and ip_start.
A: You're using the where()-function wrong. The entire point with the where function is for the system to determine where the column is, and what value to escape in order to prevent mysql injections.
In this case the first parameter needs to be the columns and the second one the value:
$this->db->where('ip_start <=', 2057793231);
$this->db->where('ip_end >=', 2057793231);
Note that you can call the where() function more then once. It simply adds an AND between the 2 conditions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQgrid with jquery UI autocomplete validation What I have is jqgrid which uses jQueryUI autocomplete in a column. Everything works perfect except 1 little thing, if user choose to write "fsdfsdfsfasf" and press enter my program will of course freak out and tell me that such item does not exist.
What I want is to make some kind of validation, so if user enter some data which does not exist in autocomplete list program should automatically put autocomplete text to be "" just like here: http://view.jquery.com/trunk/plugins/autocomplete/demo/ in the "month" field.
Since I am using jQueryUI autocomplete and not jquery autocomplete i cant use the mustmatch option.
{
name: 'Brand',
index: 'Brand',
align: 'left',
width: 50,
sortable: true,
editable: true,
edittype: 'text',
editoptions: {
dataInit:
function (elem) {
$(elem).autocomplete({
delay: 0,
minLength: 0,
source: '@Url.Action("GetBrands")',
minChars: 0,
max: 12,
autoFill: true,
mustMatch: true,
matchContains: false,
scrollHeight: 220,
formatItem: function(data, i, total) {
return data[0];
},
select: function (event, ui) {
if (ui.item.value == "Opret ny Brand...") {
$(function () {
var dialogDiv = $('#dialog');
var viewUrl = '@Url.Action("CreateBrand")';
$.get(viewUrl, function (data) {
dialogDiv.html(data);
var $form = $("#updateCarForm");
$form.unbind();
$form.data("validator", null);
//Check document for changes
$.validator.unobtrusive.parse(document);
//Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
});
});
}
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><span style='display:inline-block;width:60px;'><b>" +
item.value + "</b></span></a>")
.appendTo(ul);
};
}
}
},
A: You can implement this functionality by providing a function as an argument to the source parameter of autocomplete and doing the AJAX request yourself. Something like:
$("#auto").autocomplete({
source: function(request, response) {
// Manually perform the AJAX request:
var element = this.element;
$.get('@Url.Action("GetBrands")', request, function (results) {
// No results? Clear out the input field.
if (!results.length) {
element.val('');
}
// Notify the widget of the results.
response(results);
});
}
});
(Untested. You may need to tweak the AJAX call)
I can provide a remote example if necessary, but the concept is the same with an example using a local data source: http://jsfiddle.net/andrewwhitaker/Dgfgr/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to disable audio recording function in iPhone? I'm making a VoIP app for iPhone. It's required to to forbid any form of audio recording for security reason. Is it possible to do so? If so, how to do it? Thanks a lot!
Edit: The app is not for jailbroken iPhones. However, private frameworks are permissible.
A: in your .h file -
#import <AVFoundation/AVFoundation.h>
@interface recordViewController : UIViewController
<AVAudioRecorderDelegate, AVAudioPlayerDelegate>
{
AVAudioRecorder *audioRecorder;
UIButton *playButton;
UIButton *recordButton;
UIButton *stopButton;
}
@property (nonatomic, retain) IBOutlet UIButton *playButton;
@property (nonatomic, retain) IBOutlet UIButton *recordButton;
@property (nonatomic, retain) IBOutlet UIButton *stopButton;
In you .m file -
- (void)viewDidLoad {
[super viewDidLoad];
playButton.enabled = NO;
stopButton.enabled = NO;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:@"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
[audioRecorder stop];
}
The last line [audioRecorder stop] is going to make sure the audio recording is stopped. You can do something similar to your app..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validate dataset using XSD file I have XML file and i am genrating Datset from it
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(strMasterSqlXML))); //strMasterSqlXML is XML string
I have XSD file and i want to validate that dataset set by XSD file to check datatype and relations, if it's possible by direct xml validation or by dataset i am ready to implemt.
Give me idea...
A: Try looking into JAXB. From your xsd it will generate java classes that you can uses to populate your dataset with simple methods. From there you can validate and write to an XML file with ease.
jaxb.java.net
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Creating screenshot with AutoIt _ScreenCapture_Capture in remote server does not work I have a farm of virtual windows servers and they are autonomously running various desktop applications and I want to have easy way to see what's going on on each server without connecting through RDP. So I have created a simple AutoIt script which automatically runs every minute and creates a screenshot of virtual servers desktop:
#NoTrayIcon
#include <WinAPI.au3>
#include <ScreenCapture.au3>
#include <WindowsConstants.au3>
$LocalIP = _getLocalIP()
_ScreenCapture_Capture($CmdLine[1] & "\network\shared\screenshot_" & $LocalIP & ".jpg")
...
The problem I am having is that screenshot only displays desktop with apps when I am connected to it through RDP, once I close it - screenshot will appear black and only mouse pointer is visible.
Is there any way I can create screenshot even if RDP session is closed? Is that possible?
A: Like mentioned in previous replies - this is probably due to the machine being locked.
You can try to use a script that will unlock the remote station, and then perform a screen capture.
Have a look at this post in autoit forum
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How Pass data from one fragment to another In one of my project i am using 2 fragments.one fragment is displaying a list of items.So i want when the topic will be selected in first fragment the details should be changed in another fragment.Data i am able to pass from one fragment to other but the view is not changing.In which method i should implement the view of second fragment so that it can change accordingly.
A: See this link. It describes exactly your problem.
Basically, you have a listener on the items fragment to be notified on each item selection. The class implementing the listener interface may be the Activity or even the other fragment.
When the listener is notified, it updates the details fragment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Locale::TextDomain fails when $LANG is not initially set We have a system of translation that uses perl Locale::TextDomain/gettext.
We have an issue where the localization works on one system and not the other.
The only discernible difference is that environment variable LANG equals 'en_GB.UTF-8' on the working system and LANG is not defined on the non-working system. The non working system has no /etc/default/locale
exporting LANG on the broken system makes it work and unsetting on the working system breaks it.
The following script demonstrates:
#!/usr/bin/perl
use strict;
use warnings;
use Locale::TextDomain ('appdomain', '/path/to/language/folders');
use POSIX (':locale_h');
setlocale(LC_ALL, '');
$ENV{'LANGUAGE'} = 'it';
print __('Back'), "\n";
Why does there need to be an initial $LANG set if we're specifying the LANGUAGE anyway?
Running 'Ubuntu 10.04.2 LTS' and Locale::TextDomain 1.20
A: The locale "" (the empty string) denotes the system locale. All known Un*x implementations of setlocale() use then environment variables to set the locale. You are setting the environment variable after the call to setlocale(), and it is therefore ignored.
Locale::TextDomain does not fail here. It is a configuration error.
There are several approaches for fixing such problems. If you know the language that you want to use you can let libintl-perl do the heavy liftings:
use Locale::Util qw(set_locale);
set_locale(LC_MESSAGES, 'pt', 'BR', 'utf-8');
The call to set_locale() will try all known conventions for locale identifiers for setting the language to Portuguese 'pt' for Brazil ('BR'). It will also try to select a UTF-8 locale. See http://search.cpan.org/dist/libintl-perl/lib/Locale/Util.pm#FUNCTIONS for more information! The name set_locale() was intentionally chosen to avoid a name clash with setlocale() from POSIX.pm.
Beginning with libintl-perl 1.22, you can also switch to the "dumb" gettext backend:
use Locale::Messages qw(select_package);
BEGIN { Locale::Messages->select_package('gettext_dumb') }
The "dumb" backend never bothers to call setlocale() to find the current locale settings but only inspects environment variables. Please see http://search.cpan.org/dist/libintl-perl/lib/Locale/gettext_dumb.pm for the pros and cons of this approach. The biggest disadvantage is that C code does not honor this, so that $! for example will not use the configured language.
Alternatively you can switch to the 'gettext_pp' backend just as described for 'gettext_dumb' above. This will force using the pure Perl implementation of the gettext runtime. The main advantage of this is actually that it is easier to debug. But there are also subtle differences to the C implementation.
Just a side note: You should keep in mind that the environment variable LANGUAGE is a GNU extension and may not work in a non-GNU environment.
A: $LANG is the system-wide default variable used across most Unixy systems. $LANGUAGE is for more specific purposes.
Systems these days really ought to have $LANG set to a sensible default. Get the sysadmin to put it in /etc/profile or wherever it need to be for system-wide shell defaults.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I have a lib ".a" file, where it contents some value,I am able to read the contents I have a lib ".a" file, where it contents some value. I am able to read the contents.But I want replace the space with the Comma(,) and remove the first value in it.
For Example if my .a file Contents the following data,
1 2 3
4 5 6
I want the Output in the following way,
2,3
5,6
So i want to remove the first value from each string and want to replace the Space between the second and third values with a Comma(,).How can I do this.
A: It's may help you!
NSString *str=@"1 2 3";
NSArray *split = [str componentsSeparatedByString:@" "];
NSString *replacevalue=@" ";
for(int i=1;i<[split count];i++)
{
if([replacevalue isEqualToString:@" "])
replacevalue=[NSString stringWithFormat:@"%@",[split objectAtIndex:i]];
else
replacevalue=[NSString stringWithFormat:@"%@,%@",replacevalue,[split objectAtIndex:i]];
}
NSLog(@"%@",replacevalue);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Syntax error in INSERT INTO statement for MS Access I have a SQL Insert Into command that works in normal conditions. That means if I fill in every textbox, the data is send to the db (Acces db).
But when I 'forget' 1 textbox, I receive a "Syntax error in INSERT INTO statement."
How can you avoid this?
string commandPerson = "Insert into Person (LastName,FirstName,DateOfBirth,Phone,Email,AdditionalInfo, Hobbies, CVinDropBOX, Informationrequest) values('" + txtLastN.Text + "','" + txtFirstN.Text + "'," + txtDOB.Text + ",'" + txtPhone.Text + "','" + txtEmail.Text + "','" + txtAdditionalInfo.Text + "','" + txtHobbies.Text + "'," + chkCVDROPBOX.Checked + "," + chkInformation.Checked + ")";
When every textbox has a value, there is no problem.
It is only when i leave 1 or 2 textboxes empty, the error message shows :
Syntax error in INSERT INTO statement
A: use a parametrized approach which not only is safe against SQL Injection, but also let's you solve your problem because you will set a parameter value to NULL (or string.empty) when not provided.
here an example:
string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
and here the full article: http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access
A: try this for the dob (you are missing the single quotes):
'" + txtDOB.Text + "'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I delete duplicate data from SQL table I am in the midst of uploading and updating my db from data from a third party source. Unfortunately, there are many duplicate records in the data from the third party data source.
I looked at a few questions here on SO but all of them seem to be cases where there is an ID column which differentiates one row from the other.
In my case, there is no ID column. e.g.
State City SubDiv Pincode Locality Lat Long
Orissa Koraput Jeypore 764001 B.D.Pur 18.7743 82.5693
Orissa Koraput Jeypore 764001 Jeypore 18.7743 82.5693
Orissa Koraput Jeypore 764001 Jeypore 18.7743 82.5693
Orissa Koraput Jeypore 764001 Jeypore 18.7743 82.5693
Orissa Koraput Jeypore 764001 Jeypore 18.7743 82.5693
Is there a simple query which I can run to delete all duplicate records and keep one record as the original? So in the above case I want to delete rows 3,4,5 from the table.
I am not sure if this can be done using simple sql statements but would like to know others opinion how this can be done
A: ;with cte as(
select State City, SubDiv, Pincode, Locality, Lat, Long,
row_number() over (partition by City, SubDiv, Pincode, Locality, Lat,Long order by City) rn
from yourtable
)
delete cte where rn > 1
A: I would insert the third party data to a temporary table that then:
insert into
target_table
select distinct
*
from
temporary_table
and finally delete the temporary table.
Only distinct (unique) rows will be inserted to the target table.
A: One of
*
*add a column to de-duplicate and leave it
*do a SELECT DISTINCT * INTO ANewTable FROM OldTable and then rename etc
*Use t-clausen.dk's CTE approach
And then add a unique index on the desired columns
A: You may use the ROW_NUMBER() function : SQL SERVER – 2005 – 2008 – Delete Duplicate Rows
A: Try this
alter table mytable add id int identity(1,1)
delete mytable where id in (
select duplicateid from (select ROW_NUMBER() over (partition by State ,City ,SubDiv ,Pincode ,Locality ,Lat ,Long order by State ,City ,SubDiv ,Pincode ,Locality ,Lat ,Long ) duplicateid
from mytable) t where duplicateid !=1)
alter table mytable drop column id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ordering returns from a select statement based on the number of times a particular value appears I have a general question that I would like to ask about MySQL and using the ORDER BY command in a SELECT statement. In particular, I want to know whether it is possible to count the number of times a particular value appears in a database and order the database based this count statement. For example, if I have a player table with the following player_ids:
player_id
1
2
3
4
5
and a game table with the following game and player ids:
game_id player_id
0 5
1 2
2 5
3 1
4 3
5 4
6 3
7 5
8 4
I want to be able to select the players from the player table and organise them by the number of times that they appeared in the database. For example, this would return player 5 first (as player_id has played the most number of games) followed by players 3 and 4. Is there anyway that I can do this? At the same time, I do not want duplicate records (for example, the record for player 5 only has to be returned once rather than 3 times). If anybody could help, it would be greatly appreciated.
A: You need to select the ID against a COUNT of the player_id's and use 'GROUP BY' to ensure that the counts are done against each individual ID. If you want to add up results instead of count them, then use SUM instead with GROUP BY. To order the whole lot by the number of results, use ORDER BY and use the same COUNT command as before.
Your statement will look something like this:-
select id, count(id) from table1, table2 where table1.id = table2.keyid group by id order by count(id) descending;
A: Try this:
SELECT p.*, COUNT(g.game_id) tot_games
FROM players p INNER JOIN game g
ON p.player_id = g.player_id
GROUP BY p.player_id
ORDER BY tot_games DESC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get Html of a view using jQuery in ASP .NET MVC 3.0 I want to get html of a view using jquery and want to show this html in a div on another view page.
I know the .html() method of jquery but it doesn't work for my requirement. I have done a lot of searches but I didn't find this. Please send the answer as soon as possible.
A: have a normal ActionResult that renders a partial
call that ActionLink using jquery ajax e.g.
[HttpPost]
public ActionResult partialview()
{
//do some process if you want to
return PartialView();
}
in jquery
$.ajax({
url:'/Controller/partialview'
type:'POST',
cache:false,
success:function(data){// this handler is called upon successful completion of request
//data contains the html generated by partial view
// you can append it to a div or body as you like e.g
$("#DivID").html(data);
//$(data).appendTo("body");
//etc
//etc
},
error:function(jxhr){// error callback is called if something goes wrong
if(typeof(console)!='undefined'){
console.log(jxhr.status);
console.log(jxhr.responseText);
}
}
});
A: You can use jQuery load to load the response from an action method
Have this markup in your View which has the DIV
<script type="text/javascript">
$(function(){
$("#yourDivID").load("@Url.Action("YourController","YourAction")");
});
</script>
Have an acion method called YourAction in your YourController controller like this
public ActionResult YourAction()
{
return View();
}
Make sure your you have the view YourAction.cshtml under Views/Your folder, which has some markup you want to display.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to change content_for into a partial and getting "undefined local variable or method resource ..." I currently have my devise login form set up like this. Instead of content_for, I would like to just put this content in a partial (named views/devise/sessions/_new.html.erb instead of views/devise/sessions/new.html.erb) to be rendered in the layout. But when I do, I get
undefined local variable or method resource for #<#<Class:0x0000010300f6f0>:0x0000010300da30>
<% content_for :header do %>
<div id="login">
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
<div class="login_header"><%= f.email_field :email, :placeholder => "Email" %></div>
<div class="login_header"><%= f.password_field :password, :placeholder => "Password" %></div>
<% if devise_mapping.rememberable? -%>
<div class="login_header"><%= f.check_box :remember_me %> <%= f.label :Stay_logged_in %></div>
<% end -%>
<div class="login_header"><%= f.submit "Sign in" %></div>
<% end %>
<br /><br />
<%= render :partial => "devise/shared/links" %>
</div>
<% end %>
A: It's complaining that it doesn't know about a local variable that you're passing to form_for. You need to pass your partial a local variable called resource or set it as an instance variable in the controller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: lambda function don't closure the parameter in Python? Code talks more:
from pprint import pprint
li = []
for i in range(5):
li.append(lambda : pprint(i))
for k in li:
k()
yield:
4
4
4
4
4
why not
0
1
2
3
4
??
Thanks.
P.S. If I write the complete decorator, it works as expected:
from pprint import pprint
li = []
#for i in range(5):
#li.append(lambda : pprint(i))
def closure(i):
def _func():
pprint(i)
return _func
for i in range(5):
li.append(closure(i))
for k in li:
k()
A: It does properly reference i, only the thing is, that by the time your list gets populated, i would have the value assigned form the last item in the sequence when the iteration ended, so that's why your seeing 4 all over.
A: If you don't want to use a default argument -- which could introduce bugs if accidentally called with an argument -- you can use a nested lambda:
from pprint import pprint
li = []
for i in range(5):
li.append((lambda x: lambda: pprint(x))(i))
for k in li:
k()
This is an anonymous version of your closure function.
A: you need to do:
lambda i=i: pprint(i)
instead to capture the current value of i
A: The lambda functions create closures over the i variable. After the first for loop is finished, i has value 4.
Then the second for loop starts and all the lambda functions are executed. Each of them then prints the current value of i, which is 4.
A: The answer: Because the code inside the lambda is using your global variable i.
Your second variant will do the same as the first one with lambda if you remove the parameter i:
def closure():
Instead of
def closure(i):
I.e. the code inside the function will use the global variable i.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: check if a character is carriage return i would like to remove the last line from my string.. the nsstring object here is _text. My thoughts are to scan characters from the end and if i found a carriage return symbol i substring to that index, and finnish. But i don't want to remove every carriage return, just the last one.
So i would like to do something like this:
for (int i = [_text length] ; i>0; i--) {
char character = [_text characterAtIndex:i];
if (character == @"\n") {
_text = [_text substringToIndex:i];
return;
}
}
Any help would be very appreciated!
Thanks.
A: Your approach is correct, but you're checking if a char is equal to a literal string pointer! Try this instead:
if (character == '\n')
...
By the way, this is a newline. A carriage return is represented by '\r'. Also, as a word of caution, review your memory management. If _text is an ivar, you may want to use a setter instead. Otherwise, you're assigning an autoreleased object to it that probably won't exist anymore in a latter path, causing other problems.
A: You might try:
NSString *newString = [originalString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
It will remove all leading and trailing carriage returns '\r' and new lines '\n'.
A: You should handle the last char being whitespace or CR.
You also had a bug where you needed length - 1 in the for loop.
Here's some working code:
NSString *_text = [NSString stringWithString:@"line number 1\nline number 2\nlinenumber 3\n "];
// make sure you handle ending whitespace and ending carriage return
_text = [_text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSUInteger i;
unichar cr = '\n';
for (i = [_text length] - 1; i>0; i--)
{
if ([_text characterAtIndex:i] == cr)
{
break;
}
}
if (index > 0)
{
_text = [_text substringToIndex:i];
}
NSLog(@"%@", _text);
This outputs:
2011-09-22 08:00:10.473 Craplet[667:707] line number 1
line number 2
A: Try this -
if([_text characterAtIndex:[albumName length]-1] == '\n') //compare last char
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Routing and reflection problem I added routing to my solution in order to have a more user friendly URL in the address bar.
I start the solution and when I rollover my Favorites link, I see the URL .../Affaire/Favorite (picture below). This one is OK for me.
When I rollover my Recycle bin link, I see the URL ../Affaire/Deleted (picture below). This one is OK for me.
Then I click on the Recycle bin link, I navigate to the corresponding page and the URL showed in the address bar is OK for me (picture below).
Next, I rollover the Favorite link again (picture below), I see the URL ../Affaire/Delete?OnlyFavorite=true!! That's not OK.
The routing is now retrieving an attribute not from my link but from the active URL! This attribute is named OnlyFavorite and I don't want this attribute. This is the "reflexion". Notice that all of my routes are using the same controller and the same action but using different attributes for the routes.
Below are some links I used.
Example for navigating to the favorite page:
@Html.ActionLink("Favorites", "SearchAffaires", new { OnlyFavorite = true })
Example for navigating to the recycle bin page:
@Html.ActionLink("Recycle bin", "SearchAffaires", new { StatusCode = "DELETED" })
Here are my routes:
routes.MapRoute(
"Affaire Status Open/Closed/Deleted", // Route name
"{controller}/{StatusCode}", // URL with parameters
new { action = "SearchAffaires" }, // Parameter defaults
new { controller = "Affaire", StatusCode = "^Open$|^Closed$|^Deleted$" }// Contraints
);
routes.MapRoute(
"Affaire Only Favorite", // Route name
"{controller}/Favorite", // URL with parameters
new { action = "SearchAffaires", Page = 1, OnlyFavorite = true }, // Parameter defaults
new { controller = "Affaire" } // Contraints
);
Do you have any idea how can I proceed to avoid this behaviour?
I don't want the routing to get the attribute named OnlyFavorite from my current URL by reflexion. I already try to pass OnlyFavorite=null on the action link but it doesn't work: the routing says "ok, I don't have a value for OnlyFavorite on the link itself but I have OnlyFavorite on the URL so I use it!".
A: When you are on the Deleted page, the link is being processed that way because the StatusCode token is equal to Deleted, so the first route is satisfied. Change your link as follows:
@Html.ActionLink("Favorites", "SearchAffaires", new { StatusCode = String.Empty, OnlyFavorite = true })
UPDATED
The best solution is to reverse your routes. As a general rule, the most specific routes should always go first, and you should have more generic routes later. Since the "Affaire Only Favorite" route is more specific, it should always go first. If it is the first route satisfied, that should address your issue.
UPDATE #2
I ran a test, and all of the links were generated correctly, when I set the routes as follows:
routes.MapRoute(
"Affaire Only Favorite", // Route name
"Affaire/Favorite", // URL with parameters
new { controller = "Affaire", action = "SearchAffaires",
StatusCode = String.Empty, Page = 1, OnlyFavorite = true } // Parameter defaults
);
routes.MapRoute(
"Affaire Status Open/Closed/Deleted", // Route name
"{controller}/{StatusCode}", // URL with parameters
new { action = "SearchAffaires" }, // Parameter defaults
new { controller = "Affaire", StatusCode = "^Open$|^Closed$|^Deleted$" } // Constraints
);
In addition, the following more generic routes also generated correctly:
routes.MapRoute(
"Favorite", // Route name
"{controller}/Favorite", // URL with parameters
new { action = "Search",
StatusCode = String.Empty, Page = 1, OnlyFavorite = true } // Parameter defaults
);
routes.MapRoute(
"Status Open/Closed/Deleted", // Route name
"{controller}/{StatusCode}", // URL with parameters
new { action = "Search" }, // Parameter defaults
new { StatusCode = "^Open$|^Closed$|^Deleted$" } // Constraints
);
For the more generic routes to work, I had to rename the action as Search and I had to change each link from SearchAffaires to Search.
A: Well, you could use Html.RouteLink helper to point exactly to the route used. However, as @counsellorben pointed out, you should set your more specific route to be the first one.
And if there's no problem to show your url like "Affaire/Favorite/True", then you can use the example below:
routes.MapRoute(
"Affaire Only Favorite", // Route name
"{controller}/Favorite/{OnlyFavorite}", // URL with parameters
new { action = "SearchAffaires", Page = 1, OnlyFavorite = ""}, // Parameter defaults
new { controller = "Affaire" } // Contraints
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I read exactly n bytes from a stream? This is a little more tricky than I first imagined. I'm trying to read n bytes from a stream.
The MSDN claims that Read does not have to return n bytes, it just must return at least 1 and up to n bytes, with 0 bytes being the special case of reaching the end of the stream.
Typically, I'm using something like
var buf = new byte[size];
var count = stream.Read (buf, 0, size);
if (count != size) {
buf = buf.Take (count).ToArray ();
}
yield return buf;
I'm hoping for exactly size bytes but by spec FileStream would be allowed to return a large number of 1-byte chunks as well. This must be avoided.
One way to solve this would be to have 2 buffers, one for reading and one for collecting the chunks until we got the requested number of bytes. That's a little cumbersome though.
I also had a look at BinaryReader but its spec also does not clearly state that n bytes will be returned for sure.
To clarify: Of course, upon the end of the stream the returned number of bytes may be less than size - that's not a problem. I'm only talking about not receiving n bytes even though they are available in the stream.
A: A slightly more readable version:
int offset = 0;
while (offset < count)
{
int read = stream.Read(buffer, offset, count - offset);
if (read == 0)
throw new System.IO.EndOfStreamException();
offset += read;
}
Or written as an extension method for the Stream class:
public static class StreamUtils
{
public static byte[] ReadExactly(this System.IO.Stream stream, int count)
{
byte[] buffer = new byte[count];
int offset = 0;
while (offset < count)
{
int read = stream.Read(buffer, offset, count - offset);
if (read == 0)
throw new System.IO.EndOfStreamException();
offset += read;
}
System.Diagnostics.Debug.Assert(offset == count);
return buffer;
}
}
A: Simply; you loop;
int read, offset = 0;
while(leftToRead > 0 && (read = stream.Read(buf, offset, leftToRead)) > 0) {
leftToRead -= read;
offset += read;
}
if(leftToRead > 0) throw new EndOfStreamException(); // not enough!
After this, buf should have been populated with exactly the right amount of data from the stream, or will have thrown an EOF.
A: Getting everything together from answers here I came up with the following solution. It relies on a source stream length. Works on .NET core 3.1
/// <summary>
/// Copy stream based on source stream length
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
/// <param name="bufferSize">
/// A value that is the largest multiple of 4096 and is still smaller than the LOH threshold (85K).
/// So the buffer is likely to be collected at Gen0, and it offers a significant improvement in Copy performance.
/// </param>
/// <returns></returns>
private async Task CopyStream(Stream source, Stream destination, int bufferSize = 81920)
{
var buffer = new byte[bufferSize];
var offset = 0;
while (offset < source.Length)
{
var leftToRead = source.Length - offset;
var lengthToRead = leftToRead - buffer.Length < 0 ? (int)(leftToRead) : buffer.Length;
var read = await source.ReadAsync(buffer, 0, lengthToRead).ConfigureAwait(false);
if (read == 0)
break;
await destination.WriteAsync(buffer, 0, lengthToRead).ConfigureAwait(false);
offset += read;
}
destination.Seek(0, SeekOrigin.Begin);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Passing message to another window I would like to write an application which passes every message it receives to another window. For example, I have an application where user can press some keys, move mouse over it, etc. and I want all these messages passed to, for example, MS Paint.
How do I do this? Any ideas? As far as I know, there may be a problem with sending key strokes to another window, so please advice as well.
EDIT
Okay, maybe I will give you more description of what I'm looking for.
My applications displays a window of another application on the form. Now I would like to control the other window using messages sent to my application's form (like key downs, mouse moves, etc.).
I have been thinking of passing all the messages my form receives to the window of the application I'm kind of 'embedding' into my own. By 'embedding' I mean making the application window display on my form.
Maybe there's another solution to my problem. Please advice.
Thank you for your time.
A: Some messages (i.e. input messages) arrive through the message queue and the rest are delivered straight to the recipient windows. What you are asking to do therefore requires you to do all of the following:
*
*Implement a top level message loop that retrieves messages from the queue and sends them to the other app.
*Reimplement all modal window loops to pass all messages on.
*Replace the window procedure for all windows in your process with one that passes all messages on to the other app.
*Look for other opportunities for messages to arrive that I have not covered.
I can't imagine that this is really going to be the solution to your problem, whatever that problem is.
A: Forwarding the messages is definitely possible and easy, but it likely won't do what you are expecting. Take a look here.
A: Override the form's DefaultHandler() and post every message it gets to the other form. If there are any explicit message handlers in the form or even some controls then you may not see those messages in DefaultHandler().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# is there anyway to instruct a code block to finish processing before the app gets shut down? I know this won't work in all scenarios, but please keep in mind the following 3 scenarios:
*
*An IIS reset - if the code is running inside IIS
*A Server restart or shut down
*User closes the app (if its a Windows form or Console App).
Lets say I have a code block that runs a loop. Is there a way to ensure at least that the current loop item gets processed before the app shuts down.
Like this...
Loop runs: 100 items, app gets shutdown (for reasons above), app is busy with item in loop 53 for example. It first finishes all code for that item between the foreach... and then allows the app to gracefully shutdown.
Is this type of thing possible?
A: Nothing I would do but If it is ok to abuse the system you might be able to use the CriticalFinalizerObject
It is guaranteed to execute
even in situations where the CLR forcibly unloads an application domain or aborts a thread
A: I really don't think so. You are stuck in front of windows. Windows take that kind of decisions for you.. IF somebody is shutting down the pc, then you are just shut down. This is the same scenario as if they where a power failure. What will you do in that case?
A: In most apps you can handle close event and not allow it but you can't do anything when user decides to kill your process. So i would say that its not possible.
A: For a normal application: While your code is running in a foreground thread (not ThreadPool or Thread.IsBackground == true) it will not be aborted mid-execution, unless the user forcibly quits the process.
If you are running your loop in a background thread, you can try handling the exit event of the application, waiting for the loop to finish or at least reach a stable state before being aborted.
A: How about doing this. using a try catch and finally in the static void Main
Here even if you end task the application, finally will run. not sure about power failure.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
finally
{
MessageBox.Show("I run always.");
}
}
Hope it helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to enable Jscript intellisense (VS2010) in class library project I have a normal class library project that will provide some custom web controls for usage in other (normal ASP.NET Web form) projects.
Those controls will have java script files and I want to use Intellisense in there - especially for the MS Ajax library.
My class library project references System.Web.Extensions, and I added a new JScript file to a Resources\Scripts folder in my project and set it to embedded resource (to be able to reference it from my control and deliver it). So in this script I tried this in the very first line:
/// <reference name="MicrosoftAjax.js" />
But no JScript Intellisense is available (i.e. the Sys and Type global objects are not available in Intellisense).
I also tried this:
/// <reference name="MicrosoftAjax.debug.js" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
but this has the same (negative) results. I also discovered the same behavior when adding a JScript file to a normal web project - also here is no Intellisense available.
So the question is: How can I activate intellisense for the MS Ajax library in my script files?
Additionally: From the web projects (that will only reference my compiled cotnrol assembly, NOT the assembly project with its source), how can I add Intellisense support for the files defined there? The reference with name and assembly seems not to work too.
A: You have to give a path and not just a filename unless the file actually lives in the same folder. also, many files have separate code and vsdoc, try to look for a -vsdoc.js file and reference that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Always avoid recursive methods in Java? I recall that one should always avoid using recursive method calls in Java. I thought the reasons are, that the overhead procuded by saving the invoked methods on the heap is not worth the reduced lines of code in the implementation.
However, I was told lately that this is not true, if the recursive implementation captures the problem space quite well. I did not understand this fully, since every recursive method can be implemented iteratively, for instance by using a stack.
There are several problems which can be solved by using recursive implementations, for instance traversing through the tree data structure.
Should one always avoid recursive implementations in Java or not? If not, what is a good criteria to decide, whether to use recursive or iterative implemenation. Is the produced overhead important or is it optimized anyway? I've read on stackoverflow, that tail recursive optimization is not supported in Java.
A: No, you should not avoid recursion in Java per se. It has its limitations in the JVM, mainly that you can't recurse as deep as e.g. in functional languages can (because, as you noted, tail recursion optimization is not supported by the JVM), but it is certainly useful and usable within those limits.
So use it whenever it makes your solution simpler. Yes, you can always unroll recursion into iteration, but the resulting code may often be more difficult to understand and maintain. Performance of recursion is usually not an issue to be worry about in advance. First prove with measurements that recursion is a performance bottleneck in your program, then you can rewrite it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Optional stubbing in Mockito I want to create a method in superclass of test-class that stubs some commonly used methods in under-test-classes but some of those methods might not exist.
For example, I have a class hierarchy like this:
abstract class A {
void search(); // implemented by subclass
String getFoo() { return "REAL FOO"; }
}
class B extends A {
void search() {
getFoo();
}
}
class C extends A {
void search() {
getFoo();
getBar();
}
String getBar() { return "REAL BAR"; }
}
There are tons of subclasses of A (a tool generated the skeleton) thus I want to create a superclass to make it easier for me to test:
abstract class AbstractSearchTest {
A underTest;
@Test void test() {
doReturn( "FOO" ).when( underTest ).getFoo();
doReturn( "BAR" ).when( underTest, "getBar" ); // THE PROBLEM!
underTest.search();
}
}
class BSearchTest extends AbstractSearchTest {
BSearchTest() {
underTest = new B();
}
}
class CSearchTest extends AbstractSearchTest {
CSearchTest() {
underTest = new C();
}
}
Which basically says, "Before invoking search(), stub getFoo(). Oh, if the subclass happen to have getBar(), stub it too."
But I can't do that since it'll throw org.powermock.reflect.exceptions.MethodNotFoundException. How to do this?
A: Use reflection to determine if the class is implemented.
try{
Method m = underTest.getClass().getMethod("getBar");
// no exception means the method is implememented
// Do your mocking here
doReturn( "BAR" ).when( underTest, "getBar" );
}catch(NoSuchMethodException e){}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to display a pie chart in blackberry application How to display a pie chart in blackberry application using rim apis?
Are there controls available in the rim apis or how can it be done? Can some help me by sharing the code snippet
A: The Google Chart API allows you to provide a URL to the Google service, which in turn returns a chart image. This capability is useful from the BlackBerry smartphone because data can be passed from the BlackBerry smartphone and generates a corresponding chart image on the BlackBerry smartphone.
here are the type of the chat you can do
Here are the chat types defined in Google API.
public static final String LINE_C = "lc";
public static final String LINE_S = "ls";
public static final String LINE_XY = "lxy";
public static final String BAR_HORIZONTAL_STACKED = "bhs";
public static final String BAR_VERTICAL_STACKED = "bvs";
public static final String BAR_HORIZONTAL_GROUPED = "bhg";
public static final String BAR_VERTICAL_GROUPED = "bvg";
public static final String BAR_ = "b";
public static final String PIE = "p";
public static final String PIE_3D = "p3";
public static final String PIE_CONCENTRIC = "pc";
public static final String VENN = "v";
public static final String SCATTER = "s";
public static final String RADAR = "r";
public static final String RADAR_SPLINES = "rs";
public static final String MAP = "t";
public static final String GOOGLE_O_METER = "gom";
public static final String QR_CODE = "qr";
The all you need to do is to request the chat URL. it will download as image to your device. The URL format is given below.
http://chart.apis.google.com/chart?&cht=p3&chd=t:250,100,40&chs=320x200&chl=Apple|Grapes|Mango
cht = chart type
chd = chart data
chs = chart size
chl = chart label
Enjoy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamic Elements in JSP? I am wondering how to create dynamic elements in a JSP webpage? For example, what I want to do is that I have a Selection Box, in which a user selects an image. Upon clicking a button (or possibly after selecting an item), the image will 'slide down' (like how PPT slides slide down when changing slides) and rest on the center of the screen.
Or at least another simpler case would be, when clicking a button, a text box will appear each time you click the button. So far, the only idea I have of this is by using visibility but that will limit me.
Can you help me on how to do these things or if it is possible to do these with only JSP? Additionally, is it possible for elements to 'pop up' (like in facebook photo viewer) without refreshing the page?
Thank you!
A: You want things to happen on the client, so you need to be focusing on the HTML, CSS and JavaScript. The fact you generate the HTML using JSP is irrelevant.
*
*Build on things that work
*Write JS logic for adding new content based on the form options
*Write JS logic for manipulating the CSS to do the animation
Consider using a library such as YUI or jQuery to help with the JS, and using CSS 3 Transitions for the animation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove faces servlet url pattern and page extension from url i have a command link in my page which looks like:
<h:commandLink value="Add user" action="add?faces-redirect=true" />
and when i click it, it goes to url:
http://localhost:8080/myapp/faces/add.xhtml
but i want the url to be:
http://localhost:8080/myapp/add
how to do that ?
i am using spring 3, jsf 2
this is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>myapp</display-name>
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- Change to "Production" when you are ready to deploy -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>faces/users.xhtml</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
A: You can use PrettyFaces for it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: update to rails 3 on ubuntu Hopefully this is an easy one - I'm trying to install rails on my netbook. I can#'t seem to get it to update to rails 3 (seems stuck on 2.3.5). Here's some terminal output to show you what I mean...
mike@Ubuntu-Netbook:~$ rails -v
Rails 2.3.5
mike@Ubuntu-Netbook:~$ gem update rails
Updating installed gems
Nothing to update
mike@Ubuntu-Netbook:~$ sudo gem install rails
[sudo] password for mike:
Successfully installed rails-3.1.0
1 gem installed
Installing ri documentation for rails-3.1.0...
file 'lib' not found
Installing RDoc documentation for rails-3.1.0...
file 'lib' not found
mike@Ubuntu-Netbook:~$ rails -v
Rails 2.3.5
See? Stuck at 2.3.5! I have done a whole bunch of rails installs on other machines and never had this problem before - what am I missing?
The 2.3.5 install is completely working.
EDIT: I did not get an answer to this question. I got around it by investigating rvm and installing that way instead.
A: Are you using bundler? Are you in an rvm gemset?
If you're using the latter, once you sudo, you're in a different user's rvm install, so installation won't be the same. If you're using bundler and have locked rails to 2.3.5, that's what it'll be regardless whether you run gem update or not.
If you can answer the above two questions, we can probably narrow down your issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to search in List items I have a List and it is filled with strings like this:
List<string> data = new List<string>();
data.Add(itemType + "," + itemStock + "," + itemPrice);
So basically there are 3 string variables that are comma separated.
Now I want to search in this list and delete items that are from a specific type. That is I need to search that which elements of my list view begin with desired "itemType".
Thanks.
A: To answer the question in the title ("How to search..."), this returns an IEnumerable<string> with the desired items:
var itemsToRemove = data.Where(x => x.StartsWith(specificItemType + ","));
To answer the question in your question body, you can use List(T).RemoveAll to remove the items:
data.RemoveAll(x => x.StartsWith(specificItemType + ","));
However, I would suggest that you rethink your data structure. Consider creating a class Item:
public class Item {
public string Type { get; set; }
public int Stock { get; set; }
public decimal Price { get; set; }
public override string ToString() {
return itemType + "," + itemStock + "," + itemPrice;
}
}
Then add these data structures to your list:
List<Item> data = new List<Item>();
data.Add(new Item {Type = itemType, Stock = itemStock, Price = itemPrice});
Then you can search, read, reformat, etc. without having to resort to string manipulation:
data.RemoveAll(x => x.Type == specificItemType);
A: var matches = data.Where(d => d.StartsWith(itemType));
You can also use RemoveAll with a predicate condition:
data.RemoveAll(d => d.StartsWith(itemType));
A: var typematch = data.Where(t => t.StartsWith(itemType)).ToList();
Will return you a list of strings that start with a specified type.
A: Data setup
List<string> data = new List<string>();
data.Add("Type1" + "," + "A" + "," + "A");
data.Add("Type2" + "," + "B" + "," + "B");
string typeToExclude = "Type2";
int typeIndex = 0;
Filtering itself
var items = data.Where(
x => x.Split(new char[] {','})[typeIndex] != typeToExclude);
A: You want to delete them from the list so...
data.RemoveAll(x => x.StartsWith(itemType));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How we can skip any Test Cases during CTS Run? How we can do the following task:
During the running time we can skip the any package or case...?
A: You can not skip the particular test cases directly in CTS. For that you have to execute the Test Cases manually which you want to execute. Since there are thousands of test cases so there is a short way to execute test cases, use the short package name which is common.
eg. you can use $ start --plan CTS -p android.app
So this will executes all the test cases which starts with name android.app, like
android.app.cts.ActivityGroupTest
android.app.cts.AlarmManagerTest
android.app.cts.AlertDialogTest
android.app.cts.InstrumentationTest
and so on...
A: while running CTS locally we can actually write a .xml file (say foo.xml) which cab be kept under android-cts/repository/plans directory. Test cases under <Entry exclude="class#method;class#method name="package"/> will not be executed for the package.
And then we can run like below example
cts run -s device_ip:port --plan foo
This is helpful while debugging CTS issues
A: We can skip the particular test case by editing the xml file in the Plans folder .
For eg in the folder
android-cts/repository/plans/CTS.xml
This contains list of all the packages to be executed.Simply delete the package which you want to exclude and save it with other name like
CTS_1.xml and run.
run cts --plan CTS1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: LyXliteral programming I keep writing codes in gedit but at the end of the week we need to submit a lyx literal programming file. Copying and pasting or importing is painful, since , we need to keep pressing tabs or enters. Can anyone suggest a simple alternative to this? Please keep in mind that we need to export the c file from the lyx file.
A: With the help of my friend, i have written a python code to convert the python or c or any other code, as it is to a lyx file. you can later add whatever you want to the lyx file
Here is the link: http://dpaste.com/hold/671718/
A: The aforementioned link is broken, but here's the original.
The script essentially takes code and creates LyX scrap from it. It requires that scrap and noweb be installed on the machine in question. Also, I believe I'd made this for LyX v.1.6. Not sure how it will hold up against newer versions. Then again, one can select and indent using tab in scrap code in the newer versions, so the OP's problem is somewhat mitigated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using Scala Option to validate command line argument I am using Apache commons CLI for command line parsing in a Scala utility application. One of the arguments is a database port number (--port=) that overrides the default "5432" (for PostgreSQL). I am trying to use the Option class to assist in the validation. Here is the code I came up with. Is there a better way to do the validation?
val port = Option(commandLine.getOptionValue("port", "5432")) map {
try {
val value = Integer.parseInt(_)
if (value < 1 || value > 65535) throw new NumberFormatException
value
} catch {
case ex: NumberFormatException =>
throw new
IllegalArgumentException("the port argument must be a number between 1 and 65535")
}
} get
The port number must be an integer between 1 and 65535, inclusive.
Would it be better to do this? Why or why not?
val port = Option(commandLine.getOptionValue("port")) map {
try {
val value = Integer.parseInt(_)
if (value < 1 || value > 65535) throw new NumberFormatException
value
} catch {
case ex: NumberFormatException =>
throw new
IllegalArgumentException("the port argument must be a number between 1 and 65535")
}
} getOrElse(5432)
A: I admit I'm not 100% sure, what you want to be thrown in case something goes wrong, or if the 5432 is a default port for every wrong value, but here is what I would do:
def getPort(candidate: Option[String]) = candidate
.map { _.toInt } // throws NumberFormatException
.filter { v => v > 0 && v <= 65535 } // returns Option[Int]
.getOrElse { throw new IllegalArgumentException("error message") } // return an Int or throws an exception
A: I guess it's a good time for me to explore Validation.
import scalaz._
import Scalaz._
val port = {
def checkRange(port: Int): Validation[String, Int] = {
if (port < 1 || port > 65535) "port not in [1-65535]".fail
else port.success
}
commandLine.getOptionValue("port", "5432")
.parseInt.flatMap(checkRange) match {
case Failure(e) => throw new IllegalArgumentException(e.toString)
case Success(port) => port
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: NSButton setAlignment does not work I used
[button setAlignment:NSCenterTextAlignment];
to make the text display at the center of the button.
It worked.
But if I set button title attribute before the code, button 'setAlignment' will not work
- (void)setButtonTitle:(NSButton*)button fontName:(NSString*)fontName fontSize:(CGFloat)fontSize fontColor:(NSColor*)fontColor;
{
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:[button title]
attributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:fontName size:fontSize]
forKey:NSFontAttributeName]];
[attributedString addAttribute:NSForegroundColorAttributeName
value:fontColor
range:NSMakeRange(0, [[button title] length] )];
[button setAttributedTitle: attributedString];
[button setAlignment:NSCenterTextAlignment];//button title alignment always displayed as 'NSLeftTextAlignment' rather than 'NSCenterTextAlignment'.
}
title alignment always displayed as 'NSLeftTextAlignment' rather than 'NSCenterTextAlignment'.
Welcome any comment
A: Since you’re using an attributed string for the button title, the attributes in that string are responsible for setting the alignment.
To centre that attributed string, add an NSParagraphStyleAttributeName attribute with a centred alignment value:
NSMutableParagraphStyle *centredStyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
[centredStyle setAlignment:NSCenterTextAlignment];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:centredStyle,
NSParagraphStyleAttributeName,
[NSFont fontWithName:fontName size:fontSize],
NSFontAttributeName,
fontColor,
NSForegroundColorAttributeName,
nil];
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:[button title]
attributes:attrs];
[button setAttributedTitle: attributedString];
In the code above, I’ve created a single attrs dictionary holding all the attributes for the attributed string. From your code, it looks like the font colour should be applied to the whole string anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Using Telephony Manager in android to find IMEI number I m very new to Android Development.
I want to find the IMEI number of the phone and using "android.telephony.TelephonyManager;".
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
Now the compiler says.
Context cannot be resolved to a variable.
Any one can help me ? What step I m missing
I have also included user permission in XML.
A: Add in this code:
TelephonyManager manager=(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String deviceid=manager.getDeviceId();
//Device Id is IMEI number
Log.d("msg", "Device id"+deviceid);
Manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
A: Try below piece of code it will help you to get device IMEI number.
public String getDeviceID() {
String deviceId;
TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null) {
deviceId = mTelephony.getDeviceId();
} else {
deviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
}
return deviceId;
}
Also give the read phone state permission in your manifest.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
A: Verify your Imports , you should import : android.content.Context ,
And then use this code :
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
String imei = tm.getDeviceId();
//get The Phone Number
String phone = tm.getLine1Number();
Or directly : use this :
TelephonyManager tm = (TelephonyManager) getSystemService(android.content.Context.TELEPHONY_SERVICE);
EDIT : *you should pass the context to your new Class on the constructor :*
public class YourClass {
private Context context;
//the constructor
public YourClass( Context _context){
this.context = _context;
//other initialisations .....
}
//here is your method to get the IMEI Number by using the Context that you passed to your class
public String getIMEINumber(){
//...... place your code here
}
}
And in your Activity , instanciate your class and pass the context to it like this :
YourClass instance = new YourClass(this);
String IMEI = instance.getIMEINumber();
A: just remove Context keyword in Context.TELEPHONY_SERVICE and check
TelephonyManager tManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String IMEI = tManager.getDeviceId();
A: For Compiler error "Context cannot be resolved to a variable", make sure you have imported android.content.Context package. In Eclipse, quick fixes would have it when you move mouse pointer over the error line in code. And make sure you have added READ_PHONE_STATE permission Manifiest file.
A: [In case if anyone still stumbles here looking for this still existing age-old solution]
AFAIK, TelephonyManager.getLine1Number() is not reliable due to various constraints from operators.
There are some java reflection based hacks but varies from device to device thus making those hacks sort of useless [at least in terms of supported models]
But there is a legitimate lawful logic to find the number, if you really need so. Query all the SMS by sms provider and get the "To" number.
Extra benefits of this trick: 1. you can get all the line numbers if there is multi sim in the device.
Cons: 1. you will need SMS_READ permission [sorry for that]
2. You will get all the sim numbers ever used in the device. this problem can be minimized with some constraint logic e.g. time frame (sms received or sent only today) etc. It would be interesting to hear from others about how to improve this case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: CSS / Javascript Layout problem with fixed-header table, and jquery side-col animation I have a frustrating problem with the following scenario:
*
*Right col, with table. Always 100% of available browser width.
*Smaller Left col (sidebar) with width set to just 140px. Left col has slide-in / slide-out animation, i.e. it can be minimised if not required to maximise available horizontal space for the table in the right col. Right col alters its width correspondingly to use all the space.
*The page header and the table heading row are fixed at the top of the page using a jquery plugin. I could have used position:fixed but then when the table forces the page to scroll horizontally it all breaks as you cant scroll horizontally with position:fixed. Hence the jquery plugin.
The problem is, the jQuery plugin remembers the original widths on the elements, so when the sidebar is shrunk and the page is scrolled, the fixed elements (header rows and sidebar) return to their original size rather than staying shrunk.
I made a basic example of the problem, with all the elements explained above, on jfiddle.
http://jsfiddle.net/cr0wn3r/ktbdx/18/
A: Instead of using jquery plugin which doesn't include refreshing option you can do the trick by yourself.
HERE there is short and great tutorial how to obtain the position effect you want to have.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IBAction not appearing in xib file (A) I have added a normal file, and in the .h file I've added the following code:
-(IBAction)PushButton;
My problem is, the action doesn't appear in the xib file when I go into "File's Owner".
I only have the problem with my "A" files. It works perfectly fine in the "M" files.
Any ideas?
A: May you have not set the class name in the xib
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.