text stringlengths 8 267k | meta dict |
|---|---|
Q: Difference in testing for Enum Flags? Was looking at another question, and was curious if there's any difference at all (in operation or performance) between these two.
Given:
[Flags]
enum TransportModes
{
None = 0,
Bus = 1,
Train = 2,
Plane = 4
}
And a variable
var trip = TransportModes.Bus | TransportModes.Train;
*
*if((trip & TransportModes.Bus) == TransportModes.Bus) ...
*if((trip & TransportModes.Bus)) != 0) ...
I know what they do bit wise, and I know that HasFlag replaces them. But Jon Skeet recommends one, and the MSDN docs recommend another.
A: If bus is not a power of two (if it has multiple bits set), and trip has only some of those bits set, (trip & bus) == bus will be false, but (trip & bus)) != 0 will be true.
A: Your second option will return true, if the values you gave your enum values are not powers of two. The first option doesn't have this problem.
Example:
[Flags]
enum TransportModes
{
None = 0,
Bus = 1,
Train = 2,
Plane = 5
}
var trip = TransportModes.Bus | TransportModes.Train;
if((trip & TransportModes.Plane) != 0)
// will be executed
if((trip & TransportModes.Plane) == TransportModes.Plane)
// won't be executed
Explanation:
trip & TransportModes.Plane is 1 which is apparently != 0, but not equal to TransportModes.Plane which has a value of 5.
However, if you don't use powers of two for the values of a flag enum, you most likely have bigger issues. Think about what happens, if Plane would have the value 3: You couldn't tell Bus | Train and Plane apart...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Register application to handle all file type - Android I am writing an android app for transferring files using Bluetooth.
I am trying to register my application using following in the manifest but it seems it is only registered with images files only. My app does not show-up when I chose other file types from file manager.
<activity android:name="SendFile"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<data android:mimeType="application/*"/>
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="content" android:host="*" android:pathPattern="*" />
<data android:scheme="file" android:host="*" android:pathPattern="*" />
</intent-filter>
</activity>
Where I am doing wrong?
A:
I am writing an android app for transferring files using Bluetooth.
No, you are not. Nothing in that manifest fragment has anything to do with this. Instead, you are claiming that you can view all images, audio files, videos, and things with application/ as the leading portion of the MIME type. It is highly unlikely that your application is capable of doing these things.
My app does not show-up when I chose other file types from file manager.
Since there is no file manager in Android, that perhaps is a question for whoever wrote whatever file manager you are using. I would expect your audio and video files to behave as the images. The last <intent-filter> is unlikely to be honored by Android. And, of course, you should be deleting all of these <intent-filter> elements, unless you are actually capable of viewing all of those file types.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WIA via silverlight, duplex scanning I'm trying to scan an A3 page in duplex using my Xerox documate 752. I'm getting it to scan fine using the document feeder but only on side. How do I access the other image??
Here is my basic code:
dynamic imageFile1;
dynamic imageFile2;
dynamic wiaDialog = AutomationFactory.CreateObject("WIA.CommonDialog");
dynamic Scanner = wiaDialog.ShowSelectDevice(1, false, false);
dynamic manager = AutomationFactory.CreateObject("WIA.DeviceManager");
dynamic deviceInfo = null;
foreach (dynamic info in manager.DeviceInfos)
{
if (info.DeviceID == Scanner.DeviceID)
{
deviceInfo = info;
}
}
dynamic device = deviceInfo.Connect();
dynamic item = device.Items[1];
int dpi = 150;
item.Properties["6146"].Value = 2;
item.Properties["6147"].Value = dpi;
item.Properties["6148"].Value = dpi;
item.Properties["6151"].Value = (int)(dpi * _width);
item.Properties["6152"].Value = (int)(dpi * _height);
int deviceHandling = 5;//code for both feed (1) + duplex (4)
device.Properties["3088"].Value = deviceHandling;
int handlingStatus = (int)device.Properties["3087"].Value;
if (handlingStatus == deviceHandling)
{
//scan the file
imageFile1 = wiaDialog.ShowTransfer(item, "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", true);
//get the second image
imageFile2 = wiaDialog.ShowTransfer(item, "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", true);
}
imageFile1.SaveFile("C:\\testfile1.jpg");
imageFile2.SaveFile("C:\\testfile1_2.jpg");
From what I've read elsewhere if there is a duplex image you access it by calling the ShowTransfer() again. On my scanner this simple tries to scan a new document and returns an error as the feeder is now empty. I'm getting a 5 returned from my handlingStatus indicating that both feed (1) and duplex (4) are turned on - or have i got this totally wrong?
Any help would be much appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Oracle min and max columns query Alright, need some help created a query for an Oracle 10g DB. I have a table to looks like this:
----------------------------------------
| lowerBound | upperBound | locationId |
----------------------------------------
| 0 | 99 | 1 |
----------------------------------------
| 100 | 199 | 2 |
----------------------------------------
...
Another table looks like this:
-----------------------------
| locationId | locationCode |
-----------------------------
| 1 | 12345 |
-----------------------------
| 2 | 23456 |
-----------------------------
| 3 | 34567 |
-----------------------------
...
I start with a number, say 113, but it is a variable figured out in java. I need to figure out the locationId that corresponds to that number, based on it falling between the lowerBound and upperBound columns, and then join that to figure out the locationCode in the 2nd table. I've looked up things like MIN/MAX and between, however I am not finding exactly what I am looking for. I am not a good DBA, so any help is appreciated.
A: SELECT t2.locationCode
FROM table1 t1
INNER JOIN table2 t2 USING(locationId)
WHERE 113 BETWEEN t1.lowerBound AND t1.upperBound
If the USING part puzzles you:
SELECT t2.locationCode
FROM table1 t1
INNER JOIN table2 t2 ON t2.locationId = t1.locationId
WHERE 113 BETWEEN t1.lowerBound AND t1.upperBound
Note that this will work if your lowerBound and upperBound columns are INTEGERS. If they are VARCHAR, you will have to use the TO_NUMBER function of course.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android Button Programmaticallly I have following structure in XML.
<LinearLayout android:id="@+id/tagsTable"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_margin="10dip" android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="This Tag is very big that it has full width :)" android:layout_margin="2px"
android:paddingLeft="5px" android:paddingRight="25px"></Button>
</LinearLayout>
</LinearLayout>
Above layout results into...
But when the same thing I do with that code.
LinearLayout tagsTable = (LinearLayout) findViewById(R.id.tagsTable);
tagsTable.removeAllViews();
LinearLayout currentRow = new LinearLayout(this);
MarginLayoutParams params = new MarginLayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setTag(Id);
button.setText(Name);
button.setTextColor(0xFF736F6E);
button.setPadding(10, 0, 30, 0);
button.setOnTouchListener(new TagTouchListener());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(2, 2, 2, 2);
button.setLayoutParams(params);
button.setBackgroundResource(R.drawable.btn_blue_add_9);
currentRow.addView(button);
tagsTable.addView(currentRow);
The prominent problems are of vertical spacing and size of the button which is changed in both scenarios. The XML way is doing it perfect. What I am doing wrong in code?
A: In xml you have :
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
So in java you could try :
currentRow.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: google style guide script or tool Is there a script or tool that changes a code's style to google style not completely at least partially (maybe just syntax formatting)?
We are reusing some of our C++ legacy code which is not formatted by google style standards and even just formatting it syntactically would take a few hours for a developer.
For now, we wrote some regular expressions that search and replace some basic style
Thanks
A: Your best bet would be AStyle, however as you said this only does "syntax formatting":
Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android Development general question I'm learning how to write Android apps and am having the same issues I've had with learning languages in general - data types are impossible to deal with!
Why is it so hard to convert data from one type to another?? Why does everything use complex, custom data sets? The issue I'm trying to figure out right now is a good example: Android Location Services API. When I finally get the location data from Android its in this special Location type that doesn't convert to a basic string at all. Using the built in types like whatever.getLatitude() doesn't work either. Again, why is it so hard for API/OS to provide a simple conversion routine??
Example apps tend to never help, even if I get one compiled it still crashes. As a beginner I don't care about making a button work or anything, I want to see location data in a text box - that would be a better intro example app then hello,world.
If anyone would like to give me pointers on how to deal with different data types in Android that will be helpful, but honestly I posted this to hear reasons why data conversion have to be such a headache.
Thanks all!
A: Because Java is Object Oriented Language, and Android API is based on OOP principles. And it's not problem - it's provide benefits to you. For example, your Location can provide too much information and methods on them. Look at the API http://developer.android.com/reference/android/location/Location.html
API provides access to attitude, latitude, longitude, etc. You can try to call toString() methods for debug or logging purposes if you want to look stringified presentation for all these fields. But it's not good way for any other purposes.
A: Whenever I am consuming data that is in a format I'm not a big fan of or contains more information than I need or the information needs to be "translated" in a more suitable form for my purpose, I create my own object model and a translation layer. For example, when I consume a webservice that gives me json or xml data that I need to parse. I just create a package (or namespace if I'm in the .Net world) called model and one called translators. The model objects are the data exactly as my app wants it. The translator classes take in the data and return my object. The same would work for object-to-object translation and not just raw data like json and xml. It takes very little time whatsoever, and when you write yourself helpers (for example, I have a JSONHelper class I created in Java for when I'm working with Android), you just copy it over from project to project making your workflow even faster.
A: This is basic Java/OOP but this is also a question about mapping data-values. For example, you cannot simply attempt to calculate a value of two numbers that are not two numbers.
"6" (a string) does not equal the number value of 6 unless you tell the class to recognize that.
using bastardized Java/C#
String x = new String ("6");
int xi = 6;
return !x.equals( xi)// would actually fail
instead
return xi == Integer.parseInt(x);
So each part of the app and class needs to be able to understand what you are passing as parameters. Get that book Tim recommends or look up some of the various Java tutorials on the Oracle website (or on the web).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Get duplicates for two columns with LINQ LINQ drives me crazy. Why does following query not return the duplicates, whereas it works with only one identifier? Where is my error?
' generate some test-data '
Dim source As New DataTable
source.Columns.Add(New DataColumn("RowNumber", GetType(Int32)))
source.Columns.Add(New DataColumn("Value1", GetType(Int32)))
source.Columns.Add(New DataColumn("Value2", GetType(Int32)))
source.Columns.Add(New DataColumn("Text", GetType(String)))
Dim rnd As New Random()
For i As Int32 = 1 To 100
Dim newRow = source.NewRow
Dim value = rnd.Next(1, 20)
newRow("RowNumber") = i
newRow("Value1") = value
newRow("Value2") = (value + 1)
newRow("Text") = String.Format("RowNumber{0}-Text", i)
source.Rows.Add(newRow)
Next
' following query does not work, it always has Count=0 '
' although it works with only one identifier '
Dim dupIdentifiers = From row In source
Group row By grp = New With {.Val1 = row("Value1"), .Val2 = row("Value2")}
Into Group
Where Group.Count > 1
Select idGroup = New With {grp.Val1, grp.Val2, Group.Count}
Edit: Following is the complete solution, thanks to @Jon Skeet's answer :)
Dim dupKeys = From row In source
Group row By grp = New With {Key .Val1 = CInt(row("Value1")), Key .Val2 = CInt(row("Value2"))}
Into Group Where Group.Count > 1
Select RowNumber = CInt(Group.FirstOrDefault.Item("RowNumber"))
Dim dupRows = From row In source
Join dupKey In dupKeys
On row("RowNumber") Equals dupKey
Select row
If dupRows.Any Then
' create a new DataTable from the first duplicate rows '
Dim dest = dupRows.CopyToDataTable
End If
The main problem with grouping was that i must make them key properties.
The next problem in my above code was to get the duplicate rows from the original table.
Because nearly every row has a duplicate(according to two fields), the result DataTable contained 99 of 100 rows and not only the 19 duplicate values. I needed to select only the first duplicate row and join them with the original table on the PK.
Select RowNumber = CInt(Group.FirstOrDefault.Item("RowNumber"))
Although this works in my case, maybe someone can explain me how to select only the duplicates from the original table if i would have had only composite keys.
Edit: I'v answered the last part of the question myself, so here is all i need:
Dim dups = From row In source
Group By grp = New With {Key .Value1 = CInt(row("Value1")), Key .Value2 = CInt(row("Value2"))}
Into Group Where Group.Count > 1
Let Text = Group.First.Item("Text")
Select Group.First
If dups.Any Then
Dim dest = dups.CopyToDataTable
End If
I needed the Let-Keyword in order to keep the other column(s) into the same context and return only the first row of the grouped dups. On this way i can use CopyToDataTable to create a DataTable from the duplicate rows.
Only a few lines of code overall (i can save the second query to find the rows in the original table) to find duplicates on multiple columns and create a DataTable of them.
A: The problem is the way anonymous types work in VB - they're mutable by default; only Key properties are included for hashing and equality. Try this:
Group row By grp = New With {Key .Val1 = row("Value1"), Key .Val2 = row("Value2")}
(In C# this wouldn't be a problem - anonymous types in C# are always immutable in all properties.)
A: What I use to get duplicate rows across two columns in a EF table to show up as duplicates using Lin-q with C Sharp:
var DuplicatesFoundInTable =
entities.LocationDatas
.Where(c => c.TrailerNumber != null && c.CarrierName != null && (c.TrailerNumber ?? string.Empty) != string.Empty && (c.CarrierName ?? string.Empty) != string.Empty)
.GroupBy(o => new { o.TrailerNumber, o.CarrierName }, l => new { customer.TrailerNumber, customer.CarrierName })
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
When I want to see if it is a duplicate on inputs (if the entry already exists in two columns):
//Check to see if any rows are the same values on TrailerNumber and CarrierName for inputs.
bool AlreadyInTableComparer = entities.LocationDatas.Any(l => String.Compare(l.TrailerNumber, customer.TrailerNumber, StringComparison.InvariantCulture) == 0 && String.Compare(l.CarrierName, customer.CarrierName, StringComparison.InvariantCulture) == 0);
bool AlreadyInTable = entities.LocationDatas.Any(t => t.TrailerNumber == customer.TrailerNumber && t.CarrierName == customer.CarrierName);
SQL Server Checking for duplicates (commented out delete duplicates):
WITH CTE
AS
(
SELECT [TrailerNumber], [CarrierName]
,ROW_NUMBER() OVER(Partition BY TrailerNumber Order by TrailerNumber,
CarrierName) AS NumRows, ROW_NUMBER() OVER(Partition BY TrailerNumber,
CarrierName Order by CarrierName) AS NumRows2
FROM [dbo].[LocationData] --Please note, duplicates are shown in this
table.
WHERE TrailerNumber != '' AND CarrierName != ''
)
SELECT [TrailerNumber], [CarrierName], [NumRows2] FROM CTE WHERE NumRows2 > 1
--DELETE FROM CTE WHERE NumRows2 > 1 --Delete Duplicates.
Validate SQL Server to prove correct against CTE filtering:
SELECT TrailerNumber, CarrierName, COUNT(*) AS Duplicates
FROM [dbo].[LocationData]
WHERE TrailerNumber IS NOT NULL OR CarrierName IS NOT NULL
GROUP BY TrailerNumber, CarrierName
HAVING COUNT(*) >1 AND TrailerNumber != '' AND CarrierName != ''
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problem creating Facebook application with heroku I am trying to create a canvas Facebook application.
I have created Heroku application written in ruby via Facebook.
Creating the application I followed the steps of these guides:
http://devcenter.heroku.com/articles/facebook
http://devcenter.heroku.com/articles/configuring-your-facebook-app-as-a-canvas-page
After following these steps when I go to the application it says
Not Found
When I put it in Facebook's Object Debugger it says:
Extraneous Property - Objects of this type do not allow properties named og:site_url.
How can I fix this?
Thanks,
Oded
A: The canvas app POST's to '/'.
The heroku template is expecting GET.
See the following to accept both GET and POST's:
http://ujihisa.blogspot.com/2009/11/accepting-both-get-and-post-method-in.html
Change
get '/' do ...
to...
def get_or_post(path, opts={}, &block)
get(path, opts, &block)
post(path, opts, &block)
end
get_or_post '/' do...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to specify width and height of a drawable item Hi is there anyway of providing width and height of a drawable defined in drawable.xml in drawable folder.
Example:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>
I wanted to specify width and height maybe somehow using "scale" tag inside it which i tried but didnt worked. This is my code:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/icon_ratingstar">
<scale android:scaleWidth="20" android:scaleHeight="20" android:drawable="@drawable/icon_ratingstar" />
</item>
</selector>
A: layer-list will help: here change values according to your requirement
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<size
android:width="20dp"
android:height="20dp" />
<solid android:color="@android:color/black" />
</shape>
</item>
<item
android:width="20dp"
android:height="20dp"
android:drawable="@drawable/slider_knob" />
A: You can use attribute width and height in API level 23 and higher:
<item
android:width="18dp" android:height="18dp"
android:drawable="@drawable/icon_ratingstar"/>
For lower API levels, I do not know a way of specifying width and height directly. The best practice is scaling drawables as far as I know.
A: With selector and drawable you can do it like this for example:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" >
<layer-list>
<item android:drawable="@drawable/your_first_drawable"
android:height="25dp" android:width="25dp"/>
</layer-list>
</item>
<item android:state_checked="false" >
<layer-list>
<item android:drawable="@drawable/your_second_drawable"
android:height="25dp" android:width="25dp"/>
</layer-list>
</item>
</selector>
A: You can specify inside the <item> tag the width and height of the drawable:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:width="100dp"
android:height="20dp"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:width="100dp"
android:height="20dp"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How to Fade content of a div? I am new to OPA. I can replace the content of the div using DOM.transform but I want to fade that content before replacing with new one.
How do I do it?
Basically, how do I use Dom.Effect? A code snippet will help.
Thanks
A: This snippet may help you:
effect() =
_ = Dom.transition(#content, Dom.Effect.fade_out())
void
main =
<h1 id=#content onclick={_ -> effect()} >Content</h1>
server = one_page_server("Hello", -> main)
It fade-out the title when clicking on it.
Check https://opalang.org/resources/doc/index.html#dom.opa.html/!/value_stdlib.core.xhtml.Dom.Effect
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Edit Image in Photoshop I need to send an image from my application, edit it in Photoshop and return it back.
My application should wait until the Photoshop Document is closed.
Any ideas please.
A: Something like this..
MyProcess myProcess = new MyProcess();
myProcess.Start("photoshop.exe", "C:\\myImages\\image.jpg");
while (!myProcess.HasExited) {
// Do nothing while waiting.. Sleep for a few seconds might be a good idea
}
// Will be executed when process is closed.
A: Process.Start("pathtoshotoshop.exe", "someimage.jpg").WaitForExit()
A: If you know the file name, you can check the date stamp until it's after the edit starts. You should also check the file attributes and make sure the file is not still open by PhotoShop.
You can use a timer to check every few seconds, instead of checking constantly which would slow down the system.
A: Process.Start(Path.Combine(path, "image.psd"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Search query doesn't work in solr/browse panel When I create a query like something&fl=content in solr/browse the "&" and "=" in URL converted to %26 and %3D and no result occurs. How can I solve this problem?
Is it possible to change the request from the GET method to a POST?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP Getting unique values from multidimensional array inside a multidimensional array I'm trying to get values from a multidimensional array inside a multidimensional array. Here is the multidimensional array...
Array
(
[0] => Array
(
[CalID] => 121111
[Rink] => North
[TimeChunks] => Array
(
[int] => Array
(
[0] => 6
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
)
)
[1] => Array
(
[CalID] => 121111
[Rink] => South
[TimeChunks] => Array
(
[int] => Array
(
[0] => 4
[1] => 2
)
)
)
)
I want to get only the valid time chunks from [TimeChunks][int] ie: 1,2,3,4,6,8 but I can't seem to drill down to the second multidimensional array. Here is what I've been trying with no dice:
$tmp = array ();
foreach ($a as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
print_r ($tmp);
Any suggestions?
A: You're not looping through the array in the 'TimeChunks' key in your array at all, try this:
foreach ($a as $row) {
foreach ($row['TimeChunks'] as $chunk) {
if (!in_array($row,$chunk)) array_push($tmp,$$chunk);
}
}
A: Something like this?
$tmp = array();
foreach ($array as $section) { // Loop outer array
if (isset($section['TimeChunks']['int'])) { // make sure ['TimeChunks']['int'] is set for this inner array
foreach ($section['TimeChunks']['int'] as $chunk) { // Loop the time chunks
$tmp[] = $chunk; // Push the chunks onto the $tmp array
}
}
}
$tmp = array_unique($tmp); // Remove duplicate values
print_r($tmp);
You have to loop through the outer array, get the contents of the ['TimeChunks']['int'] key and push that onto the $tmp array. You can do an in_array() check on each iteration, but it would be more efficient (less function calls) to add them all to the $tmp array and pass it through array_unique() afterwards.
A: why not use foreach($a as $key=> $value)
then you can use your if statement on the keys and values if you want
A: $tmp = array();
foreach ($a AS $row) {
if (isset($row['TimeChunks']['int']) && is_array($row['TimeChunks']['int'])) {
$tmp = array_merge($tmp, $row['TimeChunks']['int']);
}
}
$tmp = array_unique($tmp);
If the array keys aren't important to you, this should do the trick. It just combines all the values in the different [TimeChunks][int] and then removes the duplicates afterwards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Placing the x-axis labels between period ticks I would like to place the x-axis labels between the ticks.
For example, by default R produces a graph that looks like this:
(Note, I added axis(1,c(2001,2002,2003,2004,2005,2006,2007,2008,2009,2010)) to give the larger amount of label years, otherwise R only uses 2002 2004 2006 2008 2010 as labels.)
But I want to move the labels such that the plot looks like this:
I tried looking, but I don't even know what it's called doing this.
A: You can offset the labels and the ticks with separate calls to axis.
(The example below does not look much like your data, but the idea is the same.)
Plot whatever, but keep the axes off.
plot(1:10, axes = FALSE)
Plot the labels at a half spacing offset and turn off the ticks. (Reverse the numbers just to be "interesting").
axis(1, at = (1:10) + 0.5, labels = 10:1, tick = FALSE)
Add the ticks back at the normal position, and keep the labels off. Add a box to finish the job.
Be careful though, the labels are now kind of ambiguous in terms of which tick they refer to, and what the tick position actually is (though for a year start to end that should not be a problem).
axis(1, at = (1:10), labels = FALSE, tick = TRUE)
box()
You can use axis(2, ...) to construct the y-axis in the same way, or just use defaults with axis(2).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: iOS - Notification of when a call is taking place? Is it possible to be notified or detect when a GSM/CDMA call is taking place on an iOS handset?
I have an application that uses audio in the background and I want to be able to detect when a call is taking place so that my app can react accordingly so as not to intrude on the cellular call in anyway.
Essentially I want to be able to detect when a call is taking place so that if the user enters my application while on a call I can disable some functionality.
So I was wondering how I can detect that a cellular call is taking place on a device?
A: As of iOS 4, you can use the CTCallCenter class in the Core Telephony framework to register an event handler so your app gets notified when a call starts or ends. The CTCall it gives you has a callState property, which can be CTCallStateDialing, CTCallStateIncoming, CTCallStateConnected, or—when it ends—CTCallStateDisconnected.
A: As of iOS 6, you should:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioInterruption:) name:AVAudioSessionInterruptionNotification object:session
and then:
- (void)onAudioInterruption:(NSNotification*)notification
{
NSDictionary *info = notification.userInfo;
NSUInteger type = [[info valueForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
if (type == AVAudioSessionInterruptionTypeBegan) {
// stop audio (or whatever)
} else if (type == AVAudioSessionInterruptionTypeEnded) {
// restart audio (or whatever)
}
}
A: Look at AVAudioSessionDelegate protocol.
A: You can use CoreTelephony framework.But you must user some private api.And I have some demo code for this. https://github.com/edison0951/AppNotifyBySMSDemo. And the finally solution is MAP.this is the same with SMS notifications in iOS6
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Exception being thrown from StaticPropertyWatcher.as Recently, I suddenly began getting the current exception being thrown from a Flex library. The file I was working on (Login.mxml) suddenly began throwing up this exception while loading.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mx.binding::StaticPropertyWatcher/updateParent()[E:\dev\4.x\frameworks\projects\framework\src\mx\binding\StaticPropertyWatcher.as:150]
at _components_LoginWatcherSetupUtil/setup()
at components::Login()[C:\Users\username\Documents\MP_MAIN\src\components\Login.mxml:0]
<snip ...>
at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\4.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:700]
at mx.managers::LayoutManager/doPhasedInstantiationCallback()[E:\dev\4.x\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1072]
Running it in the debugger doesn't give me a line of my code that is in error, but it does give me a line in StaticPropertyWatcher. Specifically:
override public function updateParent(parent:Object):void
{
// The assumption is that parent is of type, Class, and that
// the class has a static variable or property,
// staticEventDispatcher, of type IEventDispatcher.
parentObj = Class(parent);
if (parentObj["staticEventDispatcher"] != null) /* Exception thrown from here */
{
...
The debugger shows the parentObj is indeed null, explaining the immediate reason for the exception, but I can't seem to determine the deeper cause (i.e. what I did wrong). The updateParent method is being called from the _components_LoginWatcherSetupUtil class, but the debugger says there is no code for that, so the crucial connection between what I wrote and what caused the exception is missing.
So, basically, I can't even debug this. Any ideas for what to do to shed light on what's going wrong?
A: Your error is being reported as Login.mxml:0
When I see line 0 as the error it tells me that there is a syntax error of some sort. Open string maybe?
I would suggest looking at the file and see if it is set up properly.
Post the full Login.mxml file and let us look at it.
A: After laboriously adding back every change I made since last committing to my repository, I tracked down the culprit to this problem. Basically, there were several static variables used to keep track of server addresses like this:
public static var MAIN:String = "http://192.168.1.1/";
public static var MANAGE:String = MAIN + "Manage/";
The issue was that I used a non-compile-time constant MAIN to initialize MANAGE. Changing these variables to const fixed the problem.
public static const MAIN:String = "http://192.168.1.1/";
public static const MANAGE:String = MAIN + "Manage/";
Hopefully this will help anyone else coming across this problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When and who to detach observers when the observer has longer life span than the observable I encountered this problem using a third party library provided by a different group in the company (written in C++).
In the destructor of Observer, it detaches itself from all observables it subscribes to, this part makes sense to me. But in the destructor of Observable, it checks if the observable has any observer that's still in it's subscriber list. If so, throws an error.
I am going to put the fact that it intentionally throws an error in the destructor aside. Can someone try to explain to me the why the observable should expect no observers to outlive itself or is this just a bad design. If this is a bad design, when we are in circumstances when the observer outlives the observable, are there good ways to handle it?
A: If the Observer has a pointer (or reference) to the Observable, and the Observable is destroyed, that pointer will be invalid. The author is just trying to avoid dangling references.
There are three usual solutions, I think.
One is to do exactly what this code does, perhaps calling abort() rather than throwing an exception in the destructor.
Another is to have the Observable's destructor de-register itself from any Observers.
The last is to use "smart pointers" (e.g., a reference-counted shared_ptr) to guarantee that the Observable outlives any Observer.
A: It depends on the context. I would expect a totally generic
implementation of the observer pattern to support deleting an observed
object, at least optionally, but there are a lot of uses where this
doesn't make sense, and is probably a programming error. In general,
before the observable fully destructs, it should notify its observers of
the fact that it will destruct; they should then unenrol. Which means
that by the time the destructor of the observable registry object is
called, there should be no registered observers.
A: I usually implemented the pattern the other way around- the Observable adds itself and takes itself away from the Observer's list. My Observer lives throughout the whole lifetime of the application, and the Observables live a few seconds, typically.
A: It's just bad design, nothing guarantees that the observable will outlive all of its observers.
If you have access to the observable's destructor, rewrite it so it will detach all of its observers remaining.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Hide an element without masking item over top I've created an effect whereby an HTML element is initially hidden behind another HTML element, and the CSS 'top' value of the hidden element is animated to expose it from beneath the masking element in a smooth sliding motion.
Does anyone know if there is a way to recreate this effect without the masking element on top?
I want to avoid the jQuery'esque slideDown where the height of the element being shown is animated.
I have the feeling that this just isn't possible, but if someone is otherwise aware, your advise would be much appreciated.
A: You can easily do this with a wrapper that has overflow set to hidden
http://jsfiddle.net/xvNf6/1/
HTML
<div id="wrapper" style="height:0px;">
<div>content</div>
</div>
Sample CSS
#wrapper{width:300px;height:280px;margin:0 auto; overflow:hidden; background:#eee}
Javascript
//if you must not use jQuery
var animationTimer = setInterval(function(){
var wrapper = document.getElementById("wrapper");
wrapper.style.height = (parseInt(wrapper.style.height) + 1) + "px";
if(parseInt(wrapper.style.height) >= 280)
clearInterval(animationTimer)
},1);
//if you can use jQuery
$("#wrapper").animate({height:"280px"},1000);
A: Place your element within a parent div with overflow:hidden. Then, position your element beyond bounds of the parent div so that it is hidden.
#wrapper { overflow: hidden; }
#target { height: 100px; top: -100px; } /* shift element out of view */
You can then reveal it by animating to {"top":0} to get the slidedown effect that doesn't resize the height of the element.
Here's a rather crude demo: http://jsfiddle.net/7RSWZ/
Update: Here's another demo that attempts to deal better with different content sizes by dynamically setting the heights and top values. http://jsfiddle.net/7RSWZ/2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Generic trim function in java? i have a requirement, where i need to develop a single method which accepts any type of paramter(String or Integer etc) and applies trim() to remove leading and trialing spaces. please help me how to write generic method to achieve this?
Thanks!
A: Java has strictly defined types, it's not PHP or Javascript. Integer does not have spaces. Simply use trim() method of String object. If your 'integer' is actually a string, do (String.valueOf(x)).trim()
A: It does not make a lot of sense, but here it goes:
public String trim(Object o) {
if (o != null) {
return o.toString().trim();
}
return null;
}
A:
if an integer is like 12345---. --- indicates 3 spaces. how can i remove? do i need to convert it to string before trimming?
If an 'integer' has trailing spaces, it is already the string representation of the integer, not the integer itself. Therefore:
String i = "12345 ";
String trimmed = i.trim();
By contrast, the following is simply not legal
int i = "12345 "; // compilation error
and a string representation of an integer produced like this:
String i = String.valueOf(12345);
will not have leading or trailing whitespace.
A: In java, all objects have .toString() method which returns string representation of that object.
You can then call .trim() method on that string, so your function may look like this:
public static String trimAny(Object o) {
return o.toString().trim();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are CLR wrappers for dependency properties optional or not? I was under the impression that CLR wrappers for dependency properties were optional under WPF, and just useful for setting within your own code.
However, I have created a UserControl without wrappers, but some XAML that uses it will not compile without them:
namespace MyControlLib
{
public partial class MyControl : UserControl
{
public static readonly DependencyProperty SomethingProperty;
static MyControl()
{
SomethingProperty = DependencyProperty.Register("Something", typeof(int), typeof(MyControl));
}
}
}
XAML usage:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrl="clr-namespace:MyControlLib;assembly=MyControlLib">
<ctrl:MyControl Something="45" />
</Window>
Trying to compile this gives:
error MC3072: The property 'Something' does not exist in XML namespace 'clr-namespace:MyControlLib'. Line blah Position blah.
Adding a CLR wrapper in MyControl.xaml.cs like:
public int Something
{
get { return (int)GetValue(SomethingProperty); }
set { SetValue(SomethingProperty, value); }
}
means it all compiles and works fine.
What am I missing?
A: You could use dependency properties without wrappers inside runtime bindings, but to set the property like you want you must have C# property to allow xaml compiler to compile your code.
A: I believe it will compile without the wrappers if you specify the namespace prefix on the property.
They are optional, but without them the property does not show up in the XAML designer automatically
<ctrl:MyControl ctrl:MyControl.Something="45" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: using SQL Server Compact Edition in ASP.NET websites I know next to nothing about databases, but need to store and present user input on my ASP.NET tiny website (up to several thousand records). Should I consider SQL Server Compact Edition? In Microsoft docs I found:
SQL Server Compact 3.5 is not currently optimized to serve as a database for Web sites. By default, connections from ASP.NET-connected applications are blocked in SQL Server Compact 3.5. SQL Server Compact 3.5 is optimized for use as an embedded database within applications. Using SQL Server Compact 3.5 as a database for Web sites requires support for multiple users and concurrent data changes. This can cause performance problems. Therefore, these scenarios are not supported. Other editions of SQL Server, including SQL Server 2005 Express Edition and later versions, are optimized to serve as a database for Web sites.
But then I remember reading some user comment that the 4.0 version of SQL Server CE is finally working OK in ASP.NET scenario. Anyone care to share his experience? I would like to try CE first as SQL server requires additional fee on my hosting.
A: From the download site for SQL Server Compact 4.0:
Microsoft SQL Server Compact 4.0 is a free, embedded database that software developers can use for building ASP.NET websites and Windows desktop applications.
And:
SQL Server Compact 4.0 enables new scenarios and includes a host of new features, including the following:
*
*SQL Server Compact 4.0 is the default database for Microsoft WebMatrix, which is a stack of web technologies for easily building and deploying websites on the Windows platform.
(emphasis mine)
In conclusion - it has specifically been enhanced for web scenarios.
A: Yes, SQL Server Compact 4.0 has been designed with scenarios similiar to yours in mind.
New Embedded Database Support with ASP.NET
SQL CE is a free, embedded, database engine that enables easy database storage.
No Database Installation Required
SQL CE does not require you to run a setup or install a database
server in order to use it. You can simply copy the SQL CE binaries
into the \bin directory of your ASP.NET application, and then your web
application can use it as a database engine. No setup or extra
security permissions are required for it to run. You do not need to
have an administrator account on the machine. Just copy your web
application onto any server and it will work. This is true even of
medium-trust applications running in a web hosting environment.
SQL CE runs in-memory within your ASP.NET application and will
start-up when you first access a SQL CE database, and will
automatically shutdown when your application is unloaded. SQL CE
databases are stored as files that live within the \App_Data folder of
your ASP.NET Applications.
Visual Studio 2010 SP1 includes new tooling support for SQL CE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I put Powerpoint and Excel documents in a full text search index like Sphinx or PostgreSQL text search? I have a Rails application that accepts file uploads of arbitrary business documents such as from Word, Excel, Powerpoint, and PDF. I need to make all these documents searchable, preferably using Sphinx or PostgreSQL full text search. What are the best solutions?
A: As pointed out in the comments, this is covered pretty well by an older question.
In short: you're going to have to store the relevant extracted data from those files in the database for Sphinx, and likely for PostgreSQL full-text search as well. Sphinx can now also understand plain text files (as long as a database column points to a file), but that will still involve another tool extracting data from PDF, DOC, XLS et al.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to unsubscribe the NServiceBus subscription? If I choose to use the auto subscription in NServiceBus pub sub model, the system does not auto unsubscribe when the client exists.
I can always do a manual unsubscribe, but I having trouble figuring out the existing list of subscriptions and I don't want to hard code the unsubscribe.
So my question is: is there an auto-unsubscribe function in nservicebus? If not, how can I get a list of current subscriptions for a client?
A: I don't think you are going to find an auto-unsubscribe. Udi and company have intentionally designed NServiceBus to make it hard to do things that don't fit the async, pub/sub SOA pattern. Generally, the fact that the client is running or not running would not affect whether or not the subscription is still valid. If that is really what you need, you'll probably have to code that in yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JButton stays in pressed state In my Java GUI app I have a JButton and when clicked it calls a function to connect to a database, then calls a function to clear a table in the DB, then calls a function that reads text from one file and loads variables, which calls a function that reads text from another file, compares the data from both and then calls a function to either update or insert data in the DB, all of that works fine.
However my question is related to the JButton, when its clicked I want to run a Indeterminate progress bar just so the user knows work is being done and then right before it leaves the the action listener setIndeterminate to false and set the value of the progress bar to 100(complete), but in my case when you click the button it stays in the clicked state and the progress bar freezes.
What should I implement to prevent this? threading possibly? but Im quite new to threading in java. here is my action listener:
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if( e.getSource() == genButton )
{
progressBar.setIndeterminate(true);
progressBar.setString(null);
try
{
dbConnect(); //connects to DB
clearSchedules(); // deletes data in tables
readFile(); // reads first file and calls the other functions
dbClose();// closes the DB
progressBar.setIndeterminate(false);
progressBar.setValue(100);
}
catch (Exception e1){
System.err.println("Error: " + e1.getMessage());
}
}
}
}
On a side note, I would like to have the action bar actually move as the the program progresses but I wasnt sure how to monitor its progress.
Thanks, Beef.
UPDATE here is my example of SwingWorker and how I used it:
Declared globally
private functionWorker task;
private abstract class functionWorker extends SwingWorker {
public void execute() {
try {
dbConnect();
} catch (SQLException e) {
e.printStackTrace();
}
clearSchedules();
try {
readFile();
} catch (IOException e) {
e.printStackTrace();
}
dbClose();
}
}
Inside my actionPerformed method
if( e.getSource() == genButton )
{
progressBar.setIndeterminate(true);
progressBar.setString(null);
try
{
task.execute();
progressBar.setIndeterminate(false);
progressBar.setValue(100);
}
catch (Exception e1){
System.err.println("Error: " + e1.getMessage());
}
}
A: The problem is probably related to connecting to doing expensive operations in the UI thread (connecting to a database, reading from a file, calling other functions). Under no circumstances should you call code that uses excessive CPU time from the UI thread, as the entire interface can't proceed while it is executing your code, and it results in a 'dead' looking application, with components remaining in their state at the time before an expensive operation until completion. You should execute another thread, do the expensive work in that, and then use a SwingUtilities.invokeLater(Runnable doRun) with a passed runnable where you'd update the progress.
There may be synchronisation issues relating to the states of components, but you can fix these later.
A:
Could I create the new thread when the action is performed and call the new functions in the thread, or should I do the threading within the actual function itself?
You can start a SwingWorker from your button's handler, as shown here. A related example implementing Runnable is seen here.
A: One method to handle progressbars are to extend SwingWorker in a class.
SwingWorker takes care of running background tasks for you and so you do not have to implement your own threading that can end up in unknown issues.
To begin with, your class that takes care of progress bar UI should implement PropertyChangeListener
And implement public void propertyChange(PropertyChangeEvent evt) { - to update the progressbar status based on a global variable.
The background task class should look like the following(this could be an inner class) :
class ProgressTask extends SwingWorker<Void, Void> {
@Override
public Void doInBackground() {
//handle your tasks here
//update global variable to indicate task status.
}
@Override
public void done() {
//re-enabled your button
}
}
on your button's event listener :
public void actionPerformed(ActionEvent evt) {
//disable your button
//Create new instance of "ProgressTask"
//make the task listen to progress changes by task.addPropertyChangeListener(this);
//calll task.execute();
}
I have tried to water down code example, you would have to read some tutorial to understand how all these pieces fit together. However, the main point is do not code your Threads, instead use SwingWorker
A: progressBar.setIndeterminate(true);
progressBar.setValue(0);
dbConnect(); //connects to DB
progressBar.setIndeterminate(true);
progressBar.setValue(10);
clearSchedules(); // deletes data in tables
progressBar.setIndeterminate(true);
progressBar.setValue(50);
readFile(); // reads first file and calls the other functions
progressBar.setIndeterminate(true);
progressBar.setValue(75);
dbClose();// closes the DB
progressBar.setIndeterminate(false);
progressBar.setValue(100);
You will need to tell the progress bar how much progress has been made because it does not know the percentage completed. Better yet, write a method that updates and repaints the progress bar rather than repeating the method calls here.
updateProgressBar(int progress, boolean isDeterminate, String msg){};
You will also need to make sure that your specific button is firing the action performed.
class IvjEventHandler implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (e.getSource() == JMyPanel.this.getJButtonUpdate())
connEtoC1(e);
};
};
The connEtoC1(e); should execute a controller class or SwingWorker rather than firing from the GUI
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Trigger a button click inside a jQuery UI Dialog it is a very simple question that I'm not finding an answer for it. I have a dialog and in some events happening inside the dialog I want to click one of the dialog buttons. The code which defines the dialog is:
var dialog = $('<div>').dialog({
autoOpen: false,
title : title,
resizable : false,
buttons : {
'CANCEL' : {
text : messages.Cancel,
click : function(){$(this).dialog('close')}
},
'OK' : {
text : messages.Ok,
click : okButtonCallback
}
}
});
and in my event I can get the dialog, find the buttons but I can not trigger the click event with right reference passed as this. I do this:
buttons = dialog.dialog('option', 'buttons');
and I have the buttons each of them has the click function. If called directly or through trigger('click'), they call the click event of button but with the button itself as this not the dialog object.
I saw somewhere to call
buttons['OK'].apply(dialog);
but my buttons have absolutely no apply function!
I'm not sure what can I do!
A: What I use is:
// Get the buttons
var buttons = $("#myDialog").dialog("option", "buttons");
// Calls the event
buttons["OK"]();
A: First of all, you need to get buttons[0] not buttons['OK'], then, it's not a function it's an object, try to get to click function like this :
buttons[0].click.apply(dialog);
A: $('.ui-button:contains("Ok")').click()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: StatusStrip label formats my text backwards I've been having this problem for a few days. Whenever I update a label in a StatusStrip object it formats my text backwards. I send my label something like
toolStripVoltage.Text = batteryVoltage.ToString("F2") + " V";
and the label will display V 2.82.
and when I send it something like
toolStripVoltage.Text = batteryVoltage.ToString("0.00 V");
it will display the same thing. It seems like no matter how I format the string the "V" goes before the numbers. and! it still puts a space in between the unit and the number. And here's the kicker: when I call this same text to appear in a tooltip of another object like this
toolStripVoltage.ToolTipText = toolStripVoltage.Text;
It displays as 2.82 V. Any ideas on how I can make this work for me?
EDIT:
oh wow. I instantly figured this out somehow...the default RightToLeft property is Yes. I don't know why that would be! but the trick was to set that to No. Very strange for that to be the default setting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP MVC 3 - How to define a dynamic value to the base of url? I would like to "show" a dynamic value to the base of the URL, so the url would be like this: host.com/SOME_VALUE/{area}/{controller}/{action}.
So, if a url without the first value (the dynamic value) is requested: host.com/{area}/{controller}/{action} the correct action should be called but when a view is rendered (or maybe when a redirect occurs) the correct url should be returned with the correct first value.
This solution would be useful only to show in the url a specified value the identifies the user logon, like the username or maybe the company name, or any other value related to the current session, this value won't be used to restricts access to the actions, so the both urls should be valid and call the same action on then same session:
host.com/{area}/{controller}/{action}
host.com/some_value/{area}/{controller}/{action}
Any suggestions ?
A: This is completely untested but i'd have thought it would work...
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"MyRoute", // Route name
"{somevalue}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Would it be possible to add an additional static value to the URL when the somevalue part is used? i.e. host.com/users/some_value/area/controller/action. It would make the route mapping simple as all you'd need is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"LoggedInUsers", // Route name
"Users/{somevalue}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery ".triggerHandler()" vs. ".trigger()" when multiple elements are selected The jQuery ".triggerHandler()" mechanism, unlike ".trigger()", only operates on the first element referenced by the jQuery object for which it's called. In other words,
$('.all-over-the-page').triggerHandler("readjust");
will only call the "readjust" handler for the first element with class "all-over-the-page", even if there are many elements on the page with that class. The ".trigger()" method, on the other hand, would affect all of them.
I realize that I can use ".each()" to get around this (or simply write my own substitute that does that for me), but is there some rationale for why the two are different in this respect? It kind-of makes no sense to me. (I understand of course that it almost certainly can't be changed now.)
edit to clarify:
It's probably easier to understand why I'm scratching my head over this if I provide a context in the style of code I've actually got. When I put together code for various "widget" features on a page, that often involves event handlers. A good example is a form of some sort that's got some fields whose relevance is controlled by a checkbox, or radio button, or selector. A common instance of that is the "Shipping Address" checkbox that shows up on a zillion e-commerce sites: if the checkbox is checked, the shipping address is disabled and the billing address is used.
Now consider that some other code may, for its own reasons that are totally independent of the checkbox-control widget, actually do things to the form that may include updating checkbox settings programmatically. In that case, that other widget code may want to use "triggerHandler()" to tell any widgets, "hey I've updated some stuff, so you might want to re-check the current status and adjust if necessary."
Thus, if ".triggerHandler()" would operate on all selected elements, I could use:
$theForm.find('input, select, textarea').triggerHandler('change');
and all those handlers could run and do whatever they need. As I said, it's easy enough to write:
$theForm.find('input, select, textarea').each(function() {
$(this).triggerHandler('change');
});
A:
"...is there some rationale for why the two are different in this respect?"
I think the idea is that triggerHandler() is meant to be a way of invoking the function you as a handler as though it was any other function.
As such, they made triggerHandler() so that the function is only invoked once, it returns the actual return value of the function, and it doesn't affect the DOM with bubbling or default behaviors.
Of course the function may break if they changed the this value to something other than a DOM element, so they just use the first element matched.
If you're wanting to simply use your function, then I'd probably just keep a reference to it and invoke it directly, or as the argument to .each().
$('.element').each( handler_func );
...as long as you don't need the event object.
EDIT: Or if you want the values returned from the invocation, use .map() instead:
var return_values = $('.element').map( handler_func );
EDIT: With respect to the example provided in the updated question, a good solution may be to take advantage of the extraParameters capability of the trigger()[docs] method so that you can tell the handler to preventDefault() and stopPropagation().
$('.elememts').bind( 'click', function( e, was_code_triggered ) {
if( was_code_triggered ) {
e.preventDefault();
e.stopPropagation();
}
// your code
});
// ...
$('.elememts').trigger( 'click', true ); // pass "true" to let handler know
// it wasn't a DOM event
From the .trigger() docs:
"Note the difference between the extra parameters we're passing here and the eventData parameter to the .bind() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered, while the eventData argument to .bind() requires the information to be already computed at the time the handler is bound."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: JSON Encode and curly quotes I've run into an interesting behavior in the native PHP 5 implementation of json_encode(). Apparently when serializing an object to a json string, the encoder will null out any properties that are strings containing "curly" quotes, the kind that would potentially be copy-pasted out of MS Word documents with the auto conversion enabled.
Is this an expected behavior of the function? What can I do to force these kinds of characters to covert to their basic equivalents? I've checked for character encoding mismatches between the database returning the data and the administration page the inserts it and everything is setup correctly - it definitely seems like the encoder just refuses these values because of these characters. Has anyone else encountered this behavior?
EDIT:
To clarify;
MSWord will take standard quotation marks and apostraphes and convert them to more aesthetic "fancy" or "curly" quotes. These characters can cause problems when placed in content managers that have charset mistmatches between their editing interface (in the html) and the database encoding.
That's not the problem here, though. For example, I have a json_object representing a person's profile and the string:
Jim O’Shea
The UTF code for that apostraphe being \u2019
Will come out null in the json object when fetched from database and directly json_encoded.
{"model_name":"Bio","logged":true,"BioID":"17","Name":null,"Body":"Profile stuff!","Image":"","Timestamp":"2011-09-23 11:15:24","CategoryID":"1"}
A: Never had this specific problem (i.e. with json_encode()) but a simple - albeit a bit ugly - solution I have used in other places is to loop through your data and pass it through this function I got from somewhere (will credit it when I find out where I got it):
function convert_fancy_quotes ($str) {
return str_replace(array(chr(145),chr(146),chr(147),chr(148),chr(151)),array("'","'",'"','"','-'),$str);
}
A: json_encode has the nasty habit of silently dropping strings that it finds invalid (i.e. non-UTF8) characters in. (See here for background: How to keep json_encode() from dropping strings with invalid characters)
My guess is the curly quotes are in the wrong character set, or get converted along the way. For example, it could be that your database connection is ISO-8859-1 encoded.
Can you clarify where the data comes from in what format?
A: If I ever need to do that, I first copy the text into Notepad and then copy it from there. Notepad forces it to be normal quotes. Never had to do it through code though...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Python IRC bot with support for plugins and not command only I have just made a script in Python which will connect to my MySQL database every XX second and check for new posts on my forum. If there are any new posts, I would like to have the user's of my IRC channel notified.
To do this I need to hook up my script with an IRC bot.
I have been searching around to find an IRC bot which supports plugins which are not only called by commands (e.g. ".google example") as I would like my script to be running constantly and when new posts are found have the bot print a message.
Does anyone know of an IRC bot which would allow me to do that?
A: You could always take a look at Twisted, which is supposed to make it very easy for you to create your own IRC bot:
http://twistedmatrix.com/documents/10.0.0/api/twisted.words.protocols.irc.IRC.html
A: you should easily find a python IRC client library which would let you do (almost) anything you want directly from your python script.
the Python Package Index (aka. pypi) lists some irc client libraries...
A: As a kind of shameless plug, I will point to the IRC bot that I have developed with ease of extensibility in mind (via plugins and custom commands):
*
*http://github.com/Xion/seejoo
While its plugins are generally meant to be driven by IRC events (such as an user joining a channel) and not a time-based "ticks", I think it would be feasible to utilize the "someone said something on channel" (message) event as a trigger for your database poll.
If you would like to play with this thing, I recommend looking at already existing plugins - especially the memo one.
A: I am using the Twisted Library as suggested by @Fabian. Following the guide below, you will end up having a good skeleton for an IRC but which is easily extendable with your own plugins.
http://www.eflorenzano.com/blog/post/writing-markov-chain-irc-bot-twisted-and-python/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: function MySQL does not exist I'm creating my first function, with the following code:
CREATE FUNCTION CTRLPRODUCAO.COMPARATOTAIS (AG INT, P INT, ANO INT)
RETURNS BOOLEAN DETERMINISTIC
BEGIN
(...)
END
When I run the command, received the return of the Workbench: "0 row (s) affected". Is it ok?
When I run
SELECT CTRLPRODUCAO.COMPARATOTAIS (1, 9, 2011) AS TEST;
I get
"Error Code: 1305 FUNCTION CTRLPRODUCAO.COMPARATOTAIS does not exist"
What am I doing wrong?
A: You can't insert a . in your function name.
As far as i know, in MySQL, the . is interpeted as a kind of join and in your example, MySQL is looking for the function COMPARATOTAIS in CTRLPRODUCAO table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: facebook Graph API post to wall doesn't accept new line I am developing a small application for facebook.
In my application I post content to a fan page's wall.
When the user enters a new line character the post completely ignores it. How can I solve this?
A: IF you send the following text
hello%0Aline+2
The posted message will look like
hello
line 2
Checked it right now:)
A: this work fine for me:
// first: replace normal \n (or "\\n") for "\r\n"
$mensaje=str_replace("\\n","\r\n",$reg['mensaje']);
// second: this only is for clear special characters
$mensaje=utf8_encode($mensaje);
A: Use html_entities, otherwise the POST request is not transferred properly.
A: use \r\n without any spaces in facebook graph api then you will get line break
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7530999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Javascript access to hardware? I work for a company that has web and mobile apps. They are going to implement some changes to get a device ID from mobile AND web browser based system. Looks like Javascript has some ability to get hardware info like motherboard serial number etc. I was a bit shocked by this since I though my desktop browser was somewhat limited in this respect.
So, my question to this group is:
*
*Is this true for WIN/MAC/Linux desktop systems running different browsers?
*Anyway to block this and have some control over what unscrupulous vendors/agencies can strip mine from my system?
A: This is completely false.
In-browser Javascript (without the use of plugins) has no hardware access, and (I strongly assume) never will have.
A: In general, browser makers (such as Microsoft's IE, Google Chrome, Mozilla Firefox, etc) do not supply JavaScript mechanisms for accessing specific hardware information.
However, in some browsers (especially "legacy" browsers such as IE6) the use of ActiveX, plugins, Java Applets, or even specific browser exploits can reveal this kind of information by executing code outside of the secure confines of the browser. What platform does your employer expect this information to be retrieved from?
Here's an example using ActiveX through JavaScript.
I have personally tested this code in IE8. It correctly displays motherboard information, including serial number. IE8 prompts me to allow the script to run, but an older version or poorly-configured version may run the script unconditionally. (Original Source):
var locator = new ActiveXObject ("WbemScripting.SWbemLocator");
var service = locator.ConnectServer(".");
var properties = service.ExecQuery("SELECT * FROM Win32_BaseBoard");
var e = new Enumerator (properties);
document.write("<table border=1>");
for (;!e.atEnd();e.moveNext ())
{
var p = e.item ();
document.write("<tr>");
document.write("<td>" + p.HostingBoard + "</td>");
document.write("<td>" + p.Manufacturer + "</td>");
document.write("<td>" + p.PoweredOn + "</td>");
document.write("<td>" + p.Product + "</td>");
document.write("<td>" + p.SerialNumber + "</td>");
document.write("<td>" + p.Version + "</td>");
document.write("</tr>");
}
document.write("</table>");
To prevent this from happening to your machine, use a modern browser (IE9, FF4+, Chrome) and always keep it up to date. Additionally, be mindful of what plugins you install and more importantly, where you install them from.
A: *
*No. Proof: FireFox, Chrome/Chromium, to name a few.
*Don't worry. JavaScript won't get access to these resources
A: A browser cannot access hardware information.
There are other javascript tools like Titanium or node.js that may access hardware or any other information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Fast way to generate concatenated strings in Oracle Don't we hate when evil coding comes back to haunt?
Some time ago I needed to generate a string concatenating some fields for some more processing later. I thought it would be a good idea to do if straight in the query, and used SO's help to get it. It worked. For a while...
The table got to big and now that trick (which I know is super inefficient) is not exactly viable. This what I'm doing:
with my_tabe as
(
select 'user1' as usrid, '1' as prodcode from dual union
select 'user1' as usrid, '2' as prodcode from dual union
select 'user1' as usrid, '3' as prodcode from dual union
select 'user2' as usrid, '2' as prodcode from dual union
select 'user2' as usrid, '3' as prodcode from dual union
select 'user2' as usrid, '4' as prodcode from dual
)
select
usrid,
ltrim(sys_connect_by_path(prodcode, '|'), '|') as prodcode
from
(
select distinct prodcode, usrid,count(1)
over (partition by usrid) as cnt,
row_number() over (partition by usrid order by prodcode) as rn
from my_tabe
)
where
rn = cnt
start with rn = 1
connect by prior rn + 1 = rn
and prior usrid = usrid
Which nicely yields:
USRID PRODCODE
user1 1|2|3
user2 2|3|4
The evil thing in here, as you might have noticed, is the where rn = cnt, which if you remove you'll see all the work (I suppose) Oracle is really doing:
USRID PRODCODE
user1 1
user1 1|2
user1 1|2|3
user2 2
user2 2|3
user2 2|3|4
I'm actually using this in many places where I have not so many records. It is quite fine up to about a half million records.
Recently I tried the same in a table with ~15Mi records, and well... no good.
Question: is there a way to do this more efficiently on Oracle or is it time bring it down to the actual code?
This is not actual core issue, so I can still afford kludging, as long as it's fast...
Worth mentioning there's a index for the column "usrid" I'm using.
cheers,
A: Tom Kyte provides a very convenient way to do that, and it works from Oracle 9i, with a custom aggregation function. It aggregates with commas, but you can modify the function body for pipes.
Starting with Oracle 11g, you can do:
SELECT LISTAGG(column, separator) WITHIN GROUP (ORDER BY field)
FROM dataSource
GROUP BY grouping columns
This web page provides additional methods including the one that you listed and which is indeed not really efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: rails 3 and PDFkit I'm trying to follow this tutorial.
When I'm adding .pdf to my url it does nothing. My controller has:
respond_to :html, :pdf.
My mime type has been declared.
I tried this too:
respond_to do |format|
format.html
format.pdf {
html = render_to_string(:layout => false , :action => "www.google.fr")
kit = PDFKit.new(html)
send_data(kit.to_pdf, :filename => "candidats.pdf", :type => 'application/pdf')
return # to avoid double render call
}
end
but it does not work and I don't get errors. My browser keep waiting for localhost, but nothing happens.
So how should I try to use pdfkit ?
edit 2 :
According to my rails' logs, rails render successfully the HTML. I saw this in the .log, rails doesn't send it to webrick nor to my browser. And my browser keeps waiting, and waiting and nothing happen. I only have little pictures here.
edit 3 : My webrick server seem unable to respond to other request, once he starts getting a .pdf version of my url, any ideas ?
edit 4 :
I am using rails 3.1, wkhtmltopdf 0.9.5 (windows installer) and pdfkit 0.5.2
A: I found a better way to access my .pdf urls even in developpement mode.
# Enable threaded mode
config.threadsafe!
# Code is not reloaded between requests
#config.cache_classes = true
Config.cache_classes is a comment, cause i had some problems when it wasn't. This way pdfkit works wonder even with rails 3.1. But, you don't reload code between requests.
That's not really a problem, cause you first work on your html, and you switch configuration, in order to check the pdf result. This way you don't have to bother about your production database.
A: Thanks to another stack overflow answer I got part of solution.
This works:
html = '<html><body>Toto de combats</body></html>'
@pdf = PDFKit.new(html)
send_data @pdf.to_pdf, :filename => "whatever.pdf",
:type => "application/pdf",
:disposition => "attachement"
You can replace attachement by inline, so the pdf is displayed in your browser.
In the stack overflow answer I spoke about (I don't remember the link), the .to_pdf was missing, but is mandatory. Otherwise PDF reader doesn't recognize it.
I'm trying to get this work with a .pdf url.
Edit 3:
My problem with .pdf urls is solved. known issue with rails 3.1, but google was unable to find them.
explanation : explanation
Workaround (hadn't tryied yet). workaround
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Checkbox Changed Event not firing for dynamically added control I have created a 3 checkboxes in my jQuery accordion control dynamically in the page load event and I am also associating the CheckedChanged Event for the textbox. But the event is not firing at all. I am not sure what is happening here. Please help me. Thanks and appreciate your feedback.
Code that I used to generate dynamic control and associate the event
protected void Page_Load(object sender, EventArgs e)
{
dvAccordion.Controls.Clear();
foreach (DataRow row in dataSetIP.Tables[0].Rows)
{
HtmlGenericControl tt= new HtmlGenericControl("H3");
HtmlAnchor anc= new HtmlAnchor();
HtmlGenericControl dvP= new HtmlGenericControl("DIV");
dvP.InnerHtml = row["LD"].ToString();
CheckBox chkTest = new CheckBox();
if (!Page.IsPostBack) chkTest .ID = "chk" + row["SD"].ToString();
else
{
string uniqueID = System.Guid.NewGuid().ToString().Substring(0, 5);
chkTest .ID = "chk" + uniqueID + row["SD"].ToString();
}
chkTest.Text = row["SD"].ToString();
chkTest.AutoPostBack = true;
chkTest.CheckedChanged += new EventHandler(chkTest _CheckedChanged);
chkTest.InputAttributes.Add("Value", row["ID"].ToString());
anc.Controls.Add(chkTest);
tt.Controls.Add(anc);
dvAccordion.Controls.Add(tt);
dvAccordion.Controls.Add(dvP);
}
}
But the CheckboxChanged event is not firing.
A: It's an issue of when you add the control, ViewState, and some of the lifecycle. Dynamically adding controls that fully participate in the whole lifecycle is a complicated subject, and without more context, it's best for you to read the Truly Understanding Dynamic Controls series.
In your case, I think you're re-creating the control on the next page load after the ViewState initialization, so it doesn't know about the binding at the time it needs to queue up the call to your bound event handler.
A: Try adding the controls in the Page_Init() event (which is fired before the Page_Load() event).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: max no of columns in infobright We store billions of rows in an infobright table which currently has about 45 columns. We want to add 50 more columns to it. Will adding these columns bring down the performance of reads? Is creating a new table for these columns a better option? Or, since infobright is a column oriented database additions of 50 extra columns not matter much?
Thanks!
A: I think "adding these columns" will not "bring down the performance of reads" that do not use the added columns.
I think "creating a new table for these columns" is not "a better option".
Since "infobright is a column oriented database additions of 50 extra columns" should have no effect on the performance of queries that do not use the added columns.
A: The maximum number of columns for Infobrigh6t tables is 4096. However, that is if they are only TINYINT columns. I would suggest that you do not use more than 1000 columns. The key though is ensuring that in your SQL query that you do not do a SELECT * FROM. You should SELECT CustomerID, CustomerName FROM instead for ONLY those columns necessary to resolve your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Grails / GORM criteria query with hasmany String I have a domain object (Cat) like this:
class Cat {
String name
static hasMany = [
nicknames: String
]
}
(A cat has a name, and also has many nicknames (which are Strings))
And I am trying to query all the cats with certain nicknames.
I've tried this:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'ilike'('nicknames','%'+nickname+'%')
}
return results
}
But it never returns any results. (If I change the query to just use the simple name attribute, it works finding all cats with that name, but I want to query against the nicknames.)
I also tried this:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'nicknames' {
'ilike'('nicknames','%'+nickname+'%')
}
}
return results
}
But I get the error: org.hibernate.MappingException: collection was not an association: example.Cat.nicknames
So the question is, how do I query against a hasMany of type String?
A: You can use HQL for querying in such a scenario. For example,
Cat.findAll("from Cat c where :nicknames in elements(c.nicknames)", [nicknames:'kitty'])
A: After a lot of trying and researching, I found this will work with Grails 2.4.0, I don't know about older versions.
Cat.withCriteria {
createAlias('nicknames', 'n')
ilike 'n.elements', '%kitty%'
}
The trick is to use 'n.elements'
A: You can also use HQL (tested with Grails 2.5.0):
Cat.findAll("from Cat c inner join c.nicknames as n where upper(n) like '%'||?||'%'", [nickname.toUpperCase()])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: JPA\Hibernate database restart problem After database restart EntityManagerFactory's connection become invalid(persistence exception : broken pipe ) .I try to set properties on persistence.xml to solve problem but it is not worked.How can i handle this case .I am using jpa 2 with hibernate (c3p0 as connection provider)
A: I hope this SO question helps you : hibernate c3p0 broken pipe
Also this article discussed reconnecting (testing connection) with c3p0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sharepoint and SQL driven ComboBox Is there a comboxBox web part out the box in SharePoint 2010 that can be loaded from a SQL table and then be used to pass and parameter to a intergrated Reporting Service report?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WINDBG: Display dump file capture flags This is a very quick question. I searched and can't seem to find the windbg command that would show what options exist in a minidump file.
Additionally, I would like to get back the equivalent argument to the .dump command that would generate the same type of minidump, for example .dump /ma.
A: .dumpdebug will give you the flags that the mini-dump was created with. For example:
0:000> .dumpdebug
----- User Mini Dump Analysis
MINIDUMP_HEADER:
Version A793 (6C02)
NumberOfStreams 11
Flags 1806
0002 MiniDumpWithFullMemory
0004 MiniDumpWithHandleData
0800 MiniDumpWithFullMemoryInfo
1000 MiniDumpWithThreadInfo
It will also spew lots of other information, so just be patient and then scroll back to the top :)
-scott
A: When you first open a dump usually the 4th line of text will be something like this:
User Mini Dump File with Full Memory: Only application data is available
or
User Mini Dump File: Only registers, stack and portions of memory are available
This will obviously change depending upon what the options were.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Are Facebook SDK and Android Facebook app linked? I'm just starting to use Facebook SDK for Android and I'm wondering if there is a way to link it to the actual Facebook android app itself.
What I mean is when I'm logged in in Facebook official app, I would like Facebook.isSessionValid() to return true and not get into the login with password process.
Is that possible or am I dreaming of an unfeasible thing?
A: That's not possible. The Facebook SDK uses the app if it's installed for authentication. Otherwise it falls back to a WebView based one. This way you don't have to deal with usernames and passwords (and can't get them even if you wanted). It won't ask the user for credentials if he is already signed into the app though.
The user still has to confirm permissions and allow your app specifically for safety reasons.
It would be pretty bad if every app could abuse your Facebook account in the background without asking for permission first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: the user data image is used by another emulator. aborting i am creating an simple application and run this application , its work perfectly but when close my application on emulator and run another time its give me an error like this ,
[2011-09-23 20:17:57 - DatabaseApplication] Android Launch!
[2011-09-23 20:17:57 - DatabaseApplication] adb is running normally.
[2011-09-23 20:17:57 - DatabaseApplication] Performing com.database.DatabaseApplicationActivity activity launch
[2011-09-23 20:17:57 - DatabaseApplication] Automatic Target Mode: launching new emulator with compatible AVD 'Android1.6_API_4'
[2011-09-23 20:17:57 - DatabaseApplication] Launching a new emulator with Virtual Device 'Android1.6_API_4'
[2011-09-23 20:17:57 - Emulator] emulator: ERROR: the user data image is used by another emulator. aborting
A: I have got the answer of the Question :
Problem is solved using following below step :
step-1 : go to c:\user\name_of_user\.android\avd\name_of_avd
step-2 : delete below folder
1. userdata-qemu.img.lock
2. cache.img.lock
Run your application , every thing going right but i don't get right solution ,
why this problem is generate.
Thank You
Rahul Mandaliya
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can Guice annotated injections be converted to Spring dependency injection I set up this binding with Guice
bindConstant().annotatedWith( SecurityCookie.class ).to("JSESSIONID");
I need to migrate to Spring.
What would be the equivalent code with Spring ?
A: Use FieldRetrievingFactoryBean.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: libmagick equivalent of TIFFReadRGBAImage High.
I was trying to find a well written API documentation for libmagick[++] to get a raster memory block for RGB[A] image data. Something equivalent to this guide or at least well documented classes, methods and properties.
Can anyone point me in the right direction?
Thanks.
Edit:solved:
void Magick::Image::write(Blob *blob_,
const std::string &magick_,
const unsigned int depth_);
A: void Magick::Image::write(Blob *blob_,
const std::string &magick_,
const unsigned int depth_);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parametrizing string in .NET C# How to replace a method signature to accept parameterized strings without using param keywords. I have seen this functionality in Console.WriteLine().
e.g.
public void LogErrors(string message, params string[] parameters) { }
Scenario:
I have an error login function called
LogErrors(string message)
{
//some code to log errors
}
I am calling this function at different locations in the program in a way that the error messages are hardcoded. e.g.:
LogError("Line number " + lineNumber + " has some invalid text");
I am going to move these error messages to a resource file since I might change the language (localization) of the program later. In that case, how can I program to accept curly bracket bases parameterized strings? e.g.:
LogError("Line number {0} has some invalid text", lineNumber)
will be written as:
LogError(Resources.Error1000, lineNumber)
where Error1000 will be "Line number {0} has some invalid text"
A: You probably want two methods:
public void LogErrors(string message, params string[] parameters)
{
LogErrors(string.Format(message, parameters));
}
public void LogErrors(string message)
{
// Use methods with *no* formatting
}
I wouldn't just use a single method with the params, as then it'll try to apply formatting even if you don't have any parameters, which can make things harder when you want to use "{" and "}" within a simple message without any parameters.
A: Basically use String.Format() method:
public void LogError(string format, params string[] errorMessages)
{
log.WriteError(String.Format(
CultureInfo.InvariantCulture,
format,
errorMessages));
}
A: Just call String.Format in your function:
string output = String.Format(message, parameters);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: htaccess redirect to another site on certain file extensions I want to redirect to another site (storage), if client requests *.pdf or *.cdr files.
The problem is that, with the below htaccess, cdr downloading works, but not pdf.
If a change the rule order (cdr first, pdf second), then the pdf works, but not the cdr.
I've tried [OR], other regex to catch both extensions in one pattern. This is the only one that works (half-works).
The files (pdf or cdr) to which the redirection points exist (I checked through FTP).
I currently have in the root .htaccess:
#<snip>
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
# catch site.ro/some_file.pdf
RewriteCond %{REQUEST_URI} (.+pdf)$ [NC]
RewriteRule ^(.*)$ http://docs.site.com/$1 [L,R]
# catch site.ro/some_file.cdr
RewriteCond %{REQUEST_URI} (.+cdr)$ [NC]
RewriteRule ^(.*)$ http://docs.site.com/$1 [L,R]
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
A: This is what I would do:
RewriteCond %{REQUEST_FILENAME} !-d # If not an existing directory
RewriteCond %{REQUEST_FILENAME} !-f # If not an existing file
RewriteCond %{REQUEST_URI} \.(pdf|cdr)$ [NC] # If filename ends with .pdf or .cdr
RewriteRule ^(.*)$ http://docs.site.com/$1 [L,R] # Redirect the user to the other site
RewriteRule ^.*$ index.php [NC,L] # Redirect all other requests to index.php
Hope this helps you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Moving from a Mac to Ubuntu for Rails development, what are the ramifications? Are there any gotchas or things to watch out for if I move from a Mac to a Ubuntu environment?
Any major configuration issues? Or should things work pretty much the same once I figure out how to install things? (seems installation is easier on Ubuntu anyhow).
A: Most of the gotchas for setting up Rails are for Mac :-)
Stick to Ubuntu and make sure to use RVM to set up your Ruby environment. Do not use sudo apt-get to install rails, and after RVM is installed avoid using sudo altogether when installing gems (eg. gem install rails).
Only complaint is that gedit is not as slick as Textmate, but check out the gmate plugin.
A: The biggest gain of switching ubuntu, imho, is you don't have to deal with osx specific headaches of setting up dev-server environment.
I am pretty happy with ubuntu, a possible alternative to gmate might be sublime text 2.
It can be configured with vim mode, emacs mode, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: C++ Win32 Radio button background color So first i'm using the windows API, no special libraries.
I've created a radio button with this code:
g_hRadioButton = CreateWindowEx(0, "BUTTON", "Radio Button",
WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON,
10, 55, 120, 25, hWnd, (HMENU)RADIOBUTTON, GetModuleHandle(NULL), NULL);
Now I have a black background for the main window, so I would like the text to be white, and the background to be transparent.
I've tried checking both the WM_CTLCOLORBTN and WM_CTLCOLORSTATIC messages.
Here's my code:
case WM_CTLCOLORBTN:
SetTextColor((HDC)wParam, 0xffffff);
SetBkMode((HDC)wParam, TRANSPARENT);
return (LRESULT)GetStockObject(BLACK_BRUSH);
case WM_CTLCOLORSTATIC:
SetTextColor((HDC)wParam, 0xffffff);
SetBkMode((HDC)wParam, TRANSPARENT);
return (LRESULT)GetStockObject(NULL_BRUSH);
This doesn't work, the backgrounds still white and the text is black.
Also i've enabled visual styles by linking to ComCtl32.lib, creating the manifest and all that.
EDIT:
Trying to process the NM_CUSTOMDRAW message now instead.
Here's my code but it's having no effect, and i'm pretty sure im doing something wrong.
case WM_NOTIFY:
{
if (((LPNMHDR)lParam)->code == NM_CUSTOMDRAW)
{
LPNMCUSTOMDRAW nmCD = (LPNMCUSTOMDRAW)lParam;
switch(nmCD->dwDrawStage)
{
case CDDS_PREPAINT:
return CDRF_NOTIFYITEMDRAW;
case CDDS_ITEMPREPAINT:
SetTextColor(nmCD->hdc, 0xffffff);
SetBkColor(nmCD->hdc, 0x000000);
return CDRF_DODEFAULT;
}
}
break;
}
Could someone at least point me in the right direction?
A: Perhaps as soon as your application is running with visual styles, you will be better off handling NM_CUSTOMDRAW notification for button control. Originally, these were for common controls only, but quite a few versions are already extending button behavior the same way too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does ActiveRecord's find method automatically call to_i on its argument? I've come to the conclusion that ActiveRecord automatically calls to_i on its argument, but would appreciate if anybody can confirm, particularly through a reference to some documentation.
The way I came to the conclusion is best illustrated with the following code sample:
dest_task = WorkEffort.find(params[:task_dest_id])
params[:task_src_ids].split.each do |src_id|
WorkEffort.find(src_id).move_to_child_of dest_task
end
When I ran the above only the record associated with the first src_id was processed although I knew the task_src_ids parameter contained something such as "78,79". Thinking it through, find must be calling to_i on that string, which will ignore everything after the first non-digit and return 78.
If find wasn't calling to_i an error should have resulted, and I would have to call to_i explicitly. I of course fixed the code by calling "split(',')" and now it processes multiple task_src_ids instead of just the one that comes before the first comma.
I know I've sort of answered this myself, but as a Ruby/Rails newbie am looking for confirmation, and a link to relevant documentation, plus I thought it could help out others in the future. Thanks in advance
A: [Answering this with activerecord-2.3.14code, as you didn't specify a version.]
Ultimately, your value is going to be run through the Quoting#quote method. I've pasted the beginning of that here, and as you can see on the block starting at line 15 when your column type is an int it will end up calling .to_i on the value passed in.
1 module ActiveRecord
2 module ConnectionAdapters # :nodoc:
3 module Quoting
4 # Quotes the column value to help prevent
5 # {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
6 def quote(value, column = nil)
7 # records are quoted as their primary key
8 return value.quoted_id if value.respond_to?(:quoted_id)
9
10 case value
11 when String, ActiveSupport::Multibyte::Chars
12 value = value.to_s
13 if column && column.type == :binary && column.class.respond_to?(:string_to_binary)
14 "'#{quote_string(column.class.string_to_binary(value))}'" # ' (for ruby-mode)
15 elsif column && [:integer, :float].include?(column.type)
16 value = column.type == :integer ? value.to_i : value.to_f
17 value.to_s
18 else
19 "'#{quote_string(value)}'" # ' (for ruby-mode)
20 end
A: Not sure since when but now in Rails 6, to_i will be called automatically to the argument of find if the primary key of the Active Record is an integer which I think it is in most cases.
Product.find 10 # #<Product id: 10>
Product.find '10' # #<Product id: 10>
Product.find '10-ten' # #<Product id: 10>
https://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Google Contacts read only (OAuth 2.0) We're using OAuth 2.0 to access Gmail Contacts. Do you know if it is possible to request access (scope) in such a way that the authorization pop-up indicates that we need read only access.
Right now the pop say says "Manage your contacts" - view and manage your Google Contacts.
This "manage" part is discouraging to many users while all we need is to view them.
So far we tried the following scopes but the pop-up is the same ("Manage contacts"):
- https://www.google.com/m8/feeds/
- https://www-opensocial.googleusercontent.com/api/people
Thanks,
Piotr
A: Yes, there is, just use https://www.googleapis.com/auth/contacts.readonly as the scope and it will say "View your contacts".
Hope that helps!
A: For contacts, the lowest granularity of scope that google has is read/write. Read only access is not available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: strstr: behavior different using different versions of gcc I'm porting a program that works with Ubuntu 8.04 (gcc version 4.2.4) to 10.04 (gcc version 4.4.3). I have the following code:
#include <stdio.h>
#include <string.h>
int main(void) {
char p[100] = "////abcd";
char *t;
/* Remove duplicate slashes, saving only one of them */
while (t = strstr(p, "//"))
strcpy(t, t + 1);
printf("%s\n", p);
return 0;
}
The result should be /abcd, which it is with gcc 4.2.4. With 4.4.3, the output is /accd.
Can you suggest me a code change that will give the correct output using both versions of gcc, and preferrably explain what is going on here.
Thanks in advance!
A: You've just been lucky.
From the strcpy documentation:
The strcpy() function shall copy the string pointed to by s2 (including the terminating null byte) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
The strings overlap in your case, your program invokes undefined behavior.
A possible reason why it used to work but no longer does is that strcpy could have been implemented as a builtin by GCC like memmove (i.e. safe in this situation), but this changed to a non-safe version for performance reasons. (This is pure speculation.)
To fix it, use memmove rather than strcpy, with something like:
while (t = strstr(p, "//")) {
memmove(t, t+1, strlen(t)); // strlen(t)'s bytes worth of data
// will cover the string bytes left
// and the \0 terminator
}
That's not terribly efficient, but it will work portably - memmove has to handle overlapping memory areas.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Magento Blank Screen on Checkout & Cart with Compiler Enabled When I run the Magento Compiler process it completes fine and then it's enabled. Everything is fine on the frontend until I add something to the basket, it goes to a white/blank screen, same for the basket page and checkout page.
I've tried uncommenting the ini_set('display_errors', 1); line in the index.php file but still nothing is returned. I've also tried showing errors via the .htaccess file without success.
The website's php limit is 256M, so that shouldn't be an issue because the website is empty at the moment.
Really don't know what to try next to debug this? As it just returns nothing and the error logs are empty (CONFUSED!). I've disabled and removed all the 3rd party plug-ins I've used, that appears to have no effect. And I've successfully used those plug-ins I have on other sites with compilation without any issues.
Any help or pointers would be much appreciated! I'm running Magento CE 1.6.0
A: I finally worked out what was causing the problem!
I've you go to Admin > System > Configuration > Customers > Persistent Shopping Cart
And then disable it, then the checkout whitescreen error goes away!
A: Have you set it up to use https for checkout/accounts? And if so have you set the base https server to the correct value? If you have told it to use this but not set it up correctly you may get problems.
A: I'm having exactly the same issue, although I think I've tracked it down to a 3rd party extension. No errors in either the Magento or server logs, and a whitescreen or 500 internal server error, on add to cart or checkout.
The irritating thing is that although I've found references from the developers saying their plugin isn't compatible with the compiler, it seems work on my test system with the compiler.
Could your case be something to do with file permissions?
are your includes folder and subfolders writable?
The compiler doesn't seem to return an error is it can't create a new folder for a module, it just doesn't collect that module, maybe you have an in-house modification that's not being picked up?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone openGL ES 2.0 texturing - setting up multiple textures for fragment shader I'm nervous to ask this, because I've seen several posts alluding to the answer, but none have worked for me. Apologies if this is repetitive.
I'm trying to access more than one texture (2 at the moment) in my fragment shader on iPhone 4 (OS 4.3). My code is properly setting up the first texture and the shader can read and use it on my model. Once I try to add a second texture, though, it overwrites the first instead of giving me two textures.
Is there a good tutorial on passing multiple textures to a pixel shader in ES2.0 for iphone? I think I'm improperly overwriting the same texture slot or something like that.
My code is messy and lengthy. Much of it is modified online samples. Will clean up later.
Thanks!
link:
My code excerpts pertaining to texture loading and shader usage
A: This one is simple. Swap the "//Bind to textures" and "// Get uniform locations." blocks and it should work. The problem is that you are setting values of some uniforms, without knowing their location (which you get in the immediately following step).
So the effect that is happening is not "the one texture being overwritten", but the both samplers contain (the default) 0, so both read the same texture.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Select drop down from associated model I have a model InstrumentFunding (id,title) that belongsTo InstrumentFundingGroup (id,title)
In the backend when I add/edit the InstrumentFunding I want a select dropdown to select the InstrumentFundingGroup
I tried using $form->input('InstrumentFundingGroup',array('type' => 'select')); but the dropdown is empty
How can I do this?
A: In your controller:
$instrumentFundingGroups = $this->InstrumentFundingGroup->find( 'list' );
$this->set( compact( 'instrumentFundingGroups' ) );
In your view:
$form->input('InstrumentFundingGroup.id' );
Cake does the work of recognizing that the array identified by the pluralized model name should populate the id field for that model. Check out the automagic form fields page in the docs. Those outline what's happening.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: performance issue on submitting a form I have got a form in html that validates the user input. The problem is it takes a lot of time even on localhost to jump to the 'action' page. Heres the code
<form action="Activity.php" method="GET" >
<div style="display:none">
<input type="text" id="chapter" name="chapter"/>
<input type="text" id="book" name="book"/>
<input type="text" id="activity" name="activity"/>
</div>
<input type="image" src="includes/file.png" onClick="return validateForm()" title="Create New Activity" >
</form>
The code for validateForm is :
function validateForm()
{
document.body.style.cursor='wait';
if(document.getElementById("book").value==null || document.getElementById("book").value==""
|| document.getElementById("chapter").value==null || document.getElementById("chapter").value=="")
{
document.body.style.cursor='default';
alert("You cannot create an activity at the selected location.");
return false;
}
var name=prompt("Please enter the New Activity Name","New Activity Name");
if (name==null || name=="")
{
document.body.style.cursor='default';
return false;
}
document.getElementById('activity').value=encodeURI(name);
return true;
}
If I remove the prompt in above function, it instantly jumps to the activity.php page, but if I keep the prompt and ask the activity name, it takes a long time to load the desired page (may be cauze the form submitting process was interrupted by the prompt and on clicking the prompts 'ok' button the submission starts again!!no idea :S)what should be a solution (a fast one) to take input from a user when a form is being submitted? thanks!!
A: This object does not exist: document.getElementById('activity')
A: Try this.
function validateForm()
{
document.body.style.cursor='wait';
if(document.getElementById("book").value || document.getElementById("chapter").value)
{
document.body.style.cursor='default';
alert("You cannot create an activity at the selected location.");
return false;
}
var name=prompt("Please enter the New Activity Name","New Activity Name");
if (name)
{
document.body.style.cursor='default';
return false;
}
//document.getElementById('activity').value=encodeURI(name);
return true;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I change the number of decimal places iOS? I have a simple calculator app and I want it to be so that if the answer requires no decimal places, there are none, just whole numbers. If the answer was 2, I don't want it to say 2.000000, it should say 2. If it requires one decimal place, it should show to one decimal place for example 12.8 instead of 12.80. How would I do this? Here is my code.
btw, this is from a tutorial at http://www.youtube.com/watch?v=Ihw0cfNOrr4, not my own work.
viewcontroller.h
#import <UIKit/UIKit.h>
interface calcViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
@end
in the .m
#import "calcViewController.h"
@implementation calcViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:@"%2f", currentNumber];
}
-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:@"%2f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = @"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = @"0";
currentOperation = 0;
}
A: One way is to use NSNumberFormatter to format your result instead of NSString's -stringWithFormat::
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:requiredDigits];
[formatter setMinimumFractionDigits:0];
NSString *result = [formatter stringFromNumber:[NSNumber numberWithFloat:currentNumber];
A: The easiest way is just use [[NSNumber numberWithFloat:] stringValue]
Example:
float someFloatValue;
NSString floatWithoutZeroes = [[NSNumber numberWithFloat:someFloatValue] stringValue];
A: If we use %g in place of %f will truncate all zeros after decimal point.
For example
[NSString stringWithFormat:@"%g", 1.201000];
Output
1.201
A: This should work
NSString *result = [@(currentNumber) description];
A: I had the same problem. This is the code snippet that solved it (looks a lot like Caleb's solution, but that one didn't work for me, so I had to add an extra line):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = kCFNumberFormatterDecimalStyle;
numberFormatter.maximumFractionDigits = 20;
numberFormatter.minimumFractionDigits = 0;
NSNumber *number = [[NSNumber alloc]init];
NSString *numberString = [numberFormatter stringFromNumber:number];
We can use another numberStyle and override its basic appearance, setting desired properties of an NSNumberFormatter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I unit test the properties of a variable declared in a method under test I have a service layer method that recieves an object(Dto) as a parameter.
Within that method I new up a business object and i pass the values of the properties of the Dto to the properties of the business object. I then pass the business object as a parameter to a repository method call.
How will my unit test ensure that the business object declared in the service method under test receives the right value into its properties?
A: You can mock the repository (I hope that you can inject it into the service layer) and check whether the business object passed into the repository has the expected property values.
EDIT: An example
Infrastructure:
public interface IRepository
{
void Add(BusinessObject item);
}
public sealed class ServiceLayerContext
{
private readonly IRepository repository;
public ServiceLayerContext(IRepository repository)
{
this.repository = repository;
}
public void ProcessDto(IDtoObject dto)
{
var businessObject = this.CreateBusinessObject(dto);
this.repository.Add(businessObject);
}
private BusinessObject CreateBusinessObject(IDtoObject dto)
{
}
}
Test pseudocode (because RhinoMockі not the Moq):
[Test]
public void ShouldCreateBusinessOBjectWithPropertiesInitializedByDtoValues()
{
// ARRANGE
// - create mock of the IRepository
// - create dto
// - setup expectations for the IRepository.Add() method
// to check whether all property values are the same like in dto
var repositoryMock = MockRepository.GenerateMock<IRepository>();
var dto = new Dto() { ... };
BusinessObject actualBusinessObject = null;
repositoryMock.Expect(x => x.Add(null)).IgnoreArguments().WhenCalled(
(mi) =>
{
actualBusinessObject = mi[0] as BusinessObject;
}).Repeat().Any();
// ACT
// - create service layer, pass in repository mock
// - execute svc.ProcessDto(dto)
var serviceLayerContext = new ServiceLayerContext(repositoryMock);
serviceLayerContext.ProcessDto(dto);
// ASSERT
// - check whether expectations are passed
Assert.IsNotNull(actualBusinessObject);
Assert.AreEqual(dto.Id, actualBusinessObject.Id);
...
}
A: Thanks so much for your help.
The sample code below uses moq and its written in vb.net for other vb.net programmers that might of had similar challenges.
Concrete Class
Public Class UserService
Implements IUserService
Private ReadOnly userRepository As IUserRepository
Public Sub New( _
ByVal userRepository As IUserRepository)
Me.userRepository = userRepository
End Sub
Public Sub Edit(userDto As Dtos.UserDto) Implements Core.Interfaces.Services.IUserService.Edit
Try
ValidateUserProperties(userDto)
Dim user = CreateUserObject(userDto)
userRepository.Edit(user)
Catch ex As Exception
Throw
End Try
End Sub
Private Function CreateUserObject(userDto As Dtos.UserDto) As User Implements Core.Interfaces.Services.IUserService.CreateUserObject
Dim user = New User With {.Id = userDto.Id, _
.UserName = userDto.UserName, _
.UserPassword = userDto.UserPassword, _
.Profile = New Profile With {.Id = userDto.ProfileId}}
Return user
End Function
Sub ValidateUserProperties(userDto As Dtos.UserDto)
End Sub
Test Class
<TestFixture()>
Public Class UserServiceTest
Private userRepository As Mock(Of IUserRepository)
Public serviceUnderTest As IUserService
<SetUp()>
Public Sub SetUp()
userRepository = New Mock(Of IUserRepository)(MockBehavior.Strict)
serviceUnderTest = New UserService(userRepository.Object)
End Sub
<Test()>
Public Sub Test_Edit()
'Arrange
Dim userDto As New UserDto With {.UserName = "gbrown", .UserPassword = "power", .Id = 98, .ProfileId = 1}
Dim userObject As User = Nothing
userRepository.Setup(Sub(x) x.Edit(It.IsAny(Of User))) _
.Callback(Of User)(Sub(m) userObject = m)
'Act
serviceUnderTest.Edit(userDto)
'Assert
userRepository.Verify(Sub(x) x.Edit(It.IsAny(Of User)), Times.AtLeastOnce())
Assert.NotNull(userObject)
Assert.AreEqual(userDto.Id, userObject.Id)
Assert.AreEqual(userDto.ProfileId, userObject.Profile.Id)
Assert.AreEqual(userDto.UserName, userObject.UserName)
Assert.AreEqual(userDto.UserPassword, userObject.UserPassword)
End Sub
End Class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: IOS Display Image using HJCache I am new to IOS but I have made a small application that uses HJCache to display Images.
All fine, I found a way to Display an Image with HJCache, but I have a big Problem, I cannot unterstand how I display the Image to Show me the result when the Image was loaded.
My Actual Code is:
(I created the HJCache Object objMan - thumbs is a UIImageView *thumb
HJManagedImageV *asyncImage = [[[HJManagedImageV alloc] initWithFrame:CGRectMake(20,20,50,50)] autorelease];
asyncImage.url = [NSURL URLWithString:[thumbs_array objectAtIndex:thisItem]];
[objMan manage:asyncImage];
[objMan performSelectorOnMainThread:@selector(manage:) withObject:asyncImage waitUntilDone:YES];
[thumb setImage:asyncImage.image];
The example Works, it will load the image but show it only after application restart. Does anyone have an idea?
A: if u are loading images in tableview .I d do something like this instead of creating an UImageView ...
HJManagedImageV *asyncImage = [[[HJManagedImageV alloc]
initWithFrame:CGRectMake(20,20,50,50)] autorelease];
asyncImage.url = [NSURL URLWithString:[thumbs_array objectAtIndex:indexpath.row]];
[objMan manage:asyncImage];
[cell addSubview:asyncImage];
mi=(HJManagedImageV *)[cell viewWithTag:999];
[mi clear];
A: Nikolas, are you open to alternate solutions?
If you are, I know of a very easy image loading library:
SDWebImage
Link: https://github.com/rs/SDWebImage
Simple to use, 1 line code to do what you want:
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
MWPhotoBrowser
Link: https://github.com/mwaterfall/MWPhotoBrowser
For displaying scrollable, pinch-zoom gallery automagically. MWPhotoBrowser uses SDWebImage in the back, so it's an extension of that library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Monitoring open programs with Win32 I've searched the web, and various forums, but I can't find one thing, how to continually monitor open programs and then close another program (not the one being monitored) if something happens to the program being monitored.
For example, say that there is an already open Notepad window, and then the user or some other program opens a Windows Explorer window. I want to know how to close the Notepad window without interacting with the Windows Explorer window (other than realizing that it is indeed open), as well as closing the Notepad window if the user closes the Windows Explorer window.
Thanks in advance! :D
A: On windows, you can use PSAPI (The Process Status API) to know when processes are started and terminate. The EnumProcesses function can give you this information.
A more reliable method to determine that a process terminated (since process ids can be reused) is to wait on its process handle (you will need the SYNCHRONIZE access right) which you can obtain using OpenProcess and the process' id obtained from EnumProcesses.
To terminate a process, there is always TerminateProcess. To call TerminateProcess, you will need a handle to the process with the PROCESS_TERMINATE access right. All of this assumes that you have the privileges needed to perform these actions on the process to be terminated.
A: One thing to be aware of is that processes and programs - or at least what the user regards as a program - are not necessarily the same thing.
If you use the PSAPI to get a list of all the processes running, you'll see a lot of background process that don't correspond to open windows at all. There's also cases where a single process can have multiple top-level windows open. So while you have simple cases like notepad where once notepad.exe process corresponds to one Notepad window, you also have cases like:
*
*Word, where one word process handles all the word documents currently open (one process, many windows)
*Explorer, where a single exploere.exe process handles all the open explorer windows, and also things like control panel windows and the task bar.
*Chrome (and other browsers), where each tab gets its own process (many processes, one window!)
Using TerminateProcess is perhaps not the best way to close an app: it's not directly equivalent to clicking the close button. It forcibly terminates the entire process there and then, without giving it any chance to clean up. If you do this on Word, when it restarts, it will go into 'recovery mode', and act as though it hadn't shut down cleanly the last time. It's best left as a last resort if a process has stopped responding. Also, if you TerminateProcess on a process like Word or Explorer, you'll end up closing all windows owned by that process, not just one specific one.
Given all of this, if you want to essentially write some sort of program manager, you might be better off taking a window-centric approach rather than a process centric one. Instead of monitoring running processes, monitor top-level application windows.
There are several ways to listen for changes to windows; SetWinEventHook with EVENT_CREATE/DESTROY is one way to listen for HWNDs being created or destroyed (you'll need to do filtering here, since it will tell you about all HWNDs - and more! - but you only care about top-level ones, and only app ones at that). SetWindowsHookEx may have other options that could work here (WH_CBT). You can also use EnumWindows to list the windows currently present (again, you'll need to filter out owned dialogs and tooltips, currently invisible HWNDs, etc).
Given a HWND, you can get process information if needed by using GetWindowThreadProcessId.
To close a window, sending WM_SYSCOMMAND/SC_CLOSE is the best thing to try first: this is closer to clicking the close button, and it gives the app a chance to clean up. Note that some apps will display a "are you sure you wish to close?" dialog if you haven't saved recently - again, it's consistent with clicking the close button with the mouse.
A: The most well-known way of doing this on Windows is to use the Process Status API. You can use this API to enumerate processes However, this API is annoying in that it doesn't guarantee you get the full list or processes.
A better way to enumerate processes is using the Tool Help Library, which includes a way to take a complete snapshot of all processes in the system at any given time.
A: You need the Microsoft PSAPI (Processes API), for example to see the open processes you can use the openProcess function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What's the difference between mvn:deploy and mvn:install commands? I think there should be some difference, but can anyone tell me the details?
A: mvn:install copies your packaged Maven module to your local repository (by default, in ~/.m2/repository), to be accessed by other local Maven builds.
mvn:deploy uploads your packaged Maven module to another (usually remote) repository, to be accessed by other, not necessarily local, Maven builds.
See the documentation for the build lifecycle for more info.
A: The install phase is responsible for the installation of artifacts into local caching repositories. This basically applies to the Maven repository, but a well-known example is also the OSGi Bundle Repository supported by maven-bundle-plugin.
The deploy phase is responsible for the installation of artifacts into published repositories. This usually applies to remote repositories, but is could perfectly be a local repository exposed to the outside world.
As all Maven phases, you can do with them anything you want. You can shuffle plugin phases as you see fit, but the above semantics is the conventional one and you should stick to it in order to be consistent with the default phases of other plugins' goals.
A: mvn:deploy performs deployment to remote reposiory/environment, mvn:install installs all compiled packages to a local repository making them available to other builds performed on the local machine.
A: In one sentence: mvn:install compiles and installs your component in your local Maven repository, so that you can use it when other components used and developed locally depend on it. mvn:deploy deploys your (previously installed) component to a remote repository.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: what is SQL ReportServer GetMyRunningJobs in my SQL Profiler While running the SQL Profiler on a client site I noticed getmyrunningjobs running over and over bogging down their system in the morning from about 5:30 am to 6:30am. I know it runs all the time but for some reason it appears to run 4 times in a row every couple of seconds in the morning. I'm not really sure what it is used for, though I've read a lot on SQL Profiler, I can't find much on SQL Report Server.
Can I stop or change the frequency or is there something else going on that I can check? Also, what is Tablockx, and is this related?
Thanks. Any help appreciated!
A: To answer your secondary question, TABLOCKX is a SQL Server table hint that applies an exclusive table lock. I'd think this would be related to your problem only if something is holding the lock for an unusually long time during the timeframe you indicated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to dynamically alter a value in mvc3 html page <tr>
<td>
Delivery
</td>
<td>
<div class="confdelivery">
<select id="NxtDay" name="NxtDay">
<option selected="selected" value="1">Normal Devliery + 10.00</option>
<option value="2">Next Day Delivery + 20.00</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
@{
var total = Model.CartTotal;
}
@total
</td>
</tr>
Basically if a user selects next day delivery. I want 20 to be added to @total?
A: I thing you are going about this the wrong way. You either update some input value with javascript, or use the NxtDay value in your controller action to assign the correct value, depending on the selection.
ADDED:
What you want to do is something like this: (I am assuming you are using jquery, since it come with MVC3).
HOWEVER: You should check out some tutorial if you are starting. This is pretty basic stuff and you won't go far without having to come back here unless to read up on this sutff.
<tr>
<td>
Delivery
</td>
<td>
<div class="confdelivery">
<select id="NxtDay" name="NxtDay">
<option selected="selected" value="10">Normal Devliery + 10.00</option>
<option value="20">Next Day Delivery + 20.00</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<span id="totalValue" style="display: none">@Model.CartTotal</span>
<span id="totalWithShipping">0</span>
<input id="hiddenTotal" type="hidden" value="0">
</td>
</tr>
<script>
$(document).ready(function () {
$('#NxtDay').change(function() {
addToTotal();
});
});
function addToTotal(){
$('#totalWithShipping').html($('#totalValue').html() + $("#NxtDay option:selected").val());
$('#hiddenTotal').val($('#totalWithShipping').html());
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get "primary" user of a remote computer I need to know how to get the name and domain of the primary user of a computer, remotely. I define the primary user preferably as the user logged on most times, or longest time over a period. Alternatively, if this is impossible, as the user currently/last logged on.
Currently, i scan an Active Directoy for all computer objects in an OU. I then loop though them, and try to get the name of the user using WMI.
I look in Win32_ComputerSystem to see if UserName returns a value. If this is not the case, i look in Win32_LogonSession and get the username for all LogonTypes that equal 2 or 10. If this returns none, or multiple values, i discard the result and look in Win32_Process for all non-system processes and define the primary user as the user with most processes running.
There are several problems with my approach:
*
*Win32_ComputerSystem - UserName is often null.
*Win32_LogonSession often return multiple or no values. There can be only 1 primary user.
*Looking in Win32_Process is kinda ridiculous, since this will only return me the user with most processes, most likely not the primary user.
*If no user is currently logged on, looking in Win32_Process returns no value and none of the 3 steps might return a value.
My 3 approaches might get me the current user. Does anyone know of a way to get the primary user? Or at least a better way to get the current. Not necessarily using WMI.
Thanks
A: If you have administrator privileges on the remote computer and sharing access
you can use Computer Management and select to
connect to other computer and see what users and groups are on that computer.
Or you can use TS Remote Administration or Remote Desktop if the remote computer has that capability.
Use psexec.exe (www.sysinternals.com) to run commands on a remote pc:
psexec \\pc1 net user | find /i "Steve"
psexec \\pc1 c:\tool\psloggedon | find /i "Steve"
1) Find if John Black has an account on PC1.
2) Find if he is currently logged on.
Use psloggedon.exe that uis is another SysInternals tool.
Check this also: http://www.wisesoft.co.uk/scripts/vbscript_display_username_of_user_on_a_remote_computer.aspx
Also if you want to find the User Name of the currently logged user on a remote computer using the remote computer IP then Go to the command line an type nbtstat -A <IP of remote computer> This will return all of the NetBIOS names registered on the computer, one of which is the username.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Best practice for detecting changes to functions in Scala programs? I'm working on a Scala-based script language (internal DSL) that allows users to define multiple data transformations functions in a Scala script file. Since the application of these functions could take several hours I would like to cache the results in a database.
Users are allowed to change the definition of the transformation functions and also to add new functions. However, then the user restarts the application with a slightly modified script I would like to execute only those functions that have been changed or added. The question is how to detect those changes? For simplicity let us assume that the user can only adapt the script file so that any reference to something not defined in this script can be assumed to be unchanged.
In this case what's the best practice for detecting changes to such user-defined functions?
Until now I though about:
*
*parsing the script file and calculating fingerprints based on the source code of the function definitions
*getting the bytecode of each function at runtime and building fingerprints based on this data
*applying the functions to some test data and calculating fingerprints on the results
However, all three approaches have their pitfalls.
*
*Writing a parser for Scala to extract the function definitions could be quite some work, especially if you want to detect changes that indirectly affect the behaviour of your functions (e.g. if your function calls another (changed) function defined in the script).
*The bytecode analysis could be another option, but I never worked with those libraries. Thus I have no idea if they can solve my problem and how they deal with Java's dynamic binding.
*The approach with example data is definitely the simplest one, but has the drawback that different user-defined functions could be accidentally mapped to the same fingerprint if they return the same results for my test data.
Does someone has experience with one of these "solutions" or can suggest me a better one?
A: The second option doesn't look difficult. For example, with Javassist library obtaining bytecode of a method is as simple as
CtClass c = ClassPool.getDefault().get(className);
for (CtMethod m: c.getDeclaredMethod()) {
CodeAttribute ca = m.getMethodInfo().getCodeAttribute();
if (ca != null) { // i.e. if the method is not native
byte[] byteCode = ca.getCode();
...
}
}
So, as long as you assume that results of your methods depend on the code of that methods only, it's pretty straighforward.
UPDATE:
On the other hand, since your methods are written in Scala, they probably contain some closures, so that parts of their code reside in anonymous classes, and you may need to trace usage of these classes somehow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: MS Access VBA import text File I am trying to import a text file in MSAccess Vba code as below
DoCmd.TransferText acImportDelim, "", "TableName", FileName, True, ""
The file am importing does not have a any headers in it. It is a comma delimited file with just data.
The table has column names in it. Now i want to import that file in to this table. When i am trying to import that file using the above code its throwing an error Cannot find col 'X' in the table .(where X is the first row, first column of data in in the input file). Please suugest me some solution or a sample example.
Your help is appreciated.
A: If the file has no headers, you should be passing False for the HasFieldNames parameter instead of True:
expression.TransferText(TransferType, SpecificationName,
TableName, FileName, HasFieldNames, HTMLTableName, CodePage)
...
HasFieldNames: Use True to use the first row of
the text file as field names when importing, exporting, or linking.
Use False to treat the first row of the text file as normal data.
http://msdn.microsoft.com/en-us/library/aa220768.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you set up a Facebook app to ask to a user permission to allow publishing to their wall? We are trying to publish to a user's wall using the Facebook C# API using the following piece of code:
private Api _facebookAPI;
private ConnectSession _connectSession;
_connectSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);
_facebookAPI = new Api(_connectSession);
facebookAPI.Stream.Publish("testing 123");
We tried setting the application auth settings in Facebook by going to Settings -> Auth Dialog and altering these settings:
User & Friend Permissions: publish_actions
Extended Permissions: publish_stream
But when the user chooses to connect Facebook to our web app, the below message is displayed asking for the following permissions, obviously theses settings do not authorise us to post to their wall.
Access my basic information
Includes name, profile picture, gender, networks, user ID, list of friends, and any other information I've made public.
I want it to ask the user to allow publishing to the wall/feed, but we can't figure out how/where we set this up. Any help would be greatly appreciated, thank you!
A: You need to change the login link or login button to prompt for the additional permissions. What is the login url you are using now?
I would recommend switching to the newer Facebook C# SDK. The tutorial walks has an example of getting extended permissions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dylib destructor does not get called I have a dylib which I can load via injection on mac os x.
Constructor call works well.
__attribute__((constructor))
static void initialize()
But destructor does not get called? Thus resources initialized leaks.
__attribute__((destructor))
static void destroy()
*
*Does dylib gets unloaded automatically if application quits?
*Does injected dylib gets unloaded automatically if application quits?
*How can we unload dylib from the application at runtime? As its injection code I can access private area. Is there a command to do this?
A: 1, 2: No. Libraries aren't really unloaded when an application exits -- they just happen to disappear along with the rest of the process, in the same way that other resources (e.g, file handles, mapped memory, sockets, etc) are released on exit.
3: Depends on how you injected the library. If you loaded it using something like dlopen(), you should be able to unload the library using dlclose(), for instance; NSBundle has something equivalent.
Keep in mind that unloading libraries is messy. In particular, it's unsafe to unload a library which contains any ObjC classes, as the runtime may have cached references to your classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: iPhone app with or without AppStore My company is offering a service to our clients which we would like to implement on iphone. Our clients would be paying $5000 per month for the service, so they can give it free of charge to their customers. We have been looking (so far with no success) for a distribution method where we can sell our service to our clients, and they can give it to their customers, without charging the end users and without paying the 30% distribution fees to Apple.
We did our research and found that non of the convenient solutions would work for us:
*
*Putting the app for free download on the App store, protecting it with user/password and charging our clients remotely may violate the App Store terms and conditions.
*Ad hoc development would be insufficient as we are aiming towards over 10K downloads on different client devices.
*And the Enterprise solution is for internal distribution in US companies with more than 500 employees (and we are not using it internally, we are outside US and currently have only 5 employees :)
Your help would be much appreciated!
Daniel
A: The first solution could be envisaged as the best one but is not compliant with Apple Term Of Agreement.
The idea would be:
*
*sell freely (to avoid 30%) your application thru the app store
*sell a subscription directly to your client
To be compliant you need to:
*
*sell a subscription also as an in app purchase to be compliant with Apple Terms (would be never used in your case). It has changed since June, 30 2011 (BlogArticle & MacRumors) and you can found official text there : [AppleTerms] (requires a developer account)
*don't put any button to get a subscription within your application and avoid text like buy or something like that in the deployed application.
11.14 Apps can read or play approved content (specifically magazines, newspapers, books, audio, music, and video) that is subscribed to or purchased outside of the app, as long as there is no button or external link in the app to purchase the approved content. Apple will not receive any portion of the revenues for approved content that is subscribed to or purchased outside of the app.
[AppleTerms]:https://developer.apple.com/app-store/review/guidelines/ (requires a developer account)
A: Apple Terms has been updated.
*
*If you want to unlock features or functionality within your app, (by way of example: subscriptions, in-game currencies, game levels, access to premium content, or unlocking a full version), you must use in-app purchase. Apps may not include buttons, external links, or other calls to action that direct customers to purchasing mechanisms other than IAP.
*Any credits or in-game currencies purchased via IAP must be consumed within the app and may not expire, and you should make sure you have a restore mechanism for any restorable in-app purchases.
Remember to assign the correct purchasability type or your app will be rejected.
*Apps should not directly or indirectly enable gifting of IAP content, features, or consumable items to others.
*Apps distributed via the Mac App Store may host plug-ins or extensions that are enabled with mechanisms other than the App Store.
you can look at : https://developer.apple.com/app-store/review/guidelines/
A: Another possibility is to do a HTML5 web app which can run stand-alone on the device as a web clipping. Then your clients could distribute the app directly from their own web site(s), either behind a paywall or password protected page or not.
The Financial Times did this (convert from an app store app to a web app) to avoid Apple's app store restrictions on certain types of subscriptions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Find the missing date ranges Table 1
code StartDate EndDate
A 01/01/2011 06/15/2011
A 06/25/2011 06/30/2011
B 01/12/2011 07/31/2011
B 08/3/2011 12/31/2011
Table 2
code StartDate EndDate
A 01/01/2011 06/30/2011
B 01/12/2011 07/31/2011
B 08/3/2011 12/25/2011
I need find what is in Table1 and not in Table2 which is
code StartDate EndDate
B 12/26/2011 12/31/2011
And the Converse of what is in Table2 and not in Table1
code StartDate EndDate
A 06/16/2011 06/29/2011
There is no time component in the date field and T-SQL (SQL Server 2000 ) is preferred.
A: This is a bit tedious in SQL Server 2000. It uses a numbers table to expand out the ranges of dates into individual rows. Then NOT EXISTS for the anti semi join then uses an "islands" approach I stole from an MSDN article to collapse the result back into ranges again.
SET DATEFORMAT MDY
DECLARE @Numbers TABLE (N INT PRIMARY KEY)
INSERT INTO @Numbers
SELECT number
FROM master..spt_values
WHERE type='P' AND number >= 0
DECLARE @Table1 TABLE
(
code CHAR(1),
StartDate DATETIME,
EndDate DATETIME
)
DECLARE @Table2 TABLE
(
code CHAR(1),
StartDate DATETIME,
EndDate DATETIME
)
INSERT INTO @Table1
SELECT 'A','01/01/2011','06/15/2011' UNION ALL
SELECT 'A','06/25/2011','06/30/2011' UNION ALL
SELECT 'B','01/12/2011','07/31/2011' UNION ALL
SELECT 'B','08/3/2011',' 12/31/2011'
INSERT INTO @Table2
SELECT 'A','01/01/2011','06/30/2011' UNION ALL
SELECT 'B','01/12/2011','07/31/2011' UNION ALL
SELECT 'B','08/3/2011',' 12/25/2011'
DECLARE @Results TABLE
(
code CHAR(1),
StartDate DATETIME
)
INSERT INTO @Results
SELECT T1.code,
DATEADD(DAY, N, StartDate)
FROM @Table1 T1
INNER JOIN @Numbers N1
ON N <= DATEDIFF(DAY, StartDate, EndDate)
WHERE NOT EXISTS (SELECT *
FROM @Table2 T2
INNER JOIN @Numbers N2
ON N2.N <= DATEDIFF(DAY, T2.StartDate, T2.EndDate)
WHERE DATEADD(DAY, N1.N, T1.StartDate) =
DATEADD(DAY, N2.N, T2.StartDate)
AND T1.code = T2.code)
/*SQL Server 2000 gaps and islands approach from here
http://msdn.microsoft.com/en-us/library/aa175780%28v=sql.80%29.aspx*/
SELECT t1.code,
t1.StartDate,
MIN(t2.StartDate) AS EndDate
FROM (SELECT StartDate,
code
FROM @Results tbl1
WHERE NOT EXISTS(SELECT *
FROM @Results tbl2
WHERE tbl1.StartDate = tbl2.StartDate + 1
AND tbl1.code = tbl2.code)) t1
INNER JOIN (SELECT StartDate,
code
FROM @Results tbl1
WHERE NOT EXISTS(SELECT *
FROM @Results tbl2
WHERE tbl2.StartDate = tbl1.StartDate + 1
AND tbl1.code = tbl2.code)) t2
ON t1.StartDate <= t2.StartDate
AND t1.code = t2.code
GROUP BY t1.code,
t1.StartDate
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to append an ID with the value from another ID in JQuery I need to grab the value of an id and attach it to the end of a url on my form. Here's the html code for the input...
<input id="ServiceRequestEditForm.CustomObject6 Id" type="hidden" value="" tabindex="-1" name="ServiceRequestEditForm.CustomObject6 Id"/>
I want to capture the value of this input. I am trying to use the following code, but it doesn't work...
$("a[href*='http://www.google.com']").attr('href',
('http://www.google.com/search?q'+('Form.CustomObject6 Id').val()));
Could someone please help me to get this working.
A: $('a[href*="http://google.com"]').attr('href','http://google.com/search?q'+$('#someID').attr('id'));
A: Not sure I completely understand, but something like this?
$('#'+el.id).val()
A: You can get the id attribute of an element by using the attr() function:
var myId = $('Form.CustomObject6').attr('id');
So, assuming you need the id of Form.CustomObject6, this is probably what you are looking for:
$("a[href*='http://www.google.com']").attr('href',
('http://www.google.com/search?q'+ $('#ServicerequestEditForm.CustomObject6 Id').attr('id')));
Provide a sample of your HTML if you still aren't able to capture the id you need.
EDIT: I re-read your question and think I misunderstood what you are asking for. I think you are trying to get the value of the ServiceRequestEditForm.CustomObject6 Id element, but it keeps returning undefined. This is because the jQuery selector contains special characters (. and space). You have to escape each special character with two backslashes: \\. Try this:
var myVal = $('#ServiceRequestEditForm\\.CustomObject6\\ Id').val();
So your code now becomes:
$("a[href*='http://www.google.com']").attr('href',
('http://www.google.com/search?q'+ $('#ServiceRequestEditForm\\.CustomObject6\\ Id').val()));
A: $("a[href*='http://www.google.com']").attr('href',
'http://www.google.com/search?q'+$('element').attr("id"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET LINQ Is it possible to do a standard SQL Query? I was wondering if it was possible to perform traditional SQL queries using LINQ. I would then like to DataBind the results to a GridView.
Thanks so much!
A: You can use the ExecuteQuery() method.
A: Yes, just use the method ExecuteQuery on your DataContext:
IEnumerable<YourTable> rows = dataContext.ExecuteQuery("SELECT * FROM YourTable");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing tomcat server port to 80 does not work I deploy my web app into a tomcat server in a Linux AMI EC2 machine. I'm not familiar with Linux but I believe the virtual machine is similar to CentOS? I use yum install tomcat to install tomcat into the ec2 instance.
When I deploy a java/spring .war file into the /webapps directory, it works but i have to specify :8080 in the url. I set up elastic ip so i can go to xxx.xx.xx.xx:8080/webappname/
Enough with background, here is the question. I change the port to 80 in server.xml. I found the file at /etc/tomcat6/server.xml or /usr/share/tomcat6/conf/server.xml. but after the change, i go to xxx.xx.xx.xx/webappname/ and the system cannot communicate with the server. What am i doing wrong? I notice there is another file that uses port 8080 which is etc/init.d/tomcat6. Does that have anything to do with it?
I also read somewhere that port 1-xxx is restricted and if I open it up, it would be a security risk. In that case, should I just leave port 80 as is and just assign a domain name to that ip address + port?
Thanks
A: Login to the AWS console and goto the Security Groups section
Here, in the Inbound add a new rule named Custom TCP Rule and enter the custom port range 8080.
Now, enter the {ipaddress}:8080 in the browser
A: You need to define your app as default web application. Take a look on tomcat documentation.
See path attribute documentation
The context path of this web application, which is matched against the
beginning of each request URI to select the appropriate web
application for processing. All of the context paths within a
particular Host must be unique. If you specify a context path of an
empty string (""), you are defining the default web application for
this Host, which will process all requests not assigned to other
Contexts.
This attribute must only be used when statically defining a Context in
server.xml. In all other circumstances, the path will be inferred from
the filenames used for either the .xml context file or the docBase.
Even when statically defining a Context in server.xml, this attribute
must not be set unless either the docBase is not located under the
Host's appBase or both deployOnStartup and autoDeploy are false. If
this rule is not followed, double deployment is likely to result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: For extended information, should I use Django's Multi-table Inheritance or an explicit OneToOneField I have some fields on a model that won't always be filled in (e.g., the actual completion date and costs until the project is over). Because of this, I thought I'd split the model into two:
*
*Model #1: Dense table containing frequently searched and always completed fields
*Model #2: Sparse table containing infrequently searched and not always completed fields
Questions
*
*Am I thinking correctly in splitting this into two models/tables?
*Should I use Django's Multi-table Inheritance, or should I explicitly define a OneToOneField? Why?
Configuration
*
*Django version 1.3.1
Models
Using Django's Multi-table Inheritance
class Project(models.Model):
project_number = models.SlugField(max_length=5, blank=False,
primary_key=True)
budgeted_costs = models.DecimalField(max_digits=10, decimal_places=2)
class ProjectExtendedInformation(Project):
submitted_on = models.DateField(auto_now_add=True)
actual_completion_date = models.DateField(blank=True, null=True)
actual_project_costs = models.DecimalField(max_digits=10, decimal_places=2,
blank=True, null=True)
Using an Explicit OneToOneField
class Project(models.Model):
project_number = models.SlugField(max_length=5, blank=False,
primary_key=True)
budgeted_costs = models.DecimalField(max_digits=10, decimal_places=2)
class ProjectExtendedInformation(models.Model):
project = models.OneToOneField(CapExProject, primary_key=True)
submitted_on = models.DateField(auto_now_add=True)
actual_completion_date = models.DateField(blank=True, null=True)
actual_project_costs = models.DecimalField(max_digits=10, decimal_places=2,
blank=True, null=True)
A: You're essentially dealing with apples and apples here. Django's implementation of MTI (multi-table inheritance) uses an implicit OneToOneField.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: load ePub book via URL to iBook on iPad as i know the iBook App on iPad can read so called ePub Books. Now a customer want's that we develop an App, where his customers can browse his "store" and download the Books directly to iBooks.
Any Idea if this is possible? The part of writing the app and downloading the ePub Archive to the device isn't a big problem. The question is, is it possible to tell the iBook App to load the downloaded ePub Book? Or is there a way in SDK to hand over a url to the iBook-App so that the App starts and downloads the book itself?
A: If you load the epub file in mobile safari, it will prompt you to download it into iBooks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do ObjectId's work, and can I just use them anywhere? How do ObjectId's work, and can I just use them anywhere I need a unique id and trust that it will be unique?
Thanks!
A: http://www.mongodb.org/display/DOCS/Object+IDs explains ObjectIds. Because ObjectId contains a timestamp, machine ID, process ID, and incrementing counter, it should be safe to assume that it is unique each time you generate one.
A: I think it depends on what you mean with "anywhere"? To ensure, that ObjectIds are unique, the following information is used for creating the hash for the object ID:
*
*a unix timestamp
*machine hostname
*process id
*increment
see also the documentation at:
http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-BSONObjectIDSpecification
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook Like button not working in IE8 or IE9 I've been banging my head against this for over a day now and am finally posting a question, since I can't figure it out nor can find any information out there from people who are experiencing the same issue.
These Like buttons work fine in Chrome, Firefox, IE7, but NOT in IE8 nor IE9.
Do any of you Facebook gurus have any idea what may be going on here? The buttons work fine in production.
But for this page, in IE8 & IE9, if you're not logged in to Facebook, you get a popup prompting you to log in. After successful login, you're forwarded to (referencing you're url, instead of mine):
http://www.facebook.com/connect/connect_to_external_page_widget_loggedin.php?social_plugin=like&external_page_url=http%3A%2F%2Fwebhooks.digitas.com%2Flike.html#=
If you're already logged in, you go straight to this url. As you can see, the page never finishes whatever it's supposed to do.
I just don't understand how a button can work in production, but not in this test page.....
My test page contains 3 like buttons, taken directly from the like button code generator page.
<!doctype html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://webhooks.digitas.com/like.html" data-send="false" data-layout="button_count" data-width="200" data-show-faces="false"></div>
<fb:like href="http://webhooks.digitas.com/like.html" send="false" layout="button_count" width="200" show_faces="false"></fb:like>
<iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwebhooks.digitas.com%2Flike.html&send=false&layout=button_count&width=200&show_faces=false&action=like&colorscheme=light&font&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:21px;" allowTransparency="true"></iframe>
</body>
</html>
The test page is located at http://webhooks.digitas.com/like.html
I also created another page using an alternate method of loading the Facebook JS SDK that currently works on our production site:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({ appId: '168861203149296', status: true, cookie: true, xfbml: true });
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
</script>
A: There's two things you will need to do to help things out.
1) In the FB.init you should set the ChannelUrl.
2) In the headers your webserver sends out, you must specify a P3P header. See here for how to implement: http://www.hanselman.com/blog/TheImportanceOfP3PAndACompactPrivacyPolicy.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to capture variables for async functions in a coffeescript loop? I am looping over an object and trying to add an onclick event for each button that corresponds to each item in the object.
for id of obj
button = $("#my_button"+ id)
button.click(-> console.log id)
With this loop, every button logs the last id of the loop. How do I get each button to log the proper corresponding id?
A: It's a classic JavaScript problem. The standard solution is to wrap each loop iteration in an anonymous function, and pass id in to that function; that way, the function you're passing to click will see that particular id instance.
CoffeeScript provides a nice syntax for this purpose: do (id) -> ... compiles to (function(id){ ... })(id). So, for your example, you'd write
for id of obj
do (id) ->
button = $("#my_button"+ id)
button.click(-> console.log id)
I talk about do in my article A CoffeeScript Intervention.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Spring 3 link to external javascript halts execution I am using spring 3 and I have jquery added to my project. Now I am attempting to use the jquery number spinner plugin found at https://github.com/jogep/jquery.ui.spinner
The problem is, when I link to the external javascript file, it seems to hault all other javascript after the script inport. see below.
<script type="text/javascript" src="/starburst/resources/jqueryNumberSpinner/ui.spinner.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert("woi");
});
</script>
It cannot be an error in the script itself because I have the example working on my local machine using the exact same js file. If I delete the import for ui.spinner.js shown above, I get the alert showing up as it should. I am completely baffeled by this, does anyone have any ideas?
Thanks
EDIT: I am also using dojo in the project and I included the scripts after the dojo include statements.
A: 2 quick things to check out:
1) is jQuery core script already linked somewhere within the same page or imported header before the inclusion of ui.spinner.js?
2) is the path you indicated in the <script> tag effectively reachable from this page?
Anyways, if you use Chrome or Firefox with FireBug you could access to the JavaScript console to see a more detailed explanation of the error (e.g.: for Chrome you can access the console with shift+ctrl+i, while on mac it is command-option-i; on Firefox you can activate FireBug). There is something similar on IE 8+ also, with F12 if memory assists me.
Hth.
A: Ok I managed to find a solution, for the benefit of others. I am not sure if its spring specific but here goes ,
<spring:url var="spinnerJsUrl" value="/resources/jqueryNumberSpinner/ui.spinner.js"/>
<script type="text/javascript" src="http://jqueryui.com/themeroller/themeswitchertool/">
<!-- required for FF3 and Opera -->
</script>
<script type="text/javascript" src="${spinnerJsUrl}">
<!--testing here-->
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.spinner').spinner({ min: 0, max: 100 });
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django: Best practices for database design I'm starting a project and i've decided to use Django.
My question is regarding to the creation of the database. I've read the tutorial and some books and those always start creating the models, and then synchronizing the DataBase. I've to say, that's a little weird for me. I've always started with the DB, defining the schema, and after that creating my DB Abstractions (models, entities, etc).
I've check some external-pluggable apps and those use that "model first" practice too.
I can see some advantages for the "model-first" approach, like portability, re-deployment, etc.
But i also see some disadvantages: how to create indexes, the kind of index, triggers, views, SPs, etc.
So, How do you start a real life project?
A: Mostly we don't write SQL (e.g. create index, create tables, etc...) for our models, and instead rely on Django to generate it for us.
It is absolutely okay to start with designing your app from the model layer, as you can rely on Django to generate the correct database sql needed for you.
However, Django does provide various functions for you to replicate these database functions:
*
*triggers: Django code or MySQL triggers
*indexes: can be specified with db_index=True
*unique constraints: unique = True or unique_togther = (('field1', field2'),) for composite unique constraint.
The advantage with using Django instead of writing sql is that you abstract yourself away from the particular database you are using. In other words, you could be on SQLite one day and switch to PostgresQL or MySQL the next and the change would be relatively painless.
Example:
When you run this:
python manage.py syncdb
Django automatically creates the tables, indexes, triggers, etc, it needs to support the models you've created. If you are not comfortable with django creating your database for you, you can always use:
python manage.py sqlall
This will print out the SQL statements that Django would need to have in order for its models to function properly. There are other sql commands for you to use:
see: https://docs.djangoproject.com/en/1.3/ref/django-admin/#sql-appname-appname
A: Triggers, views, and stored procedures aren't really a part of the Django world. It can be made to use them, but it's painful and unnecessary. Django's developers take the view that business logic belongs in Python, not in your database.
As for indexes, you can create them along with your models (with things like db_index and unique_together, or you can add them later via database migrations using something like South.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: how to provide .jad file download link? We are trying to provide a download link to abc.jad file in index.html. abc.jad and index.html are both in the same folder. Following is the link.
<a href="abc.jad" type="text/vnd.sun.j2me.app-descriptor">download</a>
In spite of these, we are still not able to download this file from the web browser. It always gives the error HTTP Error 404 - File or directory not found .what can i do for that Problem? please any one give me the solution .
A: Sounds like a webserver configuration error to me, and nothing to do with Blackberrys or JADs.
If you can't download a file using a web browser, you need to check out your web server.
A: Although this is likely a server configuration issue, it is possible that the device is requesting additional files that do not exist.
A JAD file is a Java Application Descriptor (JAD) that J2ME (CLDC/MIDP) applications use to describe the Java modules associated with an application. In the case of BlackBerry applications, a JAD describes a collection of COD files that represent the compiled version of your application. The BlackBerry RAPC compiler compiles to a single COD file, but this file typically contains a collection of other COD files when your application becomes large enough.
Try performing these steps:
*
*Open application COD in archive application (WinZip, WinRAR, 7-zip, etc)
*Extract all COD files in application COD to same directory as JAD file
*Attempt to download JAD file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Invoking Web-Service without using JAX-RS I have a Web-Service with Restfull Jax-rs and I have created WSClient with Restfull but without using Jax-rs. I am using Spring3.0, Tomcat.
Here is my WSClient:
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
@Controller
public class WSClientController {
@Inject
@Named("restTemplate")
protected RestTemplate restTemplate;
private final static String articleServiceUrl = "http://HOST:8080/WS/Service/getAccounts.html";
@RequestMapping(value={"/accountMasterRoot"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}, headers={"Accept=application/xml, application/json"})
public List<AccountMasterWS> getAccountMasterRoot() {
try {
AccountMasterRoot ac = restTemplate.getForObject(articleServiceUrl, AccountMasterRoot.class);
List<AccountMasterWS> listAccounts = ac.getAccountMasterWS();
return listAccounts;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
but when I try to invoke Web-Service with this code I am getting error like :
org.springframework.http.converter.HttpMessageNotReadableException: Could not read [class com.nmmc.fas.ws.model.AccountMasterRoot]; nested exception is org.springframework.oxm.UnmarshallingFailureException: XStream unmarshalling exception; nested exception is com.thoughtworks.xstream.mapper.CannotResolveClassException: accountMasterRoot : accountMasterRoot
at org.springframework.http.converter.xml.MarshallingHttpMessageConverter.readFromSource(MarshallingHttpMessageConverter.java:116)
at org.springframework.http.converter.xml.AbstractXmlHttpMessageConverter.readInternal(AbstractXmlHttpMessageConverter.java:61)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:152)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:60)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:352)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:307)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:177)
at com.nmmc.ws.controller.WSClientController.getAccountMasterRoot(WSClientController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:636)
Caused by: org.springframework.oxm.UnmarshallingFailureException: XStream unmarshalling exception; nested exception is com.thoughtworks.xstream.mapper.CannotResolveClassException: accountMasterRoot : accountMasterRoot
at org.springframework.oxm.xstream.XStreamMarshaller.convertXStreamException(XStreamMarshaller.java:498)
at org.springframework.oxm.xstream.XStreamMarshaller.unmarshal(XStreamMarshaller.java:476)
at org.springframework.oxm.xstream.XStreamMarshaller.unmarshalReader(XStreamMarshaller.java:459)
at org.springframework.oxm.xstream.XStreamMarshaller.unmarshalInputStream(XStreamMarshaller.java:450)
at org.springframework.oxm.support.AbstractMarshaller.unmarshalStreamSource(AbstractMarshaller.java:368)
at org.springframework.oxm.support.AbstractMarshaller.unmarshal(AbstractMarshaller.java:134)
at org.springframework.http.converter.xml.MarshallingHttpMessageConverter.readFromSource(MarshallingHttpMessageConverter.java:113)
... 37 more
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: accountMasterRoot : accountMasterRoot
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:68)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:71)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:86)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:96)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:52)
at com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29)
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:136)
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:923)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:899)
at org.springframework.oxm.xstream.XStreamMarshaller.unmarshal(XStreamMarshaller.java:473)
I am totally stuck here, please help me what should I do changes in my code...
A: Hi here I am able to find out the solution now its working when I used webClient.
My controller snipped like:
@RequestMapping(value = { "/accountMasterRoot.etenderingWS" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
public List<AccountMasterWS> getAccountMasterRoot() {
try {
WebClient client = WebClient.create(articleServiceUrl);
AccountMasterRoot a = client.accept("application/xml").get(
AccountMasterRoot.class);
List<AccountMasterWS> wsl = a.getAccountMasterWS();
for (int i = 0; i < wsl.size(); i++) {
Long code = wsl.get(i).getCode();
String name = wsl.get(i).getName();
System.out.println("Code " + code + " name " + name);
}
System.out.println("End of WebService");
return wsl;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
A: <import resource="etendering-servlet.xml" />
<context:component-scan base-package="com.nmmc.ws" />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="aliases"> <props> <prop key="listAccounts">com.nmmc.fas.ws.model.AccountMasterRoot</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.nmmc.fas.ws.model.AccountMasterRoot</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Find out if decimal point is present in decimal data type I have a decimal data type.
I am getting values in multiple formats like 25 or 25.00.
How do I check if decimal point is presnet in a given decimal number?
If it's not present I have to add .00 to the number.
A: It's a bit of a hack, but I believe this does what you want unconditionally:
decimal twoDp = decimal.Round((original / 100) * 100, 2);
That certainly works for me:
using System;
class Test
{
static void Main(string[] args)
{
ShowRounded(25m);
ShowRounded(25.0m);
ShowRounded(25.00m);
ShowRounded(25.000m);
}
static void ShowRounded(decimal d)
{
Console.WriteLine(decimal.Round((d / 100) * 100, 2));
}
}
Alternatively, if this is only for display:
string formatted = value.ToString("0.00");
Or for display as currency, with the current cultural settings:
string formatted = value.ToString("c");
A: You are "getting values" in multiple formats. So you're getting strings in other words? I'm not exactly sure what you're ultimately asking for, but if you want to format the number as currency, you can do this:
decimal d = 25;
Console.WriteLine("{0:c}", d);
string d2 = "$25";
Console.WriteLine("{0:c}", decimal.Parse(d2, NumberStyles.Currency));
string d3 = "$25.00";
Console.WriteLine("{0:c}", decimal.Parse(d3, NumberStyles.Currency));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: htaccess rewriterule to forward specific folder I need a help here with .htaccess regular expressions. I want to forward this url: www.aloha.com/foo/bar/sample.html to www/aloha/foo/bar/index.php?go=sample.
I tried to use
RewriteRule /foo/bar/^(.*)?.html /foo/bar/index.php?go=$1 [L]
but it doesn't work.
I also already have another rewrite rule that clash with this rule. That's why I need to create another rule for this specific folder.
RewriteRule ^(.*)?.html index.php?input=$1 [L]
A: RewriteRule ^foo/bar/(.*?)\.html$ /foo/bar/index.php?go=$1 [L]
Some of your syntax was out of place. For example, the ^ denotes the beginning or a negation of a character class. Also, I'm assuming you want a file name, so don't use the optional capture ?.
Finally, I made the capture non-greedy. I'd encourage you to take this a step further and be more specific with your capture.
For example:
RewriteRule ^foo/bar/([^/]+)\.html$ /foo/bar/index.php?go=$1 [L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IIS7 Remote sever - Ip Address issue i have a local iis web site ( name is abc) , when accessing this web site from 2nd pc like 192.168.1.666/abc but i want replace ip address with name like Csc/abc
help me
A: ON second PC you need to add string in the file "C\WINDOWS\system32\drivers\etc\hosts" like this:
192.168.1.666 Csc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SSRS Using Sum Based On Condition From Multiple Procedures? I am creating a report and trying to Get a Sum combining values from multiple tables and can't figure it out and am beginning to wonder if it is even possible?
I have 2 stored procedures returning the same data with different time frame. One stored procedure is returning data based of Amounts in the past 12 months. The other procedure is returning sum of all Amounts for 13+ months. I have a sum for both to get the total collected for 1 year and total for 1 year+. I want to combine these total to get total for all years. The problem I am facing is totals are grouped by classification and name.
I have the following example data:
Date Class Name Earned Count Earned Amount Collected Count Collected Amount
Sept-11 Red Jack 5 10.50 2 54.20
Sept-11 Red Bill 2 22.75 4 120.58
Sept-11 Blue Jill 9 43.23 25 443.32
Sept-11 Green Bob 84 45846.33 62 4843.22
Sept-11 Green Pam 2 13.55 1 23.23
Sept-11 Green Tammy 32 2332.22 443 33232.33
Aug-11 Red Jack 1 23.50 2 33.20
Aug-11 Red Bill 2 52.75 4 323.22
Aug-11 Blue Jill 3 43.23 23 33.32
Aug-11 Green Bob 4 46.33 22 653.22
Aug-11 Green Pam 5 13.55 1 46.23
Aug-11 Green Tammy 6 1132.22 111 89.33
Totals Looks Like the following:
Date Class Name Earned Count Earned Amount Collected Count Collected Amount
Sub-Total Red Jack 33 ##.## ## ##.##
Bill ## ##.## ## ##.##
Blue Jill ## ##.## ## ##.##
Green Bob ## ##.## ## ##.##
Pam ## ##.## ## ##.##
Tammy ## ##.## ## ##.##
Year+ Red Jack 4344 ##.## ## ##.##
Bill ## ##.## ## ##.##
Blue Jill ## ##.## ## ##.##
Green Bob ## ##.## ## ##.##
Pam ## ##.## ## ##.##
Tammy ## ##.## ## ##.##
So I want to combine Year+ total to year total for each class and name. For example, I want to find Jack's Earned Count for a year and year+ so it would be 33 + 4344, except in reality I want to do this for everyone for all values listed.
In SSRS, I have grouped by class and name and have totals for year+ and I am trying to add the sum from year but It only gets the total for everyone and not just for one person and their class. I am using the following expression for one field:
=Fields!EarnedCount.Value + Sum(Fields!EarnedCount.Value, "MyEmployeeRpt")
Is there a way to take a sum based on a value like only get the Sum when Name = Bill and Class = Red. Another issue I am facing is that I don't know how many names or classes I might have. Any thoughts? Thanks for the help!
A: SSRS 2008 R2
Firstly if you are using SSRS 2008 R2, the LOOKUP function is well worth a look:
Lookup(source_expression, destination_expression, result_expression, dataset)
SSRS 2008
If you are SSRS 2008, there are two solutions:
Rewrite SQL Query
The SQL could be extracted from the stored procedures and then the queries joined, extending the time frames to span both and updating the report to filter to the required time frames, meaning that you could use the total of the whole dataset to achieve required result.
This may not be possible due to the natures of the stored procedures.
Use a Sub Reports
This solution requires you to make a sub report which you pass the Class, Name and Earned Count, the sub report then returns the combined value.
*
*Create a new Sub Report with Parameters for Class, Name, and Earned Count
*Add a new tablix with the SQL to return Year+
*Either Update the SQL to Filter on Parameters (this may not be possible due to it being stored procedure) Example:
...
Where [Class] = @Class and [Name] = @Name
OR using Filters on Tablix, filtering by Class and Name where they equal there respective parameters
*Delete all columns and rows of the Tablix apart from one field, add the following expression to return the Sum of Earned Count + value passed by the parameter
=Sum(Fields!EarnedCount.Value)+Parameters!EarnedCount.Value
*Resize the Report to be same size as tablix
*Remove border formatting (end up with a double border otherwise)
*Return to the original report add the Sub Report as a field in your tablix where you want to see a combined total passing parameters Class, Name, and EarnedCount
*Add the border to the sub report
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Programmatically (via. Credit Memos?) Clean-up Paypal Reversal in Magento I've been asked to look into a weird paypal problem a colleague is seeing on a Magento site w/r/t to paypal transactions. Specifically, if paypal flags a website payments standard transaction as possibly fraudulent and reverses the charges, it sends Magento a Reversal request via the IPN URL
http://store.example.com/paypal/ipn
which updates the order financials after a reversal and makes a note in the order history.
My colleague is reporting that Magento also attempts to automatically create a credit memo to zero out the order, but that the amounts are always off due to paypal fee charges. Because of this the order can't be closed out, and the stock remains tied up.
Unfortunately this happened months ago and we've gone beyond paypal's 28 day window for IPN logs. I'm setting up a paypal sandbox now to run some test transactions.
Before I get too deep into the code here
*
*Is this a known thing?
*Is there a known way to configure, or otherwise programmatically manipulate paypal/magento so this is handled seamlessly
*Are there third party programatic solutions that can automatically clean-up these orders?
*Any other thoughts, warnings, or gotchas before I wade in too deep are appreciated
Magento Version: 1.5.0.1
A: Best bet is to extend paypal return method and add comparison against order total and manipulate the sum returned from paypal to match order total
A: I'm not very familiar with order processing in magento and paypal specifics. But if you look into Magento 1.6.0.0-rc2 (Jul 11, 2011) release notes, you will see next 2 paypal related fixes:
*
*Automatically cancel order after the expiration of Order Valid Period (maybe, your orders will be canceled and products returned to stock?)
*Fixed Orders placed through PayPal marked as “Suspected Fraud”
*
*Added formatting amount into comparing (not sure if it is related to your problem)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to find the JMX port in a server? I am sure I can figure it out if I can see the JAVA OPTS parameters. I want to monitor a hornetq server using Jconsole, so I need the port number.
I remember using some command like java grep etc when I connected to it a while back.
A: You can also manually set the port from the JVM commandline settings, e.g:
-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.port=1616
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
A: If you know the process number you can use netstat to find what ports the program is listening on with something like
$ netstat -apn | grep <proc num>
The conventional port for JMX listeners is 1099.
A: You can programmatically access the JVM arguments like so:
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
...
RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = RuntimemxBean.getInputArguments();
A: I know it's an old post. You can also get the details from System:
String jmx1 = System.getProperty("com.sun.management.jmxremote");
String jmx2 = System.getProperty("com.sun.management.jmxremote.port");
String jmx3 = System.getProperty("com.sun.management.jmxremote.authenticate");
String jmx4 = System.getProperty("com.sun.management.jmxremote.ssl");
String jmx5 = System.getProperty("java.rmi.server.hostname");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Is it possible to identify individual wireless access points on a single wireless network? In thinking about the possible implementation of a mobile app that would identify a person's location based on wireless access points, I stumbled across a potential problem.
To put it into context, my university has WAPs in every teaching/lecture room, and this WAP would be used to identify the room they are currently in. However, it could be that that mobile device is in range of more than one WAP at a time - for example, one in the classroom and one in the corridor outside - so I am wondering if there is any way of identifying individual WAPs within range, given that from a UI perspective, often it is just the network itself that is shown?
And if identified could the signal strength of each WAP be measured individually?
Note: This would also need to be usable for guests who likely would not be able to actually connect to the network.
A: Each AP has its own wifi mac address. Part of the wifi discovery process gets a list of the available networks AND mac addresses for each network, so you should be able to get this from the OS's wifi stack somehow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i install phpmyadmin to a virtual server? I have a virtual unix server and currently i have to go through an awkward web interface thats not very easy to use. Basically i would like to be using phpmyadmin, but i don't know how to install it. As all i have to manipulate the server is a primitive control panel.
So how do i install to a virtual unix server?
A: Though this question is more suited for serverfault, but anyways here is a solution.
Download the latest archive from phpmyadmin.net
And follow the instructions at - http://www.phpmyadmin.net/documentation/#quick_install
Just to clarify the point raised by Ek0nomik, even if you dont have shell access:
You can upload the extracted files from the phpmyadmin archive to the server via FTP.
update
Here is a short step by step you can do.
*
*Download the latest phpmyadmin archive to your computer and extract it to a folder.
*rename the file config.sample.inc.php to config.inc.php
*Edit the file and change the line $cfg['blowfish_secret'] = ''; to add a value for this so you can use cookie authentication, something like this (use any random value of your own):
$cfg['blowfish_secret'] = 'gcaietr6snbct';
*Upload the folder via FTP to a folder on your server accessible via web.
If your website forder is /home/.../public_html upload the folder say phpmyadmin to which you extracted the contents of the phpmyadmin archive to this public_html folder.
Now you can access it as www.yourwebsite.com/phpmyadmin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: pager taglib not renaming exported url variables as documented I'm using this pager taglib solution, it generates the links to the pages almost as instructed. It offers a way to customize the variable names that are used to iterate over the data set, and that's precisely what is causing problems.
This is how I've got set up so far
<pg:pager url="/search"
items="1000"
maxPageItems="10"
export="from=offset,currentPageNumber=pageNumber"
scope="request">
<pg:param name="w" value="${w}"/>
<pg:param name="e" value="${e}"/>
<pg:first unless="current"><a href="${pageUrl}"> << first</a> </pg:first>
<pg:prev><a href="${pageUrl}"> < prev</a> </pg:prev>
<pg:pages>
<c:choose>
<c:when test="${pageNumber == currentPageNumber}">
${pageNumber}
</c:when>
<c:otherwise>
<a href="${pageUrl}">${pageNumber}</a>
</c:otherwise>
</c:choose>
</pg:pages>
<pg:next><a href="${pageUrl}">next ></a> </pg:next>
<pg:last unless="current"><a href="${pageUrl}">last >></a></pg:last>
</pg:pager>
Note, that based on the documentation you can control the name of the exported variables
The export expression export="versatz=offset" would cause the
pageOffset variable to be available as <%= versatz %>
As you can see I'm trying to rename too the offset to from (This is what the backend is expecting)
export="from=offset,currentPageNumber=pageNumber"
But all the generated links are in the form (Note the pager.offset=[number])
http://localhost:8080/search?w=param1&e=param2&pager.offset=10
What's that, that I'm doing wrong?
Anybody has experimented with this taglib?
Any feedback is deeply appreciated
A: I realize this is a bit late, but I encountered this same issue using the pager taglib mentioned above to support multiple unique pagers on a single page. Hope someone finds this useful...
It seems this parameter name is baked into the pager tag source code:
static final String OFFSET_PARAM = ".offset";
However, there is an id tag attribute whose value gets prefixed to the OFFSET_PARAM constant above during tag rendering. Its default value is pager:
static final String DEFAULT_ID = "pager";
These two values get concatenated to form an idOffsetParam field which is the final parameter name used internally by the pager tag:
private String idOffsetParam = DEFAULT_ID+OFFSET_PARAM;
Solution: If you specify your own id value in the tag declaration, you'll have partial control over the rendered parameter name:
<pg:pager
id="stackoverflow"
url="/search"
items="1000"
...
..
.
This will make navigational links render as ?stackoverflow.offset=10. The .offset portion of the param will remain, but at least you'll have some flexibility as to the uniqueness of the parameter name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pulling historic analyst opinions from yahoo finance in R Yahoo Finance has data on historic analyst opinions for stocks. I'm interested in pulling this data into R for analysis, and here is what I have so far:
getOpinions <- function(symbol) {
require(XML)
require(xts)
yahoo.URL <- "http://finance.yahoo.com/q/ud?"
tables <- readHTMLTable(paste(yahoo.URL, "s=", symbol, sep = ""), stringsAsFactors=FALSE)
Data <- tables[[11]]
Data$Date <- as.Date(Data$Date,'%d-%b-%y')
Data <- xts(Data[,-1],order.by=Data[,1])
Data
}
getOpinions('AAPL')
I'm worried that this code will break if the position of the table (currently 11) changes, but I can't think of an elegant way to detect which table has the data I want. I tried the solution posted here, but it doesn't seem to work for this problem.
Is there a better way to scrape this data that is less likely to break if yahoo re-arranges their site?
edit: it looks like there's already a package (fImport) out there to do this.
library(fImport)
yahooBriefing("AAPL")
Here is their solution, which doesn't return an xts object, and will probably break if the page layout changes (the yahooKeystats function in fImport is already broken):
function (query, file = "tempfile", source = NULL, save = FALSE,
try = TRUE)
{
if (is.null(source))
source = "http://finance.yahoo.com/q/ud?s="
if (try) {
z = try(yahooBriefing(query, file, source, save, try = FALSE))
if (class(z) == "try-error" || class(z) == "Error") {
return("No Internet Access")
}
else {
return(z)
}
}
else {
url = paste(source, query, sep = "")
download.file(url = url, destfile = file)
x = scan(file, what = "", sep = "\n")
x = x[grep("Briefing.com", x)]
x = gsub("</", "<", x, perl = TRUE)
x = gsub("/", " / ", x, perl = TRUE)
x = gsub(" class=.yfnc_tabledata1.", "", x, perl = TRUE)
x = gsub(" align=.center.", "", x, perl = TRUE)
x = gsub(" cell.......=...", "", x, perl = TRUE)
x = gsub(" border=...", "", x, perl = TRUE)
x = gsub(" color=.red.", "", x, perl = TRUE)
x = gsub(" color=.green.", "", x, perl = TRUE)
x = gsub("<.>", "", x, perl = TRUE)
x = gsub("<td>", "@", x, perl = TRUE)
x = gsub("<..>", "", x, perl = TRUE)
x = gsub("<...>", "", x, perl = TRUE)
x = gsub("<....>", "", x, perl = TRUE)
x = gsub("<table>", "", x, perl = TRUE)
x = gsub("<td nowrap", "", x, perl = TRUE)
x = gsub("<td height=....", "", x, perl = TRUE)
x = gsub("&", "&", x, perl = TRUE)
x = unlist(strsplit(x, ">"))
x = x[grep("-...-[90]", x, perl = TRUE)]
nX = length(x)
x[nX] = gsub("@$", "", x[nX], perl = TRUE)
x = unlist(strsplit(x, "@"))
x[x == ""] = "NA"
x = matrix(x, byrow = TRUE, ncol = 9)[, -c(2, 4, 6, 8)]
x[, 1] = as.character(strptime(x[, 1], format = "%d-%b-%y"))
colnames(x) = c("Date", "ResearchFirm", "Action", "From",
"To")
x = x[nrow(x):1, ]
X = as.data.frame(x)
}
X
}
A: Here is a hack you can use. Inside your function, add the following
# GET THE POSITION OF TABLE WITH MAX. ROWS
position = which.max(sapply(tables, NROW))
Data = tables[[position]]
This will work as long as the longest table on the page is what you seek.
If you want to make it a little more robust, here is another approach
# GET POSITION OF TABLE CONTAINING RESEARCH FIRM IN ITS NAMES
position = sapply(tables, function(tab) 'Research Firm' %in% names(tab))
Data = tables[position == TRUE]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: iOS: Are there any open-source Launcher Views like the home screen? I am looking for an open source project that allows me to have a launcher view like the iPhone/iPad home screen with the icons. Now know that Three20 has this but I do NOT want to use it.
Are there any alternatives out there?
A: I believe Three20 (Link) has recently broken their library into modules for specific uses so you don't have to use the whole massive package. It seems like the best option easily available. (reposted from comment)
A: Here is a better one to suit your needs
https://github.com/jarada/myLauncher
A: This one is better and recently updated among all available option.
https://github.com/heikomaass/HMLauncherView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python regex catch two kind of comment Exemple :
a = "bzzzzzz <!-- blabla --> blibli * bloblo * blublu"
I want to catch the first comment. A comment may be
(<!-- .* -->) or (\* .* \*)
That is ok :
re.search("<!--(?P<comment> .* )-->",a).group(1)
Also that :
re.search("\*(?P<comment> .* )\*",a).group(1)
But if i want one or the other in comment, i have tried something like :
re.search("(<!--(?P<comment> .* )-->|\*(?P<comment> .* )\*)",a).group(1)
But it does't work
Thanks
A: Try conditional expression:
>>> for m in re.finditer(r"(?:(<!--)|(\*))(?P<comment> .*? )(?(1)-->)(?(2)\*)", a):
... print m.group('comment')
...
blabla
bloblo
A: As Gurney pointed out, you have two captures with the same name. Since you're not actually using the name, just leave that out.
Also, the r"" raw string notation is a good habit.
Oh, and a third thing: you're grabbing the wrong index. 0 is the whole match, 1 is the whole "either-or" block, and 2 will be the inner capture that was successful.
re.search(r"(<!--( .* )-->|\*( .* )\*)",a).group(2)
A: the exception you get in the "doesn't work" part is quite explicit about what is wrong:
sre_constants.error: redefinition of group name 'comment' as group 3; was group 2
both groups have the same name: just rename the second one
>>> re.search("(<!--(?P<comment> .* )-->|\*(?P<comment2> .* )\*)",a).group(1)
'<!-- blabla -->'
>>> re.search("(<!--(?P<comment> .* )-->|\*(?P<comment2> .* )\*)",a).groups()
('<!-- blabla -->', ' blabla ', None)
>>> re.findall("(<!--(?P<comment> .* )-->|\*(?P<comment2> .* )\*)",a)
[('<!-- blabla -->', ' blabla ', ''), ('* bloblo *', '', ' bloblo ')]
A: re.findall might be a better fit for this:
import re
# Keep your regex simple. You'll thank yourself a year from now. Note that
# this doesn't include the surround spaces. It also uses non-greedy matching
# so that you can embed multiple comments on the same line, and it doesn't
# break on strings like '<!-- first comment --> fragment -->'.
pattern = re.compile(r"(?:<!-- (.*?) -->|\* (.*?) \*)")
inputstring = 'bzzzzzz <!-- blabla --> blibli * bloblo * blublu foo ' \
'<!-- another comment --> goes here'
# Now use re.findall to search the string. Each match will return a tuple
# with two elements: one for each of the groups in the regex above. Pick the
# non-blank one. This works even when both groups are empty; you just get an
# empty string.
results = [first or second for first, second in pattern.findall(inputstring)]
A: You could go 1 of 2 ways (if supported by Python) -
1: Branch reset (?|pattern|pattern|...)
(?|<!--( .*? )-->|\*( .*? )\*)/ capture group 1 always contains the comment text
2: Conditional expression (?(condition)yes-pattern|no-pattern)
(?:(<!--)|\*)(?P<comment> .*? )(?(1)-->|\*) here the condition is did we capt grp1
Modifiers sg single line and global
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NSMutableDictionary returns 0xffffffff instead of nil when a key doesn't exist I have an NSMutableDictionary that is doing something strange:
(gdb) po listenerRegistry
{
}
(gdb) po productID
com.mycompany.productid
(gdb) po [listenerRegistry objectForKey:[productID stringValue]]
0xffffffff does not appear to point to a valid object.
(gdb) po [listenerRegistry class]
__NSCFDictionary
(gdb)
According to the docs, nil is supposed to be returned for keys that aren't in the dictionary.
Has anyone else seen this before?
A: Answering my own question.
The objects inside the NSMutableDictionary are of the type id <MyObserverProtocol>, and it would appear that Monolo was right in his observation that the returned value looks like NSNotFound.
Apparently, Foundation classes return NSNotFound when asked for items of that type when they don't exist or aren't found (as discussed here). While the documentation lists NSArrays explicitly, I feel compelled to believe the same is happening in my case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to build complex dynamic hierarchy view (1-n & n-1)? Does anyone know how to create a complex dynamic hierarchy treeview with ASP.NET or Silverlight or any other technology that can be viewed on a SharePoint page?
We have records in our database connected to each other with keywords predecessor and successor. Now we want to have a visual overview of these records on the screen showing the hierarchy.
Example of what we want to create:
I have found many solutions for custom treeviews, charts, hierarchy views, .. but none of them could create our view dynamically.
EDIT: The boxes should be interactive and the sollution should support most common browser without installing software for the client. (If possible)
EDIT 2: The diagram will show all the courses (=box) for a training. Some courses are grouped in modules (=color) and for some courses, you have to succesfully passed one or more other courses.
Your help would be very appreciated.
A: As the relationships are interconnected these are not actually hierarchies. You want a directed graph with custom user controls for the nodes.
Try these (most are open source or free):
*
*Quickgraph
*Graph Sharp (Graph#)
*Node XL
*Microsoft Automatic Graph Layout
*GraphViz
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ActiveRecord combining relations I'm wondering if there's a nicer way to do this:
I have 2 complex relations with multiple joins joining to Table D. I want to combine/join them to get the Table D records. The following works but is there a better way?
class TableD < ActiveRecord::Base
def self.relation_three
r1 = TableA.relation_one.select("d.id")
r2 = TableB.relation_two.select("d.id")
where("d.id IN (#{r1.to_sql}) OR d.id IN (#{r2.to_sql})")
end
And if that's not possible then I have a supplementary question:
Is it possible to return an active record result class different from the record the query is based on? ie:
TableA.all.joins(:b).select("b.*") # Coerce into TableB class ?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP/MYSQL query ranking using secondary tables Working with a ranking algorithm, but I'm getting frustrated with the multiple database calls and data gyrations i'm having to go through to calculate the rank of a specific item, output it in to an array, and then sort by the rank value. Is it possible in MySQL to calculate the rank of a given row based on the data found in other tables?
SELECT key_value FROM table;
Now with the result set I need to rank each item based on various other tables information about those items. So if the output was -
|key_value|
|abcd1 |
|abcd2 |
|abcd3 |
Then based on 'abcd1' values in 3 other tables, I need to rank each entry based on the value divided by total and return the rank and then output it. Is there a way to do all this in a single SQL statement? I've thought about setting up some sql variables and storing different calls and then doing the calculation, but I'm still not sure how you would assign that to the SELECT statements output and rank it accordingly. I'm good with PHP, but i'm kind of a MySQL n00b.
This is probably confusing the way I'm describing it - I can answer more questions to help better explain what I'm trying to do.
Basically each row returned in the original statement is really only relevant to each user based on information stored about that object in 3 other tables. Need to know the best way to use the data in the 3 other tables to rank the relevancy of the data from the first table.
A: The key here is that you need to JOIN your other tables, then ORDER BY some expression on their fields.
SELECT key_value
FROM table
LEFT JOIN table_b on table_b.field = table.key_value
LEFT JOIN table_c on table_c.field = table.key_value
LEFT JOIN table_d on table_d.field = table.key_value
ORDER BY table_b.some_field DESC, (table_c.another_field / table_d.something_else) ASC
;
Depending on the join conditions, you may need to GROUP BY table.key_value or even use subqueries to attain the appropriate effect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem while invoking a Function from a Class I have a class that name Cleint in that i have a function ,i want to make a three instantiate from Cleint with diffrent result of a Function but the results are same here is my code:
Programm.cs:
class Program
{
static void Main(string[] args)
{
Cleint B = new Cleint();
Cleint k = new Cleint();
Cleint S = new Cleint();
Console.WriteLine(B.GenerateAddress());
Console.WriteLine(k.GenerateAddress());
Console.WriteLine(S.GenerateAddress());
Console.ReadLine();
}
}
and Cleint.cs:
class Cleint
{
public string GenerateAddress()
{
var parts = new List<string>();
Random random = new Random();
for (int i = 0; i < 4; i++)
{
int newPart = random.Next(0, 255);
parts.Add(newPart.ToString());
}
string address = string.Join(".", parts);
p;
return address;
}
}
thank's for your help
A: The problem is how you're using random number generation - you're creating a new instance of Random in each case.
See my article on random numbers for details, but basically you should use the same instance of Random for all the calls.
Assuming your classes aren't designed to be multithreaded, you could change it to either have a Random field in Client, or have a Random parameter in GenerateAddress. Either way, you'd create a single instance in Main and pass a reference to that same instance for all three cases.
A: Random is not really random - it is pseudo random and the default constructor uses the current time as the seed for the sequence.
When called in quick succession, this time will be the same and the sequence be the same.
You can use a static field to ensure you are using the same Random instance if you are only ever going to have one thread (as Random is not thread safe):
class Cleint
{
private static Random random = new Random();
public string GenerateAddress()
{
var parts = new List<string>();
for (int i = 0; i < 4; i++)
{
int newPart = random.Next(0, 255);
parts.Add(newPart.ToString());
}
string address = string.Join(".", parts);
return address;
}
}
A: When you create a new Random object, it uses the current time on your PC as the seed for it's generator. If you create many Random objects in a fast succession, they'll generate the same "random" numbers.
Try creating a single Random object and generating from that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531267",
"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.