text stringlengths 8 267k | meta dict |
|---|---|
Q: DataGridView Binding with Frozen Columns on UI Submission I have a form with a datagridview on it that I need to populate when the User completes a search. I don't bind the data to the grid until the search is performed because the binding source is dependent on which search they perform.
I have the following code to do my data loads by calling a stored procedure:
private void SearchData()
{
string returnMessage = string.Empty;
DateTime dateSelected = this.DatePicker.Value.Date;
// clear the DataGridView prior to running the search
DataGridView.DataSource = null;
switch (m_QueueSelected) // this is grabbed via the search criteria combobox
{
case 70: // search 1
Data.SearchOneTableAdapter.Fill(DataSet.spSearchOne, ref returnMessage, m_QueueSelected, dateSelected);
SearchOneBindingSource.DataSource = DataSet.spSearchOne;
DataGridView.DataSource = SearchOneBindingSource;
break;
case 80: // search 2
Data.SearchTwoTableAdapter.Fill(DataSet.spSearchTwo, ref returnMessage, m_QueueSelected, dateSelected);
SearchTwoBindingSource.DataSource = DataSet.spSearchTwo;
DataGridView.DataSource = SearchTwoBindingSource;
break;
default:
Data.SearchDefaultTableAdapter.Fill(DataSet.spSearchDefault, ref returnMessage, m_QueueSelected, dateSelected);
SearchDefaultBindingSource.DataSource = DataSet.spSearchDefault;
DataGridView.DataSource = SearchDefaultBindingSource;
break;
}
}
After I databind the grid, I perform some formatting on the columns, including making the first column in the grid frozen so when they scroll across the the first column will always show. I was getting an error message that said something like 'you cannot load a frozen column after another frozen column' Since I am using multiple binding sources, I found that I needed to drop the datasource first before loading any of the others. So I use the code included above:
DataGridView.DataSource = null;
This resolved the frozen column error message. However, yesterday I implemented a column header filter which has caused some issues. The filter gets built and applied to the columns using the DataBindingComplete Event
private void DataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
string filterStatus = DataGridViewFilterableColumnHeaderCell.GetFilterStatus(DataGridView);
if (!String.IsNullOrEmpty(filterStatus))
{
RecordCountLabel.Text = filterStatus;
}
}
The problem that I am having is since I change the DataGridView.DataSource = null there no columns/cells for the filter to identify and it fails when I try to perform additional searches. If I stop making the columns frozen, then I don't need to set the datasource to null and I have no issues.
Long story, short does anyone know of a way to reuse a datagridview with multiple binding sources and use a frozen column without having to set the datasource to null?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i install python-lzo-1.08? I need to install python-lzo-1.08.
When i try to do it from gz-file, i getting error:
NameError: name 'CURL_DIR' is not defined
OS: win7
I can't anywhere find windows installer (google taking only gz or broken links to msi/exe).
Maybe anybody have this file? please, share! ( sergiy.panasyuk88@gmail.com )
Or help with error "name 'CURL_DIR' is not defined".
Thanx!
A: Check this:
*
*Python Extension Packages for Windows - Christoph Gohlke : http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-lzo
This web is a treasure for the windows' people :) In that place you can download binary packages, and avoid all the usual installation and compiling.
A: You can't simply install python-lzo on a windows based system. If you take a look at the windows install guide, you will find directions for building python-lzo on your system.
Unless you know that you already have a c/c++ compiler, I would recommend downloading something like cygwin or MinGW first, installing that, then follow the instructions in the readme linked above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Checkboxes binding - what is better solution? I have more than 20 checkboxes in my wpf form. I need store IsChecked values from all of them in some object.
I know two ways.
1) bind all checkboxes to corresponding properties in object using dependency property like here
2) handle Clicked event of all of them
Which solution is better? Is there a better solution taking up less space in code-behind?
A: Definitely use a Binding
If your CheckBoxes are unrelated and are all over the place, you'll need 20 different dependency properties to bind to in your DataContext or ViewModel
If your CheckBoxes are all together, such as listed one after another or in a Grid, you can put them in a collection and bind an ItemsControl to them
<ItemsControl ItemsSource="{Binding Options}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Description}"
IsChecked="{Binding IsChecked}" />
</DataTemplate>
</ItemsControl>
</ItemsControl>
Your ViewModel or DataContext would contain something like this:
private List<Option> options;
private List<Option> Options
{
get
{
if (options== null)
{
options = new List<Option>();
// Load Options - For example:
options.Add(new Option { Description = "Option A", IsChecked = false });
options.Add(new Option { Description = "Option B" });
options.Add(new Option { Description = "Option C", IsChecked = true});
}
return options;
}
}
And your Option class would simply be
public class Option
{
public string Description { get; set; }
public bool IsChecked { get; set; }
}
A: Binding.
The reason is simple. If you decided to hook up to the IsChecked event you would have to have extra code to figure out which property to which check box.
Worse case is you have a method for each.
With binding once you set it to the checkbox you are done. All you have to do is save the object at the end.
A: If you use a good MVVM framework you can use binding without having to do them by hand(only name them to some convention) - I like Caliburn Micro but there are a lot of good ones out there.
A: To store IsChecked state I would suggest to follow the first one (using binding), it is better because binding allows keep UI and code behind more clean and decoupled.
Second one (handling an event) is most like WinForms approach so I do not see why you should follow it in WPF Application.
EDIT: Answer to question regarding multiple properties
If depends on what actually is bound to a View and how check boxes are placed in the View.
If you're using some ItemsControl container like ListView and each check box belong to single row/column - you can bind all checkboxes to a single collection like
private IList<bool> states;
public IList<bool> States
{
get
{
return this.states;
}
set
{
this.states = value;
this.OnPropertyChanged("States");
}
}
To give you a concrete answer - share please UI layout of Form where checkboxes are placed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to properly share code between applications in a django project I have several applications in my django project. I would like to re-use some of the functions across all of my apps. I created a new app, and added a custom functions.py to it. Trying the following:
from myNewApp import *
from myNewApp import functions
I get NameError: global name xxx is undefined
Am I omitting something important?
How would you recommend I solve the problem of re-using code across multiple apps?
Thanks,
A: Make sure that the directory above the app is on your PYTHONPATH
A: Imagine that you have a project called commons where you store all the code you want to share. And then you want to use the code of commons in a project called foo. Imagine that you have the follow directories:
/home/shared/commons.py
/home/tim/projects/foo.py
The commons.py have this content:
def say_hello():
return "Hello World!"
If you want to be able to import the module commons in your file test.py put in this file:
import sys
sys.path.append("/home/shared/")
import commons
print commons.say_hello()
And it will print "Hello world!".
A: You can use either a folder in the route of your project (in which you can create the functions you want and then import them to the desired app/file) or, you can either use a app/utils.py file, the problem that I have with this one is the fact that, maybe another app that wanted to use your functions/objects from the app/utils.py will have a direct reference linked to it e.g:
from app.utils import my_desired_function
Hope it helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Synchronizing to an object to be instantiated Are there any synchronizing/reference issues with this code?
(Assume that myStrings is already instantiated.)
MySynch.java:
public class MySynch
{
public static String[] myStrings = new String[10];
public static void updateStrings()
{
synchronized (myStrings)
{
myStrings = new String[10]; // Safe?
myStrings[0] = something[0];
myStrings[1] = somethingElse[4];
}
}
}
The object array myStrings may be read from by more than one thread, and has one thread that updates (writes) it by running updateStrings(). The threads that read from it will also use a synchronized (myStrings) block to read from it, of course, for safety.
Are there issues with locking the array and instantiating it again inside the synchronized block which is locking it (as above)?
A: There is an synchronization issue: when myStrings is set to a new instance, and a second thread is executing the method just after, that second thread will synchronize the second instance of myStrings.
You should synchronized on the class or any other static final object with
synchronized(MySynch.class) {
...
}
A: The only problem that I can see is there's a possibility that a read could be performed before the array has been properly instantiated.
A: You will get inconsistent value for myStrings, better have two synchronized blocks or methods one for update and another one for get on a class lock and have your myStrings private.
// update
synchronized (YourClass.class) {
// update
}
// get
synchronized (YourClass.class) {
// get
}
A: Cleaner, IMO.
public class MySynch {
private static AtomicReference<String[]> myStrings = new AtomicReference<String[]>(
new String[0]);
public static void updateStrings() {
String[] tmp = new String[2];
....
myStrings.set(tmp);
}
public static String[] getStrings() {
return myStrings.get();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I use dependency injection for external dependencies? I think I almost got this.
Say I want my app to send SMSs. But Im not sure yet if I should go with Twilio or SomeOtherSMSService. In fact, I dont really care yet. So I have something as simple as this so I could keep developing my app.
public interface ISMSService{
public bool SendMessage(string to, string message);
}
now I want to try Twilio. This is where I get confused. I can install it as a Nuget package but I dont think their C# wrapper that uses their REST API is going to match my interface at all.. and modifying it doesnt seem a good idea either.
from the readme I can see that to use it I need to do something like this
var msg = twilio.SendSmsMessage("+15551112222", "+15553334444", "Can you believe it's this easy to send an SMS?!");
And my best guess is that I should WRAP this into my own implementation of the interface.
Something like this.
using Twilio;
public TwilioSMSService : ISMSService
{
TwilioRestClient twilio;
public TwilioSMSService()
{
twilio = new TwilioRestClient("accountSid", "authToken");
}
public bool SendMessage(string to, string message)
{
var msg = twilio.SendSmsMessage("+15551112222", to, message);
if (msg != null) return true;
return false;
// this would obviously need more logic.
}
I want to make sure that Im keeping dependency injection principle with this but it seems fishy to me that I need to instantiate TwilioRestClient in the default constructor which is exactly what dependency injection i supposed to help you avoid :s .
Is this approach correct? If not how would you do it?
Please Help.
A: That's perfectly acceptable. You are abstracting the dependency of TwilioRestClient away from the consuming class. That way you can in your controllers toss in a FakeSMSService for unit testing. You shouldn't need to unit test Twilio.
A: There is a really good write-up on this on the twillio blog, we are not using mvc controllers for our project so we cannot use it but sharing the link in case it helps you out.
https://www.twilio.com/blog/2012/11/adding-dependency-injection-to-your-asp-net-mvc-twilio-app-using-mef.html
Article was a bit over my head but it looks useful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to format the value in a edit field in cakephp The price is a float value, and I want to display it like 1.000,00 instead of 1000.00
I know I can use an afterfind callback to change the value, but I will need the original value to do some math.
Is there any callback, like symfony data transformes in cakephp or do I need to use the callback, to create a second field with the formatted value.
Any other options?
echo $this->Form->input('price'); // Price is a float
In the docs and api for FormHelper I could not find anything about this.
A: i recommend using a behavior to "translate" from and to the database.
there a tons of them out there. "numeric", "decimal" etc should be the names for it
if you google for those behaviors you find sth like
http://float-dot-fixable-behavior.googlecode.com/svn/trunk/float_dot_fixable.php
it can easy be enhanced (both ways):
*
*from db: . to ,
*to db: , to .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: excel vba - transform an sql Has anyone had any luck with a vba macro that would convert this input:
update my_table
set time = sysdate,
randfield1 = 'FAKE',
randfield5 = 'ME',
the_field8 = 'test'
where my_key = '84'
;
into this output?
select count(*) from my_table
where (randfield1 <> 'FAKE'
or randfield5 <> 'ME'
or the_field8 <> 'TEST')
and my_key = '84';
update (what happens when using Remou's answer):
INPUT (what i have place in cell A1 of first sheet)-
update my_table
set time = sysdate,
randfield1 = 'FAKE',
randfield5 = 'ME',
the_field8 = 'test'
where my_key = '84'
;
OUTPUT (what is generated in a1 of the 2nd sheet once the macro is run)-
SELECT Count(*) FROM my_table
WHERE ()
)
)
)
)
)
)
)
randfield1 <> 'FAKE'
OR )
)
)
)
randfield5 <> 'ME'
OR )
)
)
)
the_field8 <> 'test')
)
)
)
)
AND my_key = '84'
;
A: I am still not sure what you want, but anyway:
Dim r As Range
Dim cl As Range
Dim s As String
Dim c As String
Dim arys As Variant
Dim i As Long, j As Long
''Assuming an existing worksheet
Set r = Sheet1.UsedRange
j = Sheet2.UsedRange.Rows.Count
For Each cl In r.Cells
c = cl.Value
''Fake spaces
Do While InStr(c, Chr(160)) > 0
c = Replace(c, Chr(160), "")
Loop
''Real spaces
c = Trim(c)
If c = ";" Then
arys = Split(s, vbCrLf)
For i = 0 To UBound(arys)
Sheet2.Cells(j, 1) = arys(i)
j = j + 1
Next
''Layout
j = j + 2
ElseIf UCase(c) Like "UPDATE*" Then
s = "SELECT Count(*) FROM " & Replace(c, "update", "", , , vbTextCompare)
s = s & vbCrLf & "WHERE ("
ElseIf UCase(c) Like "WHERE*" Then
s = s & Replace(c, "where", "AND", , , vbTextCompare)
s = s & vbCrLf & ";"
ElseIf Left(UCase(c), 3) <> "SET" Then
c = Replace(c, "=", "<>")
If Right(c, 1) = "," Then
s = s & Left(c, Len(c) - 1) & vbCrLf & "OR "
Else
s = s & c & ")" & vbCrLf
End If
End If
Next
A: Well, this does at least work for your sample input...
Sub NotExtensibleInTheLeast()
Dim sql As String
sql = _
"update my_table " & Chr$(10) & _
" set time = sysdate, " & Chr$(10) & _
" randfield1 = 'FAKE', " & Chr$(10) & _
" randfield5 = 'ME', " & Chr$(10) & _
" the_field8 = 'test' " & Chr$(10) & _
" where my_key = '84' " & Chr$(10) & _
" ;"
Dim newSql
newSql = sql
newSql = Replace$(newSql, "where", ") and")
newSql = Replace$(newSql, "update", "select count(*) from")
newSql = Replace$(newSql, "set", "where (")
newSql = Excel.Application.WorksheetFunction.Substitute(newSql, "=", Chr$(22), 5)
newSql = Replace$(newSql, "=", "<>")
newSql = Replace$(newSql, Chr$(22), "=")
newSql = Replace$(newSql, ",", " or ")
newSql = Replace$(newSql, "time <> sysdate or", vbNullString)
MsgBox newSql
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: polynomial time complexity There's this code from here
ub4 additive(char *key, ub4 len, ub4 prime)
{
ub4 hash, i;
for (hash=len, i=0; i<len; ++i)
hash += key[i];
return (hash % prime);
}
They say this takes 5n+3 instructions. How did they calculate it? How should i calculate it?
A: To make this calculation You need some base primitive system. For instance in The art of Computer programming, Knuth uses the MIX computer to do these kind of calculations. Different base computers might have different instructions, and different outcomes to this kind of calculation. In your particular example a common way to set it up would be:
*
*hash <- len (1 op)
*i <- 0 (1 op)
*i < len, i++ (2*n ops)
*key[i] lookup (n ops)
*hash + key[i] (n ops)
*hash <- hash + key (n ops)
*hash % prime (1 op)
and this would sum up as 5n + 3.
Variations might be along the lines of:
*
*declaring/creating the two hash and i, might be time consuming. A normal cpu might not need to do extra work because of the declarations, think register/stack storage.
*the hash += hash + key[i] might be counted as one operation on the base system, and so on.
Edit: Note that these kind of calculations are mostly useful as thought experiments on hypothetical hardware. A real life processor would quite likely not behave exactly as these calculations other than in very rare cases.
A: On the inside of your loop, you have 5 operations that run each iteration:
*
*compare i<len
*get index key[i]
*adding hash + key[i]
*assign into hash
*increment ++i
Your loop runs n times, thus 5n
Outside of the loop, you have 3 operations:
*
*assign len into hash hash=len
*assign 0 into i i=0
*perform hash % prime
Thus, 5n + 3.
A: Let's start counting the instructions.
*
*hash=len and i=0 execute once, no matter what, so we have at least 2 instructions.
*hash % prime and return execute at least once, so this is either 1 or 2 instructions (depending on whether or not you count "return" as an instruction... I suspect they do not).
*Each iteration of the loop requires i<< len, ++i, key[i], hash+key[i], and hash=hash+key[i]. We therefore have 5 instructions being executed once for each of the len (n) iterations of the loop.
Adding up, we get about 2 + (1 or 2) + (4 or 5)n, so that 3 + 4n <= T(n) <= 4 + 5n. 3 + 5n is reasonable; the exact answer depends on how you are counting individual instructions. A more detailed model might count simple assignments as requiring less time than e.g. the modulo operation...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I pause SlidesJS on click? I am using SlidesJS for a slideshow and I was wondering if there is a way to pause and play the slideshow on click of a button?
A: I recommend grabbing the most current version from github looks like in this new version its as simple as calling stop() and play()
He has an example here showing how as well, notice the bottom left, has the option to play and stop.
http://beta.slidesjs.com/examples/standard/
A: Your required functionality will work in the Slides 2 beta, but not in any version below 2
you can check out how it works here : https://github.com/nathansearles/slides/
A: In your jquery.slides.js file do a search for _this.stop(true);
It shows about 3-4 times, next & previous click.. and you will also see it showing for paginationLink.click
The problem i was having was the slider was stop sliding after click either previous, next or pagination. I needed the slider to restart.. so what i did was add a setTimeout to play()
_this.stop(true);
setTimeout(function ()
{ _this.play(true) }, 3000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tabcontrol, vb.net, tab button mouse over style I have a vb.net windows forms project with a tabcontrol.
Anyone know how to change the style of the tabpage title or "button" when you hover over it with the pointer ?
I guess you can change the colours with:
TabControl1.SelectedTab.BackColor = Color.Black
But not sure how to hook up the mouseover to the hovered over tab title/button.
A: If you want to change color of the tab page (i.e. area with tab content), it is very easy to do as shown below.
However, if you want to change tab button, then you need to set TabControl1 DrawMode to TabDrawMode.OwnerDrawFixed and then handle DrawItem event.
Public Class Form1
Private Sub TabControl1_MouseEnter(sender As System.Object, e As System.EventArgs) Handles TabControl1.MouseEnter
TabControl1.SelectedTab.BackColor = Color.Black
End Sub
Private Sub TabControl1_MouseLeave(sender As System.Object, e As System.EventArgs) Handles TabControl1.MouseLeave
TabControl1.SelectedTab.BackColor = DefaultBackColor
End Sub
End Class
A: The TabControl has a basic form of this functionality built in. Try setting HotTrack = True. When you mouseover the tab, it will change text colour.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring interceptor/filter I need to write an interceptor/filter in my spring-jersey application, which will check every request for session and on success it will pass a code to respective controller. Passing this code is imp, because based on the code controller will decide further action.
Q:
1) Is this possible to write this kind of login filter in Spring? How?
2) Is this possible to pass some code to controller from interceptor? How?
A: We need to implement ContainerRequestFilter interface for creating Jersey filter. Following is the code sample for intercepting and modifying a request using jersey filter:
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.log4j.Logger;
/**
*
* @author arnav
*/
public class MyAppFilter implements ContainerRequestFilter{
public ContainerRequest filter(ContainerRequest request) {
MultivaluedMap<String, String> headers = request.getRequestHeaders();
headers.add("code", "MY_APP_CODE");
request.setHeaders((InBoundHeaders)headers);
return request;
}
}
After adding this class, we need to register this filter for our web application. So now we will add following lines in our web.xml:
<servlet>
..........
..........
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>package.MyAppFilter</param-value>
</init-param>
</servlet>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Open browser tab in php I have a client(JavaScript) server(PHP) application using AJAX. On the AJAX request my PHP script returns some info to the client AND needs to open a separate browser tab as a separate process, asynchronously.
How can I do that (exec, shell_exec, passthru ... don't work)?
A: You cannot control this from server-side code. You would have to issue some javascript to the client, and have that JS code open the window/tab and point that window/tab at the URL which provides your data. Of course, you can just output the full page contents for this JS code to stuff into the window as well. But regardless, you cannot make the browser open a window directly from the server. At most you can suggest via some JS, or a target="..." attribute on a link or form.
A: When you receive the info from the Ajax request, open a new tab using JavaScript.
A: You can never, ever decide on the behaviour of client's browser. It's up to the user whether they want to open up a tab. Therefore, not only that you can't force tab opening, you shouldn't be able to do it in the first place.
A: You just output it to the client side
<?php
echo '<script>window.open("http://addr.com", "_blank", "width=400,height=500")</script>';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Geronimo StAX can't locate Woodstox implementation Using ant, I am trying to invoke a self-defined task, in which I am trying to call a web services using Axis2. I am providing all the jars by Class-Path manifest header in the parent jar. Both geronimo-stax-api_1.0_spec-1.0.1.jar and wstx-asl-3.2.4.jar are defined on Class-Path. StAX api(from geronimo-stax-api_1.0_spec-1.0.1.jar) is trying to use com.ctc.wstx.stax.WstxInputFactory(from wstx-asl-3.2.4.jar). I am getting Classloader can't locate the class. This seems to be a class loader problem, but I can't find anything wrong. The weird thing is if I put wstx-asl-3.2.4.jar on my system classpath, it will be located. But the jar spec from Sun/Oracle indicates Class-Path and system classpath function the same, use the same system class loader. BTW, as you see, some jars are osgi bundle, I am not sure this will cause any problem.
The stacktrace is shown below:
javax.xml.stream.FactoryConfigurationError: Requested factory com.ctc.wstx.stax.WstxInputFactory cannot be located. Classloader =java.net.URLClassLoader@341960
at javax.xml.stream.FactoryLocator.loadFactory(FactoryLocator.java:120)
at javax.xml.stream.FactoryLocator.locate(FactoryLocator.java:109)
at javax.xml.stream.FactoryLocator.locate(FactoryLocator.java:54)
at javax.xml.stream.XMLInputFactory.newInstance(XMLInputFactory.java:41)
at org.apache.axiom.om.util.StAXUtils$7.run(StAXUtils.java:311)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.axiom.om.util.StAXUtils.getXMLInputFactory_perClassLoader(StAXUtils.java:306)
at org.apache.axiom.om.util.StAXUtils.getXMLInputFactory(StAXUtils.java:76)
at org.apache.axiom.om.util.StAXUtils.createXMLStreamReader(StAXUtils.java:131)
at org.apache.axis2.util.XMLUtils.toOM(XMLUtils.java:596)
at org.apache.axis2.util.XMLUtils.toOM(XMLUtils.java:581)
at org.apache.axis2.deployment.DescriptionBuilder.buildOM(DescriptionBuilder.java:97)
at org.apache.axis2.deployment.AxisConfigBuilder.populateConfig(AxisConfigBuilder.java:86)
at org.apache.axis2.deployment.DeploymentEngine.populateAxisConfiguration(DeploymentEngine.java:641)
at org.apache.axis2.deployment.FileSystemConfigurator.getAxisConfiguration(FileSystemConfigurator.java:116)
at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContext(ConfigurationContextFactory.java:68)
at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContextFromFileSystem(ConfigurationContextFactory.java:184)
at org.apache.axis2.client.ServiceClient.configureServiceClient(ServiceClient.java:150)
at org.apache.axis2.client.ServiceClient.<init>(ServiceClient.java:143)
at org.apache.axis2.client.ServiceClient.<init>(ServiceClient.java:244)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: resolve Merge conflict with subversive How to resolve a merge conflict when merging a branch back to trunk with subversive. (e.g a File have different changes at the same position)
i did the folowing:
*
*selected merge at a project (team merge)
*selected branch url
*execute merge
==> conflicts are now shown in syncronize view
*select resolve conflict
==>Conflicts are shown in the Compare view
*edit the working copy to resolve one conflict
So far it worked but now i want to save the working copy and show the remaining conflicts in that file.
But when i save the working copy the conflict view is not updated. And when i reopen the conflict view i didnt see my previous changes. That makes it impossible to resolve conflicts.
thx for helping
(Eclipse 3.6, subverive 0.7.9, svnkit 1.3.5)
i use the newest subverive version and svnkit
A: You just need to right click on the file; team --> mark as merged
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Strange behavior of html I don't know why but when i have html i this order:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<div id="header" style="width: 1020px; height: 50px; vertical-align: sub; margin: 0 auto; text-align: left; background-color: white;">
{% if user.is_authenticated %}
<span><a class="header_urls" href="{{ URL }}/accounts/profile/">Profile</a> </span>
<span style="float: left; color: blue; vertical-align: sub"><a class="header_urls" href="{{ URL }}/blog/">Blog</a> </span>
<span style="float: left; color: blue; vertical-align: sub"><a class="header_urls" href="{{ URL }}/gallery/newest/1">Something</a> </span>
{% endif %}
</div>
</html>
Outpu is: Blog, Somthing, Profile.
and in chrome code spectrator code is in this order, it display this things in other order. Why could it be?
A: If the items are in different order you probably have float: right on them
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: node specific google analytics tags in Drupal I need to put this kind of tags (floodlight/doubleclick - Google Analytics) in some nodes in my Drupal site -each code snippet/GA tag is specific and different-. How can I put this specific tags in specific nodes? -near the tag if possible?-
blocks? or there's a module that could help in this case?
Thanks for any help, this is an emergency!
<!--
Inicio de la etiqueta Floodlight de DoubleClick: No elimine el
nombre de actividad de esta etiqueta: Tag 001
URL de la página Web en la que se espera que se inserte la etiqueta:
Esta etiqueta se debe insertar entre las etiquetas <body> y </body>, tan cerca como sea posible
de la etiqueta de apertura.
Fecha de creación: 09/06/2011
-->
<script type="text/javascript">
var axel = Math.random() + "";
var a = axel * 10000000000000;
document.write('<iframe src="http://fls.doubleclick.net/activityi;src=33000080;
type=tagss090; cat=tag00425;ord=' + a + '?" width="1" height="1" frameborder="0"
style="display:none"></iframe>');
</script>
<noscript>
<iframe src="http://fls.doubleclick.net/activityi;src=33000080;type=tagss090;cat=tag00425;
ord=1?" width="1" height="1" frameborder="0" style="display:none"></iframe>
</noscript>
<!-- Fin de la etiqueta Floodlight de DoubleClick: No eliminar -->
A: The way I've typically done tracking codes like that in the past was to add the code to a block in Drupal and use the block visibility settings to specify which nodes to load the block on.
A: This doesn't help with the OP's SEO "emergency", but this module was reviewed and published as full project to Drupal.org a few months ago and might help someone else who ends up on this post after searching Google for drupal + doubleclick + floodlight.
https://www.drupal.org/project/doubleclick_floodlight
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alfresco SSO with Cookie I want to integrate Alfresco with my current login system (which is an LDAP server). I can successfully integrate LDAP authentication in, however, I want to use an external login page and have Alfresco read a cookie to log the user in (the cookie will contain the username and a key which can be used to verify they're logged in with the LDAP server).
I looked into the example that came with the SDK, but there doesn't seem to be a way to login the user in without a password.
I was looking into the External Authentication Subsystem, and saw the CAS guide, but that seems like overkill and I'm not sure I understand everything that's going on or why all of that is needed for my situation.
After poking around in the Exernal subsystem, I saw it uses "SimpleAcceptOrRejectAllAuthenticationComponentImpl", which overrides the authentication function. In that function it authenticates a user via a "setCurrentUser" function, but that relies on the value of "accept" being set to true. I grepped through the Alfresco source, and looked in the files under WEB-INF/classes/alfresco/subsystems/Authentication/external, but I couldn't find out how the setAccept function ever got called. After some googling I found this example.
It looks like they setup a filter that logs the user in via a SimpleAcceptOrRejectAllAuthenticationComponentImpl object where they explicitly call setAccept(true). I haven't tried this yet, but their wiki says the web.xml file needs to be edited, something an Alfresco Dev said in another post wasn't needed after Alfresco v3.2 (I'm using v3.4.3). Is this the right avenue to go down?
I've heard another idea would be to write my own Authenticator subsystem, but I don't see any docs on that, and without knowing how the "setAccept" function gets called for the External subsystem, I feel like I'd be shooting in the dark.
Any thoughts on how to login a user in based on a cookie created by an external webapp (which is on the same domain - I've been able to read the cookie, I just don't know how to authenticate a user without a password)?
A: I figured I'd post the solution for anyone who had the same problem.
Step 1: Create a filter that will be executed when someone tries to hit one of your URLs. Once the filter is created, compile and package it in a jar, and then place that jar inside of the alfresco.war and share.war (in the location "WEB-INF/lib"). Here is a skeleton version of what the filter code will look like:
package sample.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
public class SSOIntegrationFilter implements Filter {
private static final String PARAM_REMOTE_USER = "remoteUser";
private static final String SESS_PARAM_REMOTE_USER = SSOIntegrationFilter.class.getName() + '.' + PARAM_REMOTE_USER;
@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
String remoteUser = proprieterayUserIdValidationAndExtractionMethod(req.getParameter(PARAM_REMOTE_USER));
// We've successfully authenticated the user. Remember their ID for next time.
if (remoteUser != null) {
HttpSession session = httpServletRequest.getSession();
session.setAttribute(SESS_PARAM_REMOTE_USER, remoteUser);
}
chain.doFilter(new HttpServletRequestWrapper(httpServletRequest) {
@Override
public String getRemoteUser() {
return (String) getSession().getAttribute(SESS_PARAM_REMOTE_USER);
}
}, res);
}
private String proprieterayUserIdValidationAndExtractionMethod(String param) {
return "admin"; // who to login as, replace with your cookie login code
}
}
Step 2: Configure the web.xml file for tomcat to recognize this filter (mine was located in /usr/share/tomcat/conf).
<filter>
<filter-name>Demo Filter</filter-name>
<filter-class>sample.filter.SSOIntegrationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Demo Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Step 3: Make the following changes to your share-config-custom.xml file (should be located in the shared directory): http://docs.alfresco.com/3.4/index.jsp?topic=%2Fcom.alfresco.Enterprise_3_4_0.doc%2Ftasks%2Fauth-alfrescontlm-sso.html
Step 4: Update your alfresco-global.properties file with the following information:
authentication.chain=external1:external,alfrescoNtlm1:alfrescoNtlm
external.authentication.proxyUserName=X-Alfresco-Remote-User
Then start up Alfresco and try it out. Hopefully this will put you on the right track.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Git Merge Conflict (UU): How do I resolve conflict without adding file to next commit? How do I resolve a UU (merge conflict) without adding that file to the next commit.
For example, I just cherry picked a commit to another branch and there were merge issues. I solved the merge issue and want UU readme.txt changed to M readme.txt but it not be added to the next commit I make.
Thanks
A: I don't know what version of git you were using back in '11, but right now I'm on 1.7.7.4.
It appears to me that doing an add to mark the conflict resolved does add the file to the stage; so my approach is:
git add <filename>
git reset HEAD <filename>
You could also create a custom git command that does this for you. I created an executable file named git-resolve (no extension) in a directory on my path (I like to put stuff like this in ~/.bin) and put this in it:
git add $@
git reset HEAD $@
Then from the command line, after I've resolved my conflicts, I can do:
$ git resolve <filename>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to get text position in PDF using PHP, TCPDF & FPDI? I have an issue:
I need to upload some PDF template with data and then change it.
For example, in PDF file is string:
NAME:
I need get position of this string and insert some text (username etc.) after it.
Is it possible ?
Update
The PDF isn't encrypted. Text is embedded as text.
A: If the PDF isn't encrypted (no master/client password), and the text is embedded as text and not as a rendered image, you can just do some basic string search/replace on it - PDFs are essentially Postscript code, and you can treat that as plain text for the most part.
A: This is not trivial and not possible with 100% reliability inside a PDF file because you may have to re-render the layout (to accommodate for elements moving, lines breaking etc.)
If you need to change some static form fields, you may be able to work with simple search+replace operations. For anything more complex, see e.g. this question of mine for some background and possible solutions: PHP PDF template library with PDF output?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Borders not shown in Firefox with border-collapse on table, position: relative on tbody, or background-color on cell Consider the following HTML:
<html>
<head>
<style>
TABLE.data TD.priceCell
{
background-color: #EEE;
text-align: center;
color: #000;
}
div.datagrid table
{
border-collapse: collapse;
}
div.datagrid table tbody
{
position: relative;
}
</style>
</head>
<body>
<div id="contents" class="datagrid">
<table class="data" id="tableHeader">
<thead>
<tr class="fixed-row">
<th>Product</th>
<th class="HeaderBlueWeekDay">Price</th>
<th class="HeaderBlueWeekDay">Discount</th>
</tr>
</thead>
<tbody>
<tr style="font-style: italic;">
<td>Keyboard</td>
<td class="priceCell">20</td>
<td style="border-right: #3D84FF 1px solid; border-left: #3D84FF 1px solid;" class="priceCell">2</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Notice that the last cell has a left and a right border in its inline style. You (or at least I) would expect this to be visible. In IE, this is the case. But in Firefox (6), this is not. You can solve this by:
*
*Removing position relative on div.datagrid table tbody in the CSS
*Changing div.datagrid table tbody to div.datagrid table in the CSS
*Removing the background-color on table.data td.priceCell in the CSS
*Removing the border-collapse on div.datagrid table in the CSS
This is a simplified version of our code; we also solved it (by choosing option 2). But what I'm wondering about is:
*
*Is this a bug in Firefox?
*Is this a bug in IE?
And especially: what is the reason Firefox wouldn't show the borders when the CSS is as it is?
A: This is a bug in firefox and hopefully they fix it soon. But in the mean time I was able to fix this issue for me by setting my td cells to position: static. Hopefully that will help someone else.
td {
position: static;
}
A: This looks like a Firefox bug to me. The backgrounds are painting over the borders; you can see it if you use a translucent background color.
I filed https://bugzilla.mozilla.org/show_bug.cgi?id=688556
A: Another possible solution is to correct colspan errors in your table markup.
Apparently can colspan errors cause the same effects with hidden borders when using border-collapse: collapse;
I was directed to the right solution through http://www.codingforums.com/html-and-css/46049-border-collapse-hiding-some-outside-borders.html.
In my table I had written <th colspan="9"> when there was only 8 columns.
That caused error (hidden right border) in
*
*Chrome 51.0.2704.103 m (64-bit)
*Vivaldi 1.2.490.43 () (32-bit)
but rendered with right borders in
*
*Firefox 44.0.2
*IE 11 (11.420.10586.0)
*Edge 25.10586.0.0
A: Just ran into this issue and came to a css only solution:
just add background-clip: padding-box to your td element.
See this article for more information: https://developer.mozilla.org/en-US/docs/CSS/background-clip
A: Just to put all in one place.
The problem is produced when you have a cell with position relative inside a table with collapsed borders (as Boris indicated and filled in the bug https://bugzilla.mozilla.org/show_bug.cgi?id=688556)
This can be easily solved using CSS as indicated by user2342963 (Adding background-clip: padding-box to the cell).
You can see the problem (with Firefox) and the fix here: http://jsfiddle.net/ramiro_conductiva/XgeAS/
table {border-spacing: 0px;}
td {border: 1px solid blue; background-color: yellow; padding: 5px;}
td.cellRelative {position: relative;}
td.cellRelativeFix {background-clip: padding-box;}
table.tableSeparate {border-collapse: separate;}
table.tableCollapse {border-collapse: collapse;}
<table class="tableSeparate">
<tbody>
<tr>
<td class="cellRelative">position: relative</td>
<td>position: static</td>
</tr>
</tbody>
</table>
<table class="tableCollapse">
<tbody>
<tr>
<td class="cellRelative">position: relative</td>
<td>position: static</td>
</tr>
</tbody>
</table>
<table class="tableCollapse">
<tbody>
<tr>
<td class="cellRelative cellRelativeFix">position: relative</td>
<td>position: static</td>
</tr>
</tbody>
</table>
A: The best way to solve this issue is to do something like this.
Note the position: relative property in the "thead" and the "tbody' elements, those are important. So are the border-collapse and background-clip properties. Works with background-color on all and alternating rows.
table {
width: 100% !important;
border-spacing: 0;
border-collapse: unset !important;
thead {
position: relative;
left: -1px;
top: -1px;
tr {
th {
background-clip: padding-box;
border-top: 1px solid #737373!important;
border-left: 1px solid #737373!important;
border-right: none !important;
border-bottom: none !important;
&:last-child {
border-right: 1px solid #737373!important;
}
}
}
}
tbody {
position: relative;
left: -1px;
top: -1px;
tr {
&:last-child {
td {
border-bottom: 1px solid #737373!important;
}
}
td {
background-clip: padding-box;
border-top: 1px solid #737373!important;
border-left: 1px solid #737373!important;
border-right: none !important;
border-bottom: none !important;
&:last-child {
border-right: 1px solid #737373!important;
}
}
}
}
}
A: Adding another solution for this (old) issue: This happened to me today, because I have a somewhat complicated table with multiple tbody.
The only issue was actually that I had an opened tbody tag that was not closed. I deleted that tag and the borders re-appeared, without needing to change anything in my CSS.
To clarify, my structure was something like:
<table>
<thead>
<tr><th>Col1</th><th>Col2</th></tr>
</thead>
<tbody>
<tbody>
<tr><td>Val1</td><td>Val2</td></tr>
<tr><td>Val3</td><td>Val4</td></tr>
</tbody>
</table>
A: For me add border-collapse attribute to separate inside table solved the problem
Like this:
margin-bottom: 0;
color: #333333;
font-family: "Poppins", sans-serif !important;
border-collapse: separate;
Where as in chrome, we don't need to set this attribute and works fine even without mentioning too.
A: The table body should not have
"position":"relative".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Q: The 2010 Loebner Prize winner bot: Suzette What are some of the techniques that a machine could use to be able to carry a good conversation/pass the Turing Test? I know this has to do with Natural Language Understanding and Processing, but I need more details.
I'm particularly interested in the chatbot Suzette who won the 2010 Loebner Prize.
Thank you
A: As of writing this nothing can yet pass the Turing Test.
Not an answer as such but if you're looking for something that can, then there isn't one yet known to man.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Content Provider and Content Observer Example? I am new to Android development and playing with content providers and content observers. However I am having trouble finding examples online. I have been playing and reading about this but have become stuck. Here is what I am trying to do:
I have created a small content provider (that I have confirmed is working and inserting/deleting data in a db on the phone). We will call this A.apk. Now I want to create a B.apk that will be notified with any updates done to the db. So if new content is created B will display it and if content is delete it will be removed from B's view.
I am stuck and would love to see how this is done correctly using best practices. An example would be much appreciated!
A: This is actually very easy.
*
*Just implement a ContentObserver and register it with the URI of the database to watch. In the example about when A uses B's ContentProvider to put data into B's defined database, B's ContentObserver's onChange() method will be triggered. There is a problem however if B is not running when a change is made.
*Another solution is for A to use B's ContentProvider to insert data into B's database, then send an intent to B that new data is waiting.
*Or in the implementation of B's ContentProvider it could start and Activity belonging to B.
Depending on what the application's needs and concerns are will determine which method to use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why are the ActionView::Helpers::UrlHelper not available in the assets pipeline? In ajax heavy applications having a javascript/coffeescript file that is aware of the routes in a rails application seems common and reasonable. Yet it is not easy access the url_for helper in your assets.
I commonly see people inline a variable in their views that the javascript reads. And there are a few plugins that make routes available via a javascript object. See Accessing rails routes in javascript.
Am I missing an easy way to do this? Is this a bad practice? What is the alternative?
A: Because the standard way of using the pipeline is to compile the JS files to one file with a fingerpint, I don't think there is an alternative to doing this.
The URL helpers often require some sort of context in the form of variables or params. For example:
question_path(@current_question)
These are not going to be available when the JS files are compiled for production.
Passing in a generated path via a content block seems OK to me (I do it in a current app).
A: Get the path from the view
The way we typically handle this is to have Javascript get any paths it needs from the HTML, which was rendered using all the view helpers.
For example, if you need to ajaxify a form, have the form's action attribute contain the correct URL for AJAX submission, and have Javascript look for it there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Application vanishes when trying to invoke an OLEDB provider with VB6 Form I have to use an OLEDB provider (for Sungard Investran) from my crystal reports in Winforms Application. Using .Net 4, Crystal Reports for VS2010. The OLEDB Provider has a Parameters Dialog, which I believe is developed in VB6. When I call this OLEDB provider with Queries without any Parameters, it works fine. But when calling any Query with Parameters, the entire application just vanishes. Everything Works fine on Windows XP but has this issue in Windows 7. The app is compiled for x86 platform only. Tries with "all platforms" too, same issue.
I see two errors in the Windows Event Log
* Error 1
Application: MyApplication.exe Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: exception code c0000005, exception address 071116C0
*Error 2 *
Faulting application name: MyApplication.exe, version: 1.1.2009.130,
time stamp: 0x4e7b4051 Faulting module name: unknown, version:
0.0.0.0, time stamp: 0x00000000 Exception code: 0xc0000005 Fault
offset: 0x071116c0 Faulting process id: 0xa14 Faulting application
start time: 0x01cc793091b8b5b0 Faulting application path:
C:\MYApp\MyApp\bin\x86\Debug\MyApplication.exe Faulting module path:
unknown Report Id: d351c329-e523-11e0-a2de-0023240631a8
Any Pointers to Fix this issue is highly Appreciated.
thanks
A: Found a solution hard way. We need to set uiaccess=true in the manifest. Guidance is provided on this thread. Caveat is that it is very annoying as there are lot of restrictions around this solution. But it works though. Welcome to the world of x64.
Thank you all who showed interest in this issue and tried to find a solution for me. And I am proud to be part of this community who cares for each of us.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does this JSP scriptlet fail with a NullPointerException? I can print out pageModel.foo using EL:
${pageModel.foo}
But this scriptlet fails at the line where I check the length() of foo:
java.lang.String foo = (java.lang.String)pageContext.getAttribute("pageModel.foo");
if(foo.length()>10){
foo = foo.substring(0, 9);
}
It throws a NullPointerException - which doesn't make sense because ${pageModel.foo} works!
A: There are a couple of problems with the code you posted:
*
*The EL ${pageModel.foo} doesn't load an attribute called "pageModel.foo" - it loads an attribute called "pageModel" and gets it's "foo" property.
*pageContext.getAttribute() only loads attributes from the page scope. However, EL can access attributes from many scopes - you should use pageContext.findAttribute() instead.
code:
String foo = "";
PageModel pageModel = (my.package.PageModel)pageContext.findAttribute("pageModel");
if (pageModel != null) {
foo = pageModel.getFoo();
if(foo.length()>10){
foo = foo.substring(0, 9);
}
}
A: The answer is already given by Nate, so I won't repeat it.
However, I usually supplement answers with answers which answers what the questioner really needs instead of what the questioner asks. It namely look much like that you're totally unaware of JSTL core tags and functions. You should really prefer it over fiddling with ugly scriptlets.
<c:set var="foo" value="${pageModel.foo}" />
<c:if test="${fn:length(foo) > 10)}">
<c:set var="foo" value="${fn.substring(foo, 0, 9)}" />
</c:if>
<p>${foo}</p>
or, with the conditional operator ?::
<c:set var="foo" value="${(fn:length(pageModel.foo) > 10) ? fn.substring(pageModel.foo, 0, 9) : pageModel.foo}" />
<p>${foo}</p>
Much better, isn't it?
Keep in mind: whenever you need a scriptlet <% %>, then chances are very big that you're looking for a solution in the wrong direction. Think twice about finding the solution and look in direction of taglibs, EL functions or just servlets/filters.
A: The attribute is pageModel, not pageModel.foo.
Not that you should be doing that in a scriptlet anyway :(
A: Try something like:
Map m = (java.util.Map) pageContext.getAttribute("pageModel");
String foo = (String) m.get("foo");
if(foo.length()>10){
foo = foo.substring(0, 9);
}
I'm not quite sure what kind of object pageModel is but its probably a Map.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to calculate recent row average value using MDX? My data example:
id value_a
1 1.0
2 2.0
3 3.0
4 4.0
which I want is
id / value_a / recent_n_avg
1 1.0 0.33
2 2.0 1.00
3 3.0 2.00
4 4.0 3.00
recent_n_avg is average for recent n rows( n=3 in example).
How to use MDX to solve this problem.
Thanks.
A: If you want do it only for one dimension and this dimension is flat you can write following expression for new calculated member:
SUM({[Dimension].CurrentMember.Lag(2):[Dimension].CurrentMember}, [Measures].[Your measure])/3
Also, you should remember about member "All" and members # 1,2 in your dimension.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: templates function specialization, c++ I am practicing function specialization, and I was trying to create a little storage object with a specialized print function. Here's my code:
#ifndef STORAGE_HPP_
#define STORAGE_HPP_
#include <iostream>
using namespace std;
template <typename T, int size> class Storage
{ //LINE 16 ERROR
public:
Storage():arr(new T*[size]){};
~Storage()
{
for (int i = 0; i < size; i++)
{
delete arr[i];
}
delete[] arr;
}
void push(T obj, int i)
{
arr[i] = new T(obj);
}
void print()
{
for (int i = 0; i < size; i++)
{
cout << *arr[i];
}
cout << endl;
}
private:
T** arr;
};
template <typename T, int size> void Storage<int,size>::print() //LINE 38 ERROR
{
for (int i = 0; i < size; i++)
{
cout << (char) *arr[i];
}
cout << endl;
}
#endif /* STORAGE_HPP_ */
And I get this error:
../Storage.hpp:38:63: error: invalid use of incomplete type
class Storage<int, size>
../Storage.hpp:9:1: error: declaration of ‘class Storage<int, size>’
So, first question: can specialized functions be implemented inside a class? I tried but got an error.
Second, why do I get the error I've attached?
Thanks!
EDIT: I tried something new as someone here suggested. I've change print inside the class to be only void print() and I've implemented it outside so I can overload the function. Here:
template <typename T, int size>
void Storage<T,size>::print()
{
for (int i = 0; i < size; i++)
{
cout << *arr[i];
}
cout << endl;
}
template <typename T, int size>
void Storage<int,size>::print() //ERROR HERE
{
for (int i = 0; i < size; i++)
{
cout << *arr[i];
}
cout << endl;
}
Now I get invalid use of incomplete type ‘class Storage<int, size>’Where I wrote ERROR HERE (obviously!)
I understand that's a common solution, am I right? And why do I get this error?
A: The problem is that you are trying to use a partial specialization of the entire class without having defined the partially-specialized class.
If print were itself a function template, the situation would be different, because you can indeed specialize function templates. However, your construction only has the entire class as a template.
This means that template <typename T, int n> class Storage<T, n> and template <int n> class Storage<int, n> are entirely different, unrelated classes. Thus you must first define the latter class:
template<int n> class Storage<int, n>
{
// define everything
};
template<int n> void Storage<int, n>::print() { /* implement */ }
Consider that the partial specialization Storage<int, n> may be an entirely different class from the primary template, and it may have totally different member functions. The compiler has no way of knowing this until you actually define that class.
Following sbi's comment, here's one idea:
//... in the class definition
template<typename S, int m> friend void print_helper(const Storage<S, m> &);
template<int m> friend void print_helper(const Storage<int, m> &);
void print() { print_helper(*this); }
// outside:
template <typename S, int size> void print_helper(const Storage<S, size> & s)
{
// ...
}
template <int size> void print_helper(const Storage<int, size> & s)
{
// ...
}
Instead of the friend you could also make the helper function template static, but that might add a lot of code bloat, since you'll have two static function templates per class type, rather than just two globally.
A: Partial specializations always need to use the complete template, since they define a template too.
So this would not work:
template <int size> void Storage<int,size>::print()
Full specializations of member functions can be done out of line for single member functions, because they define functions.
So this would work:
template <> void Storage<int,44>::print()
And you can not declare/define any (partial) specializations within the primary template.
A: I don't think you can use partial specialisation on a single method. You can only use full specialisation.
The question is: why do you want to use an array with a specified size? Why not just use an std::vector and let the push() function size it dynamically (with std::vector::push_back() )?
A: The only error I can see is an extraneous typename T in your specialization. It should be:
template <int size> void Storage<int,size>::print() {...}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Authenticating and authorizing users on MVC and WCF Knowing so little about WCF, ASP.Net and Authentication/Authorization that I'm having a hard time explaining what is bothering me.
I'm using ASP.Net MVC 3 app as a front end for a system I'm developing. This web site talks to a WCF web service and gets all it's info from it.
There will be pre-defined users and each user has unique access (so a action may resolve in info specific to that user). Also the login info for users will be stored service side.
Now the question is, how do I handle authentication and/or authorization?
I want users to be able to log in to the website so I guess he will make a validation call over to the webservice and if validated set a forms.authentication cookie client side.
Then if he makes a new request like ChangePassword (unique to him) should I somehow validate him again? Perhaps have created a token for him to send along his request?
Could I perhaps just do all the validation service side even so that the Service knows who the user is and returns only data related to him (without having to specifically mention him in the method call?
Does a service like this differentiate somehow between the authorization of the client web site and the user himself? I mean I want to ensure that both the tool being used is legal and that the action the user is trying to perform is ok.
I'm having a hard time understanding how all this works together and would rather have a explanation on how this works instead of a tutorial on how to do this(like a google search does).
A: "I'm having a hard time understanding how all this works together "
That's a pretty good summary of WCF. :)
WCF will use membership/role providers for logins. They need to be configured in the serviceModel section of the config file.
Your service's users will use either the username/password properties of the proxy or they will have to generate the ws-security xml config themselves if not using a generated proxy.
I've removed everything but the membership/roles stuff, so this isn't (probably) a working config section.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MyCompany.Api.Services.WebService.MyProductServiceBehavior">
<serviceCredentials>
<userNameAuthentication
userNamePasswordValidationMode="MembershipProvider"
membershipProviderName="MyCompanyMembershipProvider" />
</serviceCredentials>
<serviceAuthorization principalPermissionMode='UseAspNetRoles' roleProviderName='MyCompanyRoleProvider' />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="MembershipBinding">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="MyCompany.Api.Services.WebService.MyProductServiceBehavior" name="MyCompany.Api.Services.WebService.MyProductService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="MembershipBinding" contract="MyCompany.Api.Services.WebService.IMyProductService" />
</service>
</services>
Here is an example of using the generated proxy:
api = new MyProxyService.MyProxyServiceClient();
api.ClientCredentials.UserName.UserName = userAcct;
api.ClientCredentials.UserName.Password = password;
api.MethodCall();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SDL - about character movement I want to ask about character movement in SDL
from lazyfoo.com, There is a tutorial which explains about movements and from what I read, I conclude that these are the steps to object movements
*
*Events detected
*set new coordinates based on events
*make the screen white (SDL_FillRect())
*Then draw the object with new coords (applySurface())
My problem is that I'm using a 2D tile-based map (not a white surface) and I'm troubled at step no 3.... how to maintain the map while moving the character ??(without whitening the screen)
I'll appreciate it greatly if someone can post the codes
THX
A: You want to change position of the player without having to redraw the map?
Unless your map is really complex, you should be able to redraw it every frame.
If it is that complex or you are on slow machine, you can do the following optimization:
At the beginning of the program draw the map to separate surface.
Every frame, instead of clearing the screen and redrawing the map, just copy this surface to the screen. Copying surfaces is almost as fast as clearing them.
A: What you could do is instead of making the screen white, outside of the main while loop you BlitScreen or FillRect with your map instead of doing it every frame. Also, to save memory you could try limiting FPS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to ask permission programmatically? Is there any way to ask permission programmatically in android ? I don't want to add all permission to AndroidManifest.xml. So is there any dialog that asks for permission at runtime?
A: Not until now, but yes.
According to Google's new permission model introduced in Android M:
If an app running on the M Preview supports the new permissions model, the user does not have to grant any permissions when they install or upgrade the app. Instead, the app requests permissions as it needs them, and the system shows a dialog to the user asking for the permission.
Here's a summary of the key components of this new model:
*
*Declaring Permissions:
The app declares all the permissions it needs in the manifest, as in
earlier Android platforms.
*Permission Groups: Permissions are divided into permission groups, based on their functionality. For example, the CONTACTS permission group contains permissions to read and write the user's contacts and profile information.
*Limited Permissions Granted at Install Time: When the user installs or updates the app, the system grants the app all permissions listed in the manifest that fall under PROTECTION_NORMAL. For example, alarm clock and internet permissions fall under PROTECTION_NORMAL, so they are automatically granted at install time. For more information about how normal permissions are handled, see Normal Permissions.
The system may also grant the app signature permissions, as described in System components and signature permissions. The user is not prompted to grant any permissions at install time.
*User Grants Permissions at Run-Time: When the app requests a permission, the system shows a dialog to the user, then calls the app's callback function to notify it whether the user granted the permission.
This permission model changes the way your app behaves for features that require permissions. Here's a summary of the development practices you should follow to adjust to this model:
*Always Check for Permissions: When the app needs to perform any action that requires a permission, it should first check whether it has that permission already. If it does not, it requests to be granted that permission. You do not need to check for permissions that fall under PROTECTION_NORMAL.
*Handle Lack of Permissions Gracefully: If the app is not granted an appropriate permission, it should handle the failure cleanly. For example, if the permission is just needed for an added feature, the app can disable that feature. If the permission is essential for the app to function, the app might disable all its functionality and inform the user that they need to grant that permission.
*Permissions are Revocable: Users can revoke an app's permissions at any time. If a user turns off an app's permissions, the app is not notified. Once again, your app should verify that it has needed permissions before performing any restricted actions.
Source: https://developer.android.com/preview/features/runtime-permissions.html
A: No.
Answer here: get Android permission dynamiclly
See the "Uses Permissions" section here:
http://developer.android.com/guide/topics/security/security.html
A: No. The user needs to be informed about the permissions while installing the application. Asking the user at runtime would be a security risk.
A: Android M introduced Runtime permissions, which everyone has been waiting for. Also the permissions are now categorized into NORMAL and DANGEROUS, where NORMAL permissions are granted by default and DANGEROUS permissions are requested when they are needed. Also DANGEROUS permissions can be revoked by the user at any time from the device's Settings menu.
A:
Applications statically declare the permissions they require, and the Android system prompts the user for consent at the time the application is installed. Android has no mechanism for granting permissions dynamically (at run-time) because it complicates the user experience to the detriment of security.
*
*Android Developer site - System Permissions
A: If I combine the answers from 'Piskvor' and from 'Hanno Binder', your app can check if the helper app is available (try to invoke it with an Intent), and if it is not there (the invocation fails), prompt the user to install it.
Look at the following, for example.
how to download adobe reader programatically if not exists
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: How to setHighlightedTextColor @ NSAttributedString I have a custom UITableViewCell which uses a NSAttributedString. I want it to change color when the cell is selected. How can I make the NSAttributedString have the same behavior as a UILabel with highlightedTextColor set?
I have tried to change the color at the functions setSelected and setHighlighted of the cell, but it seems that they are called to late (on touchUpInside instead of touchDown)
Thanks in advance!
A: UILabel subclass solution
@implementation CustomLabelHighlighted
{
NSAttributedString *savedAttributedString;
}
-(void)setHighlighted:(BOOL)highlighted
{
[super setHighlighted:highlighted];
if (!highlighted)
{
[super setAttributedText:savedAttributedString];
return;
}
NSMutableAttributedString *highAttributedString = [savedAttributedString mutableCopy];
NSRange range = NSMakeRange(0, highAttributedString.string.length);
[highAttributedString addAttribute:NSForegroundColorAttributeName value:self.highlightedTextColor range:range];
[super setAttributedText:highAttributedString];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
savedAttributedString = attributedText;
}
@end
A: Typically it's pretty simple to detect selection/highlighting and change colors depending on it. The important methods are:
-(void)setHighlighted:animated:
-(void)setSelected:animated:
note that when overriding you have to use the methods with animated:, otherwise it won't work.
When you want to change only the color, the simplest solution is to let the color to be set on the label and not on the string. Note that the attributed string is still inheriting all the properties of the UILabel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can you tell if a suggestion was selected from JQuery UI Autocomplete I have a text box that is wired to JQuery UI Autocomplete. As the user types in the box my search runs via an ajax call and returns suggestions. It seems that three things can happen:
*
*The autocomplete suggests options and the user selects one of them
*The autocomplete suggests options but the user chooses to select none of them
*The autocomplete can not make a suggestion - no match (so the list of suggestions do not display)
Dealing with all of the scenarios above, how can I tell if the user selects an option from the autocomplete?
I have looked into marking a flag when a search commences (match=false) and a select occurs (match=true) but this doesn't seem a very neat way of doing things.
A: When a user selects an option, the 'select' event is fired. You can listen to it and set a flag.
(function() {
var optionSelected = false;
$( ".selector" ).autocomplete({
select: function(event, ui) { optionSelected = true; }
});
})();
A: You can use the select event like @bfavaretto points out, but I think in this situation it's more convenient to use the change event:
$("#auto").autocomplete({
source: ['hi', 'bye', 'foo', 'bar'],
change: function(event, ui) {
if (ui.item) {
$("span").text(ui.item.value);
} else {
$("span").text("user picked new value");
}
}
});
Example: http://jsfiddle.net/andrewwhitaker/3FX2n/
change fires when the field is blurred, but unlike the native change event, you get information about whether or not the user clicked an event (ui.item is null if the user did not click a suggestion).
A: jQueryUI provides a select event, you should define it in the autocomplete options (when you apply the autocomplete to your form input).
For example (from the docs):
$( ".selector" ).autocomplete({
select: function(event, ui) { ... }
});
You can access the selected item via ui.item from inside the event handler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Insert blank row between groups of rows and sorted by ID in sql I have a table which has the following columns and values
ID TYPE NAME
1 MAJOR RAM
2 MAJOR SHYAM
3 MAJOR BHOLE
4 MAJOR NATHA
5 MINOR JOHN
6 MINOR SMITH
My requirement is to right a stored procedure (or SQL query) which would return the same resultset except that there will be blank line after the TYPE changes from one type to another type (major, minor).
MAJOR RAM
MAJOR SHYAM
MAJOR BHOLE
MAJOR NATHA
MINOR JOHN
MINOR SMITH
While i use this query for adding blank line but it is not sorted by basis of ID
select TYPE, NAME from (
select
TYPE as P1,
1 as P2,
ID,
TYPE,
NAME
from EMP
union all
select distinct
TYPE,
2,
'',
'',
N''
from EMP
) Report
order by P1, P2
go
How i sort data by ID
Thanks in advance
A: Yes, yes, don't do this, but here's the query to do it, assuming SQL Server 2008 R2. Other versions/rdbms you can achieve same functionality by writing two separate queries unioned together.
Query
; WITH DEMO (id, [type], [name]) AS
(
SELECT 1,'MAJOR','RAM'
UNION ALL SELECT 2,'MAJOR','SHYAM'
UNION ALL SELECT 3,'MAJOR','BHOLE'
UNION ALL SELECT 4,'MAJOR','NATHA'
UNION ALL SELECT 5,'MINOR','JOHN'
UNION ALL SELECT 6,'MINOR','SMITH'
)
, GROUPED AS
(
SELECT
D.[type]
, D.[name]
, ROW_NUMBER() OVER (ORDER BY D.[type] ASC, D.[name] DESC) AS order_key
FROM
DEMO D
GROUP BY
--grouping sets introduced with SQL Server 2008 R2
-- http://msdn.microsoft.com/en-us/library/bb510427.aspx
GROUPING SETS
(
[type]
, ([type], [name])
)
)
SELECT
CASE WHEN G.[name] IS NULL THEN NULL ELSE G.[type] END AS [type]
, G.[name]
FROM
GROUPED G
ORDER BY
G.order_key
Results
If you don't like the nulls, use coalsece to make empty strings
type name
MAJOR SHYAM
MAJOR RAM
MAJOR NATHA
MAJOR BHOLE
NULL NULL
MINOR SMITH
MINOR JOHN
NULL NULL
A: I agree with billinkc.
In a sequential mind, like mine, it can occur different.
The approach is to use a cursor and insert the records into a temp table.
This table can have a column, INT type, lets say it is called "POSITION" which increments with every insert.
Check for ID changes, and add the empty row everytime it does.
Finally make the SELECT order by "POSITION".
My context was:
An interface that dinamically adjust to what the user needs, one of the screens shows a payment table, grouped by provider with the approach early mentioned.
I decided to manage this from database and skip maintainance for the screen at client side because every provider has different payment terms.
Hope this helps, and lets keep an open mind, avoid saying "don't do this" or "this is not what SQL was designed for"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQLite: Current date plus one day in where clause I need to get 3 queries on an 'appointment' table.
*
*where appointment.start_date is today,
*where appointment.start_date = today+1 day, and
*where appointment.start_date is > today+1 day.
I've got 1. down fine.
var resultSet = conn.execute('SELECT * FROM appointments WHERE date() = date(start_date)');
For 2., I've tried this:
var resultSet = conn.execute('SELECT * FROM appointments WHERE date("now", "+1day") = date(start_date, "+1day")');
I got date('now', '+1day') from this link this link but it returns the same results as the first query.
Can someone help with these queries?
A: If you're using exactly what's posted, I'd say you have a spacing problem
SQLite uses '+1 day' and you have posted '+1day'
Barring any explicit error messages, with the space it should work
A: I'm not sure for SQLite, but try next code:
var now = new Date();
var nowStr = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate();
var nowPlus1 = new Date(Number(now)+24*60*60*1000);
var nowPlus1Str = nowPlus1.getFullYear()+"-"+(nowPlus1.getMonth()+1)+"-"+nowPlus1.getDate();
var resultSet = conn.execute("SELECT * FROM appointments WHERE start_date = '" + nowStr + "'");
var resultSet = conn.execute("SELECT * FROM appointments WHERE start_date = '" + nowPlus1Str + "'");
var resultSet = conn.execute("SELECT * FROM appointments WHERE start_date > '" + nowPlus1Str + "'");
A: Sorry totally my own idiosity my query was wrong: WHERE date("now", "+1day") = date(start_date, "+1day") should have read WHERE date("now", "+1day") = date(start_date) I had an extra +1 day. Doh!
A: Try with "plus one day" instead of "+1 day". Its not documented, but worked for me in another code.
var resultSet = conn.execute('SELECT * FROM appointments WHERE date("now plus one day") = date(start_date plus one day")');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: glVertexAttribPointer on built-in vertex attributes like gl_Vertex, gl_Normal I have to send vertex attributes using glVertexAttribPointer to shaders expecting them as built-in (gl_Vertex, gl_Color, etc.).
The glVertexAttribPointer function needs to specify the index (or location) of each built-in attribute. I can do it on NVidia implementations since the location of each attribute is fixed (see http://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/attributes.php at the section "Custom attributes), however i'm not sure about the locations in ATI implementation.
Also, the function glGetAttribLocation will return -1 when trying to get the location of any attribute beginning starting with "gl_".
I think i'm missing something and this is a trivial problem, however I have not found the correct solution for ATI.
A: The builtin attribute arrays are not set with glVertexAttribPointer, but with functions like glVertexPointer, glColorPointer, .... And you enable these by calling glEnableClientState with constants like GL_VERTEX_ARRAY, GL_COLOR_ARRAY, ..., instead of glEnableVertexAttribArray.
Whereas on nVidia glVertexAttribPointer might work, due to their aliasing of custom attribute indices with builtin attributes, this is not standard conformant and I'm sure you cannot expect this on any other hardware vendor. So to be sure use glVertexAttribPointer for custom attributes and the glVertexPointer/glNormalPointer/... functions for bultin attributes, together with the matching enable/disable functions.
Keep in mind that the builtin attributes are deprecated anyway, together with the mentioned functions. So if you want to write modern OpenGL code, you should define your own attributes anyway. But maybe you have to support legacy shaders or don't care about forward compatiblity at the moment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to convert and write Large Images without causing an OOM Error? I have images stored in a database in the form of ImageIcons that I would like to serve to our web page, however for large images I am getting out of memory exceptions.
Here is how I currently do it,
[Edit] I expanded my ImageUtilities to provide a non transparent BufferedImage which simplifies the code,
BufferedImage rgbbi = ImageUtilities.toBufferedImage(icon.getImage());
ServletOutputStream out = null;
try {
// Get the Servlets output stream.
out = responseSupplier.get().getOutputStream();
// write image to our piped stream
ImageIO.write(rgbbi, "jpg", out);
} catch (IOException e1) {
logger.severe("Exception writing image: " + e1.getMessage());
} finally {
try {
out.close();
} catch (IOException e) {
logger.info("Error closing output stream, " + e.getMessage());
}
}
The exceptions that are being thrown are the following,
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
at java.awt.image.Raster.createPackedRaster(Raster.java:458)
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1015)
at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:230)
at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:484)
at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:120)
at sun.awt.image.JPEGImageDecoder.sendPixels(JPEGImageDecoder.java:97)
at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
at sun.awt.image.JPEGImageDecoder.produceImage(JPEGImageDecoder.java:119)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:246)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
...
Is there a way I can rewrite this to stream the output of ImageIO.write and limit its buffer size somehow?
[Edit]
I can't just increase the heap size either, the images I need to serve are in the range of 10000x7000 pixels, as a byte array that works out (10000px x 7000px x 24bits) 280MB. I think that is an unreasonable heap size to allocate for image conversion in a servlet.
An example Image Large
A: I am assuming you do not have enough pixels on your your screen to display a complete image. As you seem to need an uncompressed version of it in RAM for the display, you will need exactly as much heap as the image size implies. Having said that, there are many better ways.
I wrote my bachelor thesis on efficiently displaying multiple large images with up to 40000x40000 px simultaneously. We ended up implementing an LOD with a multilevel cache. Meaning the image was resized and each size was chopped up into square chunks, resulting in an image pyramid. We had to expariment a bit to find an optimal chunk size. It varies from system to system but may be safely assumed to be somewhere between 64x64 and 256x256 px.
Next thing was to implement a scheduling algorithm for uploading the right chuncks in order to keep the ratio of 1:1 of texel:pixel. To achieve better quality, we used trilinear interpolation between the slices of the pyramid.
The "multilevel" means that image chunks were uploaded to the VRAM of the graphics card with RAM as the L1 cach and the HD as the L2 cache (provided the image is on the network), but this optimisation might be excessive in your case.
All in all, this is lots of things to consider, while you were just asking for memory control. If this is a major project though, implementing an LOD is the right tool for the job.
A: As pointed out in the comments, to store 10000x7000 images in a database, as ImageIcons, and serve them through a servlet, smells as bad design.
Nevertheless, I point out this PNGJ library (disclaimer: I coded it) that allows you read/write images in PNG sequentially, line by line. Of course, this would only be useful if you store your big images in that format.
A: You're not going to be able to do this using the inbuilt classes like you're using, since they're designed to work on bitmaps wholesale. You might be better off running these out of java via something like Image Magick (or whatever it is these days).
Do you just need to do this once?
You might be stuck having to write all this yourself, loading the file, processing the "pixels" and writing it out. That would be the BEST way to do it, rather than loading the entire thing, converting (i.e. copying) it, and writing it out. I don't know if things like Image Magick work on streams or memory images.
Addenda for AlexR:
To do this PROPERLY, he needs to decode the file in to some streamable format. For example, JPEG divides images in to 8x8 blocks, compresses them individually, then it streams those blocks out. While it is streaming the blocks out, the blocks themselves are compressed (so if you had 10 black blocks, you get like 1 black block with a count of 10).
A raw bit map is little more than blocks of bytes, for high color spaces with alpha, it's 4 bytes (one each for Red, Green, Blue, and Alpha). Most colorspace conversions happen at the pixel level. Other more sophisticated filters work on the pixel and surrounding pixels (Gaussian blur is a simple example).
For simplicity, especially with lots of different formats, it's easier to "load the whole image" in to memory, work on its raw bit map, copy that bit map while converting it, then write the raw image back out in whatever format (say, converting a color JPEG to a Gray Scale PNG).
For large images, as what this person is dealing with, it happens to be VERY expensive with memory.
So, OPTIMALLY, he'd write specific code to read the file in portions, that is stream it in, convert each little bit, and stream it back out again. This would take very little memory, but he'd likely have to do most of the work himself.
So, yes, he can "just read the image byte-by-byte", but the processing and algorithms will likely be rather involved.
A: More memory seems to be the only answer for conversion without me having to write my own.
My solution was then to just not convert the images and use the method described in this answer to retrieve the image mime type to be able to set the header.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to filter lines without Sobel filter in OpenCV I'm trying to detect lines just with linear filters. My first try was rotate a kernel like this but wouldn't work:
kernel = zeros((13,13))
kernel60 = zeros((13,13))
kernel[4] = [0,0,0,0,-1,-1,-1,-1,-1,0,0,0,0]
#kernel[5] = [0,0,0,0,0]
kernel[6] = [0,0,0,0,2,2,2,2,2,0,0,0,0]
#kernel[7] = [0,0,0,0,0]
kernel[8] = [0,0,0,0,-1,-1,-1,-1,-1,0,0,0,0]
rotate60 = zeros((2,3))
GetRotationMatrix2D((6,6),60,1, rotate60)
WarpAffine(kernel,kernel60,rotate60,CV_WARP_FILL_OUTLIERS, ScalarAll(0))
After that I prepared a kernel that's a linear combination from two Sobel kernels (steerable filters). This works but I would better like a non-sobel kernel, similar to the first try. Any alternative to the sobel kernels?
Sobel Kernel combination:
kernel_x[0] = [-1,0,+1]
kernel_x[1] = [-1,0,+1]
kernel_x[2] = [-1,0,+1]
kernel_y[0] = [-1,-1,-1]
kernel_y[1] = [0,0,0]
kernel_y[2] = [+1,+1,+1]
normal_theta = radians(-30)
kernel = multiply(cos(theta),kernel_x) + multiply(sin(theta),kernel_y)
Then filtering:
Filter2D(src,dst,kernel)
I use Python and numpy in a Windows machine.
A: You can use Canny algorithm for edge detection (which uses Sobel anyway) and Hough transform for line detection. Performing blur before Canny can help eliminate outlier lines. This is the classic approach. You can use OpenCV that implements both parts.
See the following:
http://en.wikipedia.org/wiki/Hough_transform
http://en.wikipedia.org/wiki/Canny_edge_detector
Here is the documentation for OpenCV implementation:
http://opencv.willowgarage.com/documentation/cpp/imgproc_feature_detection.html
see the cvHoughLines* functions there are sample code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set cookie to the WebBrowser control only I have a webbrowser control with flash video player inside. I want to set a cookie to the webbrowser control so I can play forbidden videos (that need this cookie). I don't want to set the cookie globally and affect IE's cookies. I tried with webBrowser.Document.Cookie, but nothing happened. Still forbidden. What to do?
A: You could try using the Navigate function and add aditional headers
webBrowser1.Navigate("http://www.google.com", "", NULL, "Cookie :" + yourCookie + Environment.NewLine);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: GitHub - Private vs Public Collaborators New to GitHub and a bit confused by private vs public collaborators.
If I do a Micro account with one private collaborator but have 5 total team members wanting to contribute, how would the remaining four apply? I see it has unlimited public collaborators.
So what is the difference between Private vs Public Collaborators on GitHub?
A: If you have private repository and 5 collaborators, you need something bigger than Micro plan. For all private repositories you manually select collaborators in the admins tools of your repository, as you have micro plan, you can add only one collaborators to your private repository.
In other case if you have public repository, it doesn't meter which account you have, everybody can fork and contribute to your project.
A: The other team members can create free accounts. "5 private collaborators" means that you can add up to 5 of them to a private project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cake: habtm relationship with not-default key on other model I have 2 models that need to be linked by a habtm relationship, having this table-structure:
CATEGORIES:
id | name | ..
-----------------------
1 | test | ..
POSTS:
id | name | other_id | ..
---------------------------------
1 | test | 5 | ..
CATEGORIES_POSTS:
id | category_id | other_id
--------------------------------
1 | 1 | 5
I need to get the posts from the category side, but don't seem to be able to set the habtm relation correctly. The important thing, that I didn't mention so far, is that the id used in the Post-model is not id but other_id. This is what I tried so far (all in the Category-model):
*
*set the associationForeignKey to 'other_id'
in the sql-query it has: CategoriesPost.other_id = Post.id fragment -> wrong relation (should be CategoriesPost.other_id = Post.other_id
*set the associationForeignKey to false and add a condition CategoriesPost.other_id = Post.other_id
now the sql fragment is CategoriesPost. = Post.id --> sql error
*set the associationForeignKey to CategoriesPost.other_id = Post.other_id
well .. this is an error as well, as Cake takes the input as 1 field: CategoriesPost.other_id = Post.other_id = Post.id
I know I could achieve to relation through 2 hasMany links, but that gives me a lot of queries instead of 1
Thanks in advance!
A: Cake can't customise the primary key to use on the join when doing a normal find.
You could use a custom join, if you really want: http://book.cakephp.org/view/1047/Joining-tables
Why exactly do you need two ids? You are trying to join a post to a category, the ids will be unique anyway; as far as relating the two, the primary should work just fine.
A: just change the post model primaryKey on the fly for some operations you need to....
To do so, just need to do $this->primaryKey = 'other_id' OR in a controller $this->Post->primaryKey= 'other_id'
that would do the trick.
But remember, if you are retrieving data from all associations and you have more associations than this one then the other associations if they use Post.id are going to fail since primary key is Post.other_id
you should do a find function in your post models for when you are using this union, something like this:
function otherFind ($type, $options){
$this->primaryKey = 'other_id';
$result = $this->find($type, $options);
$this->primaryKey = 'id';
return $result;
}
if you need to join it with other models gets a little more tricky i will recommend to use joins for that (try looking at the linkable bhaviour code to see how)
I strongly suggest to use only ONE primary key since it's not really helpfull a second one. A primary key should be unique anyway and you can associate anything with just one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to search for words containg certain letters in a txt file with Python? Look at the code below. This finds the letter 'b' containing in the text file and prints all the words containing the letter 'b' right?
x = open("text file", "r")
for line in x:
if "b" and in line: print line
searchfile.close()
Now here is my problem. I would like to search with not only one, but several letters.
Like, a and b both has to be in the same word.
And then print the list of words containing both letters.
And I'd like to have the user decide what the letters should be.
How do I do that?
Now I've come up with something new. After reading an answer.
x = open("text file", "r")
for line in x:
if "b" in line and "c" in line and "r" in line: print line
Would this work instead?
And how do I make the user enter the letters?
A: No, your code (apart from the fact that it's syntactically incorrect), will print every line that has a "b", not the words.
In order to do what you want to do, we need more information about the text file. Suppossing words are separated by single spaces, you could do something like this
x = open("file", "r")
words = [w for w in x.read().split() if "a" in w or "b" in w]
A: You could use sets for this:
letters = set(('l','e'))
for line in open('file'):
if letters <= set(line):
print line
In the above,letters <= set(line) tests whether every element of letters is present in the set consisting of the unique letters of line.
A: x = open("text file", "r")
letters = raw_input('Enter the letters to match') # "ro" would match "copper" and "word"
letters = letters.lower()
for line in x:
for word in line.split()
if all(l in word.lower() for l in letters): # could optimize with sets if needed
print word
A: First you need to split the contents of the file into a list of words. To do this you need to split it on line-breaks and on spaces, possibly hypens too, I don't really know. You might want to use re.split depending on how complicated the requirements are. But for this examples lets just go:
words = []
with open('file.txt', 'r') as f:
for line in f:
words += line.split(' ')
Now it will help efficiency if we only have to scan words once and presumably you only want a word to appear once in the final list anyway, so we cast this list as a set
words = set(words)
Then to get only those selected_words containing all of the letters in some other iterable letters:
selected_words = [word for word in words if
[letter for letter in letters if letter in word] == letters]
I think that should work. Any thoughts on efficiency? I don't know the details of how those list comprehensions run.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python - single vs multiline REGEX Considering the following text pattern,
#goals: the process report timestamp, eg. 2011-09-21 15:45:00 and the first two stats in succ. statistics line, eg: 1438 1439
input_text = '''
# Process_Name ( 23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\n
some line 1\n
some line 2\n
some other lines\n
succ. statistics | 1438 1439 99 | 3782245 3797376 99 |\n
some lines\n
Process_Name ( 23387) Report at 2011-09-21 15:50:00.001 Type: Periodic #\n
some line 1\n
some line 2\n
some other lines\n
succ. statistics | 1436 1440 99 | 3782459 3797523 99 |\n
repeat the pattern several hundred times...
'''
I got it working when iterating line to line,
def parse_file(file_handler, patterns):
results = []
for line in file_handler:
for key in patterns.iterkeys():
result = re.match(patterns[key], line)
if result:
results.append( result )
return results
patterns = {
'report_date_time': re.compile('^# Process_Name\s*\(\s*\d+\) Report at (.*)\.[0-9] {3}\s+Type:\s*Periodic\s*#\s*.*$'),
'serv_term_stats': re.compile('^succ. statistics \|\s+(\d+)\s+ (\d+)+\s+\d+\s+\|\s+\d+\s+\d+\s+\d+\s+\|\s*$'),
}
results = parse_file(fh, patterns)
returning
[('2011-09-21 15:40:00',),
('1425', '1428'),
('2011-09-21 15:45:00',),
('1438', '1439')]
but having a list of tuples output as my goal,
[('2011-09-21 15:40:00','1425', '1428'),
('2011-09-21 15:45:00', '1438', '1439')]
I tried several combos with the initial patterns and a lazy quantifier between them but can't figure out how to capture the patterns using a multiline REGEX
# .+? Lazy quantifier "match as few characters as possible (all characters allowed) until reaching the next expression"
pattern = '# Process_Name\s*\(\s*\d+\) Report at (.*)\.[0-9]{3}\s+Type:\s*Periodic.*?succ. statistics) \|\s+(\d+)\s+(\d+)+\s+\d+\s+\|\s+\d+\s+\d+\s+\d+\s+\|\s'
regex = re.compile(pattern, flags=re.MULTILINE)
data = file_handler.read()
for match in regex.finditer(data):
results = match.groups()
How can I accomplish this ?
A: Use re.DOTALL so . will match any character, including newlines:
import re
data = '''
# Process_Name ( 23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\n
some line 1\n
some line 2\n
some other lines\n
succ. statistics | 1438 1439 99 | 3782245 3797376 99 |\n
some lines\n
repeat the pattern several hundred times...
'''
pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*?succ. statistics\s+\|\s+(\d+)\s+(\d+)'
regex = re.compile(pattern, flags=re.MULTILINE|re.DOTALL)
for match in regex.finditer(data):
results = match.groups()
print(results)
# ('2011-09-21', '1438', '1439')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Fetch data from a website after login, client side I would like to import data that the user had entered into his profile on a website that I do not control. I don't want the user to hand me his login credentials to grab the data from the server-side (connecting directly to aforementioned website). I would rather prefer the login data to stay on the client's machine: It makes my service more trustworthy and I don't have to process sensitive data.
I thought that this can probably done with javascript without greater hassle. However, given the security risks, it seems to be blocked by browsers. See How to get data with JavaScript from another server?
So I think my question is already answered and can be closed/deleted.
A: I'm not sure I understand what you're trying to do, but there is no secure way to verify login credentials in a browser client. If you want to check login credentials, you will have to involve a server.
Some data can be stored on the client side, but then a user is tied to a particular browser on a particular computer and can't use the service from anywhere else. In older browsers data is generally limited to what can be stored in a cookie and cookies are not guaranteed to survive for any particular long lasting time frame. In the latest browsers, data can be stored in HTML5 local storage which allows for a little more structured way of storing data, but even then you're still stuck in one particular browser on one particular computer.
Based on your comments, it sounds you're trying to "cache" a copy of the data from web-site A that you can access from client-side code on web-site B on multiple visits to your website. If that's the case, then it sounds like HTML5 local storage may work to serve as a cache storage mechanism. You will have to figure out how to get the data from web-site A into the cache as the cache will be subject to same-origin access (domain X can only access the data that was put into HTML5 local storage by domain X), but if you can get manage to get the data from web-site A into your web-site B client-side page (perhaps using JSONP), then you could cache it using HTML5 local storage. You will need to realize that even HTML5 local storage is not guaranteed forever (so you need to be able to fetch it again from web-site A if required).
A: You said this
I don't want the user to hand me his login credentials to grab the
data from the server-side (connecting directly to aforementioned
website).
If you do that, anyone would be able to access any User's data, since you don't restrict access to data.
You also said this
I would rather prefer the login data to stay on the client's machine:
It makes my service more trustworthy and I don't have to process
sensitive data.
I'm really not sure that's a good idea. You still need to lock down personal information. But anyway, if you really want to, you can use localstorage -- modern webbrowsers support this.
Check out this link for a primer on local storage.
Storing Objects in HTML5 localStorage
Note that the user can clear the browsers local storage, so you still need to have a form to enter credentials.
EDIT -- if you want to save a user's profile information on the client, you can do that with local storage. But you still need to save the data to the server, else if the user goes to a different machine or even browser, they won't have their data. Plus, your server side model probably needs to associate a user's content with their profile in some way. I don't think there is any way around it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access one object from another form in C#? Let's say I have "Form1" and "Form2", both are forms.
In Form1 there are the Main Class and the Main method.
In Form1 I create an object like:
public myobject ob1 = new myobject();
But then, in Form2, I have this code:
private void bdCancelar_Click(object sender, EventArgs e)
{
ob1.status = 1; // I can't access ob1 !!!
}
Any help ?
Thanks.
A: You need an instance of Form1. Normally if you have displayed this form you have instantiated it (Form1 form1 = new Form1()). Then you could operate on this instance and access public members:
form1.ob1.status = 1;
Another possibility is to have your Form2 constructor take a Form1 instance:
public class Form2: Form
{
private readonly Form1 _form1;
public Form2(Form1 form1)
{
_form1 = form1;
}
private void bdCancelar_Click(object sender, EventArgs e)
{
_form1.ob1.status = 1;
}
}
and then when you are somewhere inside Form1 and want to create and show Form2:
var form2 = new Form2(this);
form2.ShowDialog();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Set path of the radiobutton in jsp form I am using spring aplication 2.5. I have a list of the radio buttons displayed using list of the objects on the jsp. I want to set the path of the radiobuttons to its respective
objects in the list.
<form:form commandName = "artifact" name="formradioquest">
<c:forEach var="questionArtifact" items="${artifact.questionGroupDetails}">
<c:forEach var="answerOption" items="${questionArtifact.question.answerOptions}">
<form:radiobutton path="choosenAnswers" value="${answerOption}" label="${answerOption.answerText}" cssClass="styled"/>
</c:forEach>
</c:forEach>
.
.
</form:form>
public class Artifact{
List<questionGroupDetails> questionGroupDetails;
.
.
}
public class questionGroupDetails{
Question question;
AnswerOption choosenAnswers;
.
.
}
public class Question{
List<AnswerOption> answerOptions;
.
.
}
How can I set the path variable of the radio buttons to the 'choosenAnswers' variable in QuestionGroupDetails class. Because when I use this code, it actually expects 'choosenAnswers' variable in Artifact. Please help.
A: You can use the varStatus property of the <for:each ... /> tag to get the current loop index.
<c:forEach var="questionArtifact" items="${artifact.questionGroupDetails}" varStatus="row">
<c:forEach var="answerOption" items="${questionArtifact.question.answerOptions}">
<form:radiobutton path="choosenAnswers[${row.index}]" value="${answerOption}" label="${answerOption.answerText}" cssClass="styled"/>
</c:forEach>
</c:forEach>
The path property resolves this to choosenAnswers.get(row.getIndex()).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: grep: one pattern works but not the other I have a teb-delimited file that has gene names in one column and expression values for these genes in the other. I want to delete certain genes from this file using grep. So, this:
"42261" "SNHG7" "20.2678"
"42262" "SNHG8" "25.3981"
"42263" "SNHG9" "0.488534"
"42264" "SNIP1" "7.35454"
"42265" "SNN" "2.05365"
"42266" "snoMBII-202" "0"
"42267" "snoMBII-202" "0"
"42268" "snoMe28S-Am2634" "0"
"42269" "snoMe28S-Am2634" "0"
"42270" "snoR26" "0"
"42271" "SNORA1" "0"
"42272" "SNORA1" "0"
becomes this:
"42261" "SNHG7" "20.2678"
"42262" "SNHG8" "25.3981"
"42263" "SNHG9" "0.488534"
"42264" "SNIP1" "7.35454"
"42265" "SNN" "2.05365"
I've used the following command that i've put together with my limited terminal knowledge:
grep -iv sno* <input.text> | grep -iv rp* | grep -iv U6* | grep -iv 7SK* > <output.txt>
So with this command, my output file lacks genes that start with sno, u6 and 7sk but somehow grep has deleted all the genes that has "r" in them instead of the ones that start with "rp". I'm very confused about this. Any ideas why sno* works but rp* not?
Thanks!
A: Although this doesn't directly answer your question, there is one thing in your sample command line that you may want to be careful with: Whenever you use a special shell metacharacter (like "*"), you need to escape or quote it. So your command line should look more like:
grep -iv 'sno*' <input.text> | grep -iv 'rp*' | grep -iv 'U6*' | grep -iv '7SK*' > <output.txt>
Often, shells are smart, and if no files match the glob, they will use the text as-is (so if you enter "foo*" but there are no filenames starting with "foo", then the string "foo*" will be passed to the command).
A: grep -iEv "sno|rp|U6|7SK" yourInput
test:
kent$ cat b
"42261" "SNHG7" "20.2678"
"42262" "SNHG8" "25.3981"
"42263" "SNHG9" "0.488534"
"42264" "SNIP1" "7.35454"
"42265" "SNN" "2.05365"
"42266" "snoMBII-202" "0"
"42267" "snoMBII-202" "0"
"42268" "snoMe28S-Am2634" "0"
"42269" "snoMe28S-Am2634" "0"
"42270" "snoR26" "0"
"42271" "SNORA1" "0"
"42272" "SNORA1" "0"
kent$ grep -iEv "sno|rp|U6|7SK" b
"42261" "SNHG7" "20.2678"
"42262" "SNHG8" "25.3981"
"42263" "SNHG9" "0.488534"
"42264" "SNIP1" "7.35454"
"42265" "SNN" "2.05365"
A: The grep command uses regular expressions, not globbing patterns.
The pattern rp* means "'r' followed by zero or more 'p'". What you really want is rp.*, or even better, "rp.* (or even just "rp, there's no point in trying to grep for anything after the "rp" after all). Likewise, sno* means "'sn' followed by zero or more 'o'". Again, you'd want sno.* or "sno.* (or even just "sno).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I enable reverse debugging on a multi-threaded program? I'm trying to use the reverse debugging features of gdb 7.3.1 on a multi-threaded project (using libevent), but I get the following error:
(gdb) reverse-step
Target multi-thread does not support this command.
From this question, I thought perhaps that it was an issue loading libthread_db but, when I run the program, gdb says:
Starting program: /home/robb/slug/slug
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/libthread_db.so.1".
How can I enable reverse debugging with gdb 7.3.1 on a multi-threaded project? Is it possible?
A: To do this, you need to activate the instruction-recording target, by executing the command
record
from the point where you want to go forward and backward (remember that the recording will significantly slow down the execution, especially if you have several threads!)
I've just checked that it's working correctly:
(gdb) info threads
Id Target Id Frame
2 Thread 0x7ffff7860700 (LWP 5503) "a.out" hello (arg=0x601030) at test2.c:16
* 1 Thread 0x7ffff7fca700 (LWP 5502) "a.out" main (argc=2, argv=0x7fffffffe2e8) at test2.c:47
...
(gdb) next
49 p[i].id=i;
(gdb) reverse-next
47 for (i=0; i<n; i++)
...
17 printf("Hello from node %d\n", p->id);
(gdb) next
Hello from node 1
18 return (NULL);
(gdb) reverse-next
17 printf("Hello from node %d\n", p->id);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: Extjs 4.0 MVC - how to close a view from within the controller? I have a simple example here with a modal window that is a 'view'. I want to have a button within the window that does a window close, so the lazy user doesn't need to click the 'X' in top right.
My problem is I don't know how to reference the view from within the controller. In the non-MVC world I would just do a 'window.close()' in the button handler. Any ideas? Thanks!
View
Ext.define('AM.view.testwindow.window', {
extend: 'Ext.window.Window',
alias: 'widget.TESTwindow',
title: 'TEST Window',
layout: 'border',
width: 1000, height: 400,
minimizable: true,
maximizable: true,
closeAction: 'destroy',
initComponent: function () {
this.items = [
{xtype: 'gridpanel', region: 'center', // grid in the window
store: 'Equipments',
columns: [
{ text: 'Equip ID', dataIndex: 'EquipmentID' }
, { text: 'StationID', dataIndex: 'StationID' }
],
dockedItems: [{
xtype: 'toolbar', // Grid's toolbar
items: [
{
xtype: 'button', /* Close button to close the window */
text: 'Close Window',
itemId: 'btnTestClose'
}
]
}
]
}
];
this.callParent(arguments);
}
});
Controller
Ext.define('AM.controller.testwindow', {
extend: 'Ext.app.Controller',
stores: ['Equipments', 'Stations'],
models: ['Equipment'],
views: ['testwindow.window', 'testwindow.Grid'],
refs: [
{ ref: 'TESTgrid', selector: 'TESTgrid' },
{ ref: 'testwindow', selector: 'testwindow' }
],
init: function () {
this.control(
{
'#btnTestClose': {
click: function (butt, e, options) {
alert('close handler!');
this.getTestwindowWindowView().close(); // this fails. What should I do? ComponentQuery ?
}
}
}
)
}
}
);
Scope of 'this' from within Button handler
A: Your ref to the test window should match the alias TESTwindow (without the widget part), or maybe the long name testwindow.window:
refs: [
{ ref: 'TESTgrid', selector: 'TESTgrid' },
{ ref: 'TESTwindow', selector: 'testwindow' }
],
This will give you the autogenerated getter you need:
this.getTestwindow().close();
Getters are composed of get plus the reference selector with uppercase first letter.
A: refs: [
{ ref: 'TESTgrid', selector: 'TESTgrid' },
{ ref: 'win', selector: 'testwindow' }
],
Try this
this.getWin().close();
ready ok
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php sort() on array produces wrong result I want to sort an array that looks like this (to numerical order instead of 1, 10, 11):
Array ( [0] => 1.jpg [1] => 10.jpg [2] => 11.jpg [3] => 111.jpg [4] => 12.jpg [5] => 12a.jpg [6] => 13.jpg [7] => 14.jpg [8] => 15.jpg [9] => 16.jpg [10] => 2.jpg [11] => 3.jpg [12] => 4.jpg [13] => 5.jpg [14] => 6.jpg [15] => 7.jpg [16] => 8.jpg [17] => 9.jpg )
when i use sort() it just becomes "1" instead of a sorted array.
code:
$this->pageLinks = sort($this->pageLinks); // the array is a property in a class
print_r($this->pageLinks); // want to display the sorted array here but it just returns 1
A: The array is passed to the sort function by reference, so you don't need to do the assignment. Furthermore, the sort() function does not return the sorted array; it returns a success or failure flag, which is why you're getting a 1 in the variable (because the sort was successful).
The first line of your code therefore only needs to look like this:
sort($this->pageLinks);
Secondly, the sort() function will sort in alphabetical order by default. It is possible to get it to sort in numerical sequence by passing SORT_NUMERIC as a second parameter. Given the way PHP casts strings to integers, this might just work for you in your case, but since your values aren't strictly numbers, you may find that you need to do the conversion manually.
If this is the case, then you will need to use usort() instead of sort(), and define the sorting function yourself, where you compare two values and return the sort order. See the manual page for usort() for more info on how this works.
A: sort() sorts the array in-place. Don't re-assign it.
Correct:
sort($this->pageLinks);
Incorrect:
$this->pageLinks = sort($this->pageLinks);
A: You should read the manual on sort(), you give it a reference for an array, and it'll work on it. No need to reassign it.
sort($array);
and not
$array = sort($array);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Weird Error "Call to a member function move() on a non-object" In Symfony2 I'm adding a file upload function to my form in Symfony2. I've followed the documentation here, but I keep getting the following error:
Fatal error: Call to a member function move() on a non-object
The thing is, the line of code it refers to is this:
$this->file->move($this->getUploadRootDir(), $this->file->getClientOriginalName());
This is a line of code that I took from the documentation. I'm not entirely sure why it's moaning about the move() though. I have checked to see if I'm missing any files but I'm not.
Do I have to create a reference to this? Or am I missing a file?
Cheers
EDIT:
I have added the following code to the beginning of the upload() function:
// the file property can be empty if the field is not required
if (null === $this->file) {
return;
}
However, I have now been given the following errors:
1/2: Exception: Serialization of
'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
and
2/2: Exception:
Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector::serialize()
must return a string or NULL
I don't know if what I've done has fixed the previous error as I have now been presented with these errors.
A: You cannot persit the file property, you need 2 properties in your entity, one to hold the UploadedFile and another one to hold the filename (which is persisted).
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* @Assert\File(maxSize="6000000")
*/
public $file;
You add only the $file property to your form.
A: Add function
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload() {
if (null !== $this->file) {
$this->path = $this->file->getClientOriginalName();
}
}
then in upload function
public function upload() {
if (null === $this->file) {
return;
}
if ($this->file->move($this->getUploadRootDir(), $this->path)) {
// ok uploaded
}else{
echo "failed to upload";
}
}
A: You probably have
$this->file == null
Check that you have instanced it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java Play Framework Global Variables I am currently "Playing" With the Java Play Framework and would like to know a simple solution to having an online status on the main.html page (this page will be consistent throughout the site e.g. navigation bar, header and footer). At the top of this page I would like an online status for users that are signed in, I am yet to implement authentication as I will probably use an already existing play module to do this. My concern is that would I have to send a variable through to the main.html for every page I implement with this online status.
My main question is how do you store globally accessible variables in play?
Thanks
A: The renderArgs are available in inherited templates (main.html), so you don't need to pass them with the #{set} tag. Additionally, if you use a @Before method in a superclass of your controller, you could have it populate the renderArgs with the global value. So you'd only have to set it once to make it available in main.html for all of your pages.
A: I did something similar by writing a FastTag to get the needed information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Universal Programming IDE I'm searching for a good IDE that supports multiply languages and compiling of them, syntax highlighting, uploading of microcontroller projects etc.
The problem is; I currently have 8 different IDE:s, each for a different language (Programmer's Notepad (PHP, HTML), Qt Creator (C++ with Qt libraries), Eclipse C++ (C++), Eclipse Java (Java), Processing (Processing), Arduino IDE (Arduino), AVR Studio (AVR (C)), Microsoft Visual Studio 2010 Express (Visual C++)), and I am sure more will be added to the list.
So what I'm searching for now is a Windows (or cross plattform) Programming IDE with support for as many languages as possible, and not only with syntax highlighting (PN), I want ONE button to compile a program and ONE button to Run/Upload the program, not multiply from a list.
Can someone please help me?
A: Eclipse with according plugins can support almost all of the above, except maybe for VC++
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clean NSLog - No timestamp and program name I almost finishing a clean NSLog with this code:
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, __VA_ARGS__] UTF8String]);
This work fine if I do this:
NSLog(@"Show %@ message", @"this");
But, will fail if I user it
NSLog(@"One argument");
because __VA_ARGS__ is nothing, so it produce
printf("%s\n", [[NSString stringWithFormat:@"One argument",] UTF8String]);
So, the problem is the comma. Because this is macro, __VA_ARGS__ is nothing. So I can't do things like __VA_ARGS__==nil because will produce ==nil and will fail.
The question is simple: What to do when __VA_ARGS__ is nothing? Or only use comma when have more arguments.
A: Use this code (notice the ## part):
#define NSLog(FORMAT, ...) fprintf(stderr, "%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: How to efficiently cache mysql query in php for this table I have a Posts table containing the fields title, contents, rating, no_of_comments, author_id. When a user downvotes the post, the rating field is decremented and vice-versa. Also i am caching the display query, which shows the recent posts, and it's related to the table Authors. The problem is that the ratings field need to be updated often i.e. there are a lot of upvotes and downvotes. So i need to rebuild the cache every time a user up/down the post. I believe this is a waste, because only one field in the entire cached data is updated. So i want to know is there any workaround this issue. btw i am using file based caching.
A: Alright. So your solution is to open an ajax request to a PHP that does the following:
UNTESTED
while (array_pop(mysql_fetch_array(mysql_query("SELECT count(*) FROM `posts` WHERE `ID` = '$latest_id_prediction'"))) == 0) {
sleep(10);
}
echo array_pop(mysql_fetch_array(mysql_query("SELECT * FROM `posts` WHERE `ID` = '$latest_id_prediction'");
This will check every 10 seconds if there is a new post, if there is, it will echo out the post information. what you do is make an ajax request to this page without a timeout, and update the page when you get a reply. When you get the reply, open a new connection.
A: If you normalised your data structure, you would be able to cache the static part - i.e. The "Post", have the "Post Attributes" or whatever you decide to use, being dynamic.
Number of comments should be derived by counting the number of comments in a "Comments" table.
A solid data structure will help you out alot here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: LINQPad and unhandled exceptions I'm trying to crash LINQPad4 using the following C# statement:
new Thread(() => new Thread(() => { throw new Exception(); }).Start()).Start();
An unhandled exception dialog is shown, but the process doesn't die. I suppose IsTerminating = true like in all UnhandledThreadExceptions... how does it stop the process from dying?
A: it has a global exception handler for all non UI thread exceptions as well, something like this in the Main method:
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
there are also other small things to do of course plus as usual the try/catch around the Application.Run.
see a full article and details here: C# Tutorial - Dealing With Unhandled Exceptions
Edit: hb. try to debug this one: ;-)
using System;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
new Thread(() => new Thread(() => { throw new ApplicationException("Ciao"); }).Start()).Start();
try
{
Application.Run(new Form1());
}
catch (Exception exc)
{
System.Diagnostics.Debug.WriteLine(exc.Message);
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// here catching Unhandled Exceptions
System.Diagnostics.Debug.WriteLine(e.ExceptionObject.ToString());
}
}
}
A: LINQPad seems to not only execute its queries, but also load its dependencies within their own AppDomain. If you create a new AppDomain within your application, you can handle the exceptions in a friendly way and reload/compile the application in a friendly manner.
Even more interesting is how LINQPad handles its dependencies. Apparently they are "shadow-copied" when loaded into these AppDomains, since I have a custom library that I have developed and I am able to make changes to it "on-the-fly" and LINQPad doesn't lock the file; instead, it seems as if it has a FileSystemWatcher which looks for changes to the file, unloads the AppDomain, then re-loads the AppDomain with the new dependency.
The 'pause' in the application after building a new library and then those new 'methods' that I have added are now available to scripts through intellisense indicates that LINQPad is rather intelligent when dealing with scripts and referenced libraries that: a) not only change; but b) could cause it to crash.
However, you can always use the System.Diagnostics.Debugger.Break() if you really want to have some fun. If you turn off optimization on your scripts in the LINQPad properties, you can actually debug into the LINQPad process, get your source code in a Visual Studio debugger window, place breakpoints, step through, examine variables, etc. in order to actually 'debug' your code snippets created in LINQPad. It's a couple of extra lines in your script, but well worth it if you do some heavy scripting/testing within LINQPad.
This is still one of the best tools I have been able to find to prototype, unit test and build up C# code which uses LINQ queries that I can just cut & paste into applications with a relatively easy feeling they will behave as observed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to inject different subclasses as ManagedProperty JSF 2? I'm new to JSF and I'm wondering if it's possible to inject different subclasses of a base class as a MangedProperty, depending on different situations? For instance, I have this managed bean:
@ManagedBean
@SessionScoped
public class Claim implements Serializable {
private Loss lossDetails; //need to inject one of two subclasses
}
And the following base class:
public class Loss implements Serializable {
private String lossCause;
private String lossDescription;
}
Which has two subclasses:
public class AutoLoss extends Loss implements Serializable {
private List<String> vehicles;
//...
}
public class PropLoss extends Loss implements Serializable {
private String property;
private boolean weatherRelated;
//...
}
Depending on selections that are made on my application's JSF pages, I want to inject one of the subclasses as the lossDetails ManagedProperty in the Claim managed bean. Since I can't give the two subclasses the same managed bean name and I don't know ahead of time which one needs to be injected, is this something that can be accomplished in JSF? Or is there a different approach I should be considering?
Thanks!
A: You can't and shouldn't.
*
*It's not possible to inject a request scoped value as managed property in a session scoped bean.
*Entities should not be treated as managed beans.
Rather pass it as method argument instead:
<h:dataTable value="#{lossManager.losses}" var="loss">
<h:column>
<h:commandButton value="Claim" action="#{claim.doAction(loss)}" />
</h:column>
</h:dataTable>
With in Claim managed bean:
public void doAction(Loss loss) {
// ...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Question about optimization in C++ I've read that the C++ standard allows optimization to a point where it can actually hinder with expected functionality. When I say this, I'm talking about return value optimization, where you might actually have some logic in the copy constructor, yet the compiler optimizes the call out.
I find this to be somewhat bad, as in someone who doesn't know this might spend quite some time fixing a bug resulting from this.
What I want to know is whether there are any other situations where over-optimization from the compiler can change functionality.
For example, something like:
int x = 1;
x = 1;
x = 1;
x = 1;
might be optimized to a single x=1;
Suppose I have:
class A;
A a = b;
a = b;
a = b;
Could this possibly also be optimized? Probably not the best example, but I hope you know what I mean...
A: It might be optimized, yes. But you still have some control over the process, for example, suppose code:
int x = 1;
x = 1;
x = 1;
x = 1;
volatile int y = 1;
y = 1;
y = 1;
y = 1;
Provided that neither x, nor y are used below this fragment, VS 2010 generates code:
int x = 1;
x = 1;
x = 1;
x = 1;
volatile int y = 1;
010B1004 xor eax,eax
010B1006 inc eax
010B1007 mov dword ptr [y],eax
y = 1;
010B100A mov dword ptr [y],eax
y = 1;
010B100D mov dword ptr [y],eax
y = 1;
010B1010 mov dword ptr [y],eax
That is, optimization strips all lines with "x", and leaves all four lines with "y". This is how volatile works, but the point is that you still have control over what compiler does for you.
Whether it is a class, or primitive type - all depends on compiler, how sophisticated it's optimization caps are.
Another code fragment for study:
class A
{
private:
int c;
public:
A(int b)
{
*this = b;
}
A& operator = (int b)
{
c = b;
return *this;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int b = 0;
A a = b;
a = b;
a = b;
return 0;
}
Visual Studio 2010 optimization strips all the code to nothing, in release build with "full optimization" _tmain does just nothing and immediately returns zero.
A: Eliding copy operations is the only case where a compiler is allowed to optimize to the point where side effects visibly change. Do not rely on copy constructors being called, the compiler might optimize away those calls.
For everything else, the "as-if" rule applies: The compiler might optimize as it pleases, as long as the visible side effects are the same as if the compiler had not optimized at all.
("Visible side effects" include, for example, stuff written to the console or the file system, but not runtime and CPU fan speed.)
A: This will depend on how class A is implemented, whether the compiler can see the implementation and whether it is smart enough. For example, if operator=() in class A has some side effects such optimizing out would change the program behavior and is not possible.
A: Optimization does not (in proper term) "remove calls to copy or assignments".
It convert a finite state machine in another finite state, machine with a same external behaviour.
Now, if you repeadly call
a=b; a=b; a=b;
what the compiler do depends on what operator= actually is.
If the compiler founds that a call have no chances to alter the state of the program (and the "state of the program" is "everything lives longer than a scope that a scope can access") it will strip it off.
If this cannot be "demonstrated" the call will stay in place.
Whatever the compiler will do, don't worry too much about: the compiler cannot (by contract) change the external logic of a program or of part of it.
A: i dont know c++ that much but am currently reading Compilers-Principles, techniques and tools
here is a snippet from their section on code optimization:
the machine-independent code-optimization phase attempts to improve
intermediate code so that better target code will result. Usually
better means faster, but other objectives may be desired, such as
shorter code, or target code that consumes less power. for example a
straightforward algorithm generates the intermediate code (1.3) using
an instruction for each operator in the tree representation that comes
from semantic analyzer. a simple intermediate code generation
algorithm followed by code optimization is a reasonable way to
generate good target code. the optimizar can duduce that the
conversion of 60 from integer to floating point can be done once and
for all at compile time, so the inttofloat operation can be eliminated
by replacing the integer 6- by the floating point number 60.0.
moreover t3 is used only once to trasmit its value to id1 so the
optimizer can transform 1.3 into the shorter sequence (1.4)
1.3
t1 - intoffloat(60
t2 -- id3 * id1
ts -- id2 + t2
id1 t3
1.4
t1=id3 * 60.0
id1 = id2 + t1
all and all i mean to say that code optimization should come at a much deeper level and because the code is at such a simple state is doesnt effect what your code does
A: I had some trouble with const variables and const_cast. The compiler produced incorrect results when it was used to calculate something else. The const variable was optimized away, its old value was made into a compile-time constant. Truly "unexpected behavior". Okay, perhaps not ;)
Example:
const int x = 2;
const_cast<int&>(x) = 3;
int y = x * 2;
cout << y << endl;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: .NET Remoting on Mono: Uri already in use Running:
*
*Ubuntu 10.04, 32-bit
*Mono 2.6.7
I have an application developed in VS 2008 that uses .NET remoting (with a custom RemotingUDPChannel class). We are trying to run this on linux (building in MonoDevelop) now, but I am receiving the following error.
Code causing exception:
this.server = RemotingServices.Marshal(this, objectUri);
Exception:
System.Runtime.Remoting.RemotingException: Uri already in use:
We received this error in the past when running on the Window side if we had multiple remoting apps running, but fixed it by creating a new appdomain for each. However, this does not seem to affect it on the linux side. Also, we are not trying to run multiple remoting apps, just the single one.
Any ideas on this problem? Thanks!
A: Our workaround to this problem:
Remove a tag from our remoting config file that causes the remoting object to be added at both
RemotingConfiguration.Configure(configurationFile, false);
and
RemotingServices.Marshal(this, objectUri);
The tag removed was:
<service>
<wellknown mode="Singleton" objectUri="FileSyncer.rem" type="MyLib.FileSyncerServer, MyLib" />
</service>
This only had to be done from the server side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Struct initialization problem in C I seem to be having a problem setting the values of an array inside a structure with a meaningless error spat out of the compiler:
expected primary-expression before '{' token
I understand that a structure must "exist" to accept values, and it exists as a pointer to one. I would like you to explain to me what i am doing wrong and how to achieve my objective.
struct EventCheckData {
unsigned long refresh_time;
unsigned long last_execution_ms; //Can also serve to delay at startup
byte signal_type;
};
struct ClockData {
struct EventCheckData event_array[4];
byte event_count;
unsigned long last_absolute_time;
UISignal *warning_signals;
};
void ResetClock(UISignal *warning_signal, struct ClockData *clock_data, unsigned long absolute_time) {
if(SignalCheckValue(warning_signal, RESET_CLOCK, 1)) {
extern volatile unsigned long timer0_overflow_count;
timer0_overflow_count = 0;
clock_data->last_absolute_time = absolute_time;
clock_data->event_count = 3;
(clock_data->event_array)[0] = { .refresh_time = 3000UL, .last_execution_ms = 0UL, .signal_type = WATER_PUMP_ON};
// clock_data->event_array[1] = {10000UL, 0UL, EXPORT_LOG};
// clock_data->event_array[2] = {100000UL, 0UL, EXTERNAL_CONNECTION};
SignalSet(warning_signal, RESET_CLOCK, 0);
}
}
Thank you
Paulo Neves
A: The way you are assigning it looks like an initializer. You need assignment, try a compound literal:
clock_data->event_array[0] = (struct EventCheckData){ .refresh_time = 3000UL, ...};
A: (clock_data->event_array)[0] = { .refresh_time = 3000UL, .last_execution_ms = 0UL, .signal_type = WATER_PUMP_ON}; is not initialization. It is assignment.
And you cannot use initializer syntax in assignment.
With C99, you should be able to use a compound literal, like
(clock_data->event_array)[0] = (struct EventCheckData){ .refresh_time = 3000UL, .last_execution_ms = 0UL, .signal_type = WATER_PUMP_ON};
A: Without any C99 stuff you can simply use:
void ResetClock(UISignal *warning_signal, struct ClockData *clock_data, unsigned long absolute_time) {
if(SignalCheckValue(warning_signal, RESET_CLOCK, 1)) {
extern volatile unsigned long timer0_overflow_count;
timer0_overflow_count = 0;
clock_data->last_absolute_time = absolute_time;
clock_data->event_count = 3;
{
struct EventCheckData a[]={ {3000UL, 0UL, WATER_PUMP_ON},
{10000UL, 0UL, EXPORT_LOG},
{100000UL, 0UL, EXTERNAL_CONNECTION}};
memcpy(clock_data->event_array,a,sizeof a);
}
SignalSet(warning_signal, RESET_CLOCK, 0);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C# Preventing clicks on a form without using Enabled=false I have a form that requires a long operation (expansion of a treeview node searches the network for additional items to create more tree nodes) - so I plan on using a BackgroundWorker for this task. During the long operation I want the cursor to be the wait cursor and I want the entire form to be unclickable except for the Cancel button. I know I could use Enabled=false but this turns the treeview grey which looks pretty lame imo.
I could just NOT use a BW but that means I have to use DoEvents to get the cursor to change and that possibly "Not Responding" would show up, which I hate.
I thought of handling all the mouse click events and keyboard events so that they are cancelled if the BW is busy... so that is my current plan. I just wondered if I am missing something, if there is another way.
Thanks.
A: There is no easy way to do that. It is better to fix your treeview and use Enabled property. You can also show your progressbar in Modal dialog - that will block UI
A: You could use a Panel as an overlay over the form, wholly or partly transparent, which only propagates clicks when over the cancel button - similar to the way browsers simulate modal windows by 'graying' the background with an overlay.
When you are in processing mode, set the Z-Order of the mask to be in front of all other controls, and when that finishes set it behind them.
A: You could use Background worker and pop up another dialog with progressbar and that shows current progress and a cancel button. Where you can user
popup = new ProgressWindow();
popup.Owner=this;
popup.show();
And the cancel button will cancel the background worker. In this way your back form will not be clickable and popup will remain on top with cancel button.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: HornetQ reports Invalid STOMP frame in JBoss 7 with stomp-websocket client? The following test client code (using https://github.com/jmesnil/stomp-websocket) yields an exception in JBoss 7.0.1:
var client = Stomp.client("ws://192.168.0.4:61614/stomp");
client.connect("guest", "guest", function() {
client.send("/queue/test", {priority: 9}, "Hello world!");
});
client.subscribe("/queue/test", function(message) {
alert(message.body);
});
It also happens with the single line below:
new WebSocket("ws://192.168.0.4:61614/stomp");
Why does JBoss HornetQ report the following exception?
08:56:55,732 ERROR [org.hornetq.core.protocol.stomp.StompProtocolManager] (Old I/O server worker (parentId: 17267825, [id: 0x01077c71, france/192.168.0.4:61614])) Failed to decode: org.hornetq.core.protocol.stomp.StompException: Invalid STOMP frame: G,E,T,32,/,s,t,o,m,p,32,H,T,T,P,/,1,.,1,13,10,U,p,g,r,a,d,e,:,32,w,e,b,s,o,c,k,e,t,13,10,C,o,n,n,e,c,t,i,o,n,:,32,U,p,g,r,a,d,e,13,10,H,o,s,t,:,32,1,9,2,.,1,6,8,.,0,.,4,:,6,1,6,1,4,13,10,S,e,c,-,W,e,b,S,o,c,k,e,t,-,O,r,i,g,i,n,:,32,n,u,l,l,13,10,S,e,c,-,W,e,b,S,o,c,k,e,t,-,K,e,y,:,32,J,9,d,h,k,4,a,w,c,Z,l,y,d,p,0,k,b,X,P,u,s,Q,=,=,13,10,S,e,c,-,W,e,b,S,o,c,k,e,t,-,V,e,r,s,i,o,n,:,32,8,13,10,13,10,
at org.hornetq.core.protocol.stomp.StompDecoder.throwInvalid(StompDecoder.java:566) [hornetq-core-2.2.7.Final.jar:]
at org.hornetq.core.protocol.stomp.StompDecoder.decode(StompDecoder.java:367) [hornetq-core-2.2.7.Final.jar:]
at org.hornetq.core.protocol.stomp.StompProtocolManager.handleBuffer(StompProtocolManager.java:161) [hornetq-core-2.2.7.Final.jar:]
at org.hornetq.core.protocol.stomp.StompConnection.bufferReceived(StompConnection.java:269) [hornetq-core-2.2.7.Final.jar:]
at org.hornetq.core.remoting.server.impl.RemotingServiceImpl$DelegatingBufferHandler.bufferReceived(RemotingServiceImpl.java:458) [hornetq-core-2.2.7.Final.jar:]
at org.hornetq.core.remoting.impl.netty.HornetQChannelHandler.messageReceived(HornetQChannelHandler.java:73) [hornetq-core-2.2.7.Final.jar:]
at org.jboss.netty.channel.SimpleChannelHandler.handleUpstream(SimpleChannelHandler.java:100) [netty-3.2.3.Final.jar:]
at org.jboss.netty.channel.StaticChannelPipeline.sendUpstream(StaticChannelPipeline.java:362) [netty-3.2.3.Final.jar:]
at org.jboss.netty.channel.StaticChannelPipeline.sendUpstream(StaticChannelPipeline.java:357) [netty-3.2.3.Final.jar:]
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:274) [netty-3.2.3.Final.jar:]
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:261) [netty-3.2.3.Final.jar:]
at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:90) [netty-3.2.3.Final.jar:]
at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) [netty-3.2.3.Final.jar:]
at org.jboss.netty.util.internal.IoWorkerRunnable.run(IoWorkerRunnable.java:46) [netty-3.2.3.Final.jar:]
at org.jboss.netty.util.VirtualExecutorService$ChildExecutorRunnable.run(VirtualExecutorService.java:181) [netty-3.2.3.Final.jar:]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [:1.7.0]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [:1.7.0]
at java.lang.Thread.run(Thread.java:722) [:1.7.0]
A: Look at the standalone.xml (the main configuration file for JBoss)
the old hornetq-configuration.xml is under the message subsystem. All you have to do is to declare the stomp websocket under the acceptors:
<acceptors>
.....
<acceptor name="stomp-websocket">
<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
<param key="protocol" value="stomp_ws" />
<param key="port" value="61614" />
</acceptor>
</acceptors>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I programmatically get the Keyboard Repeat settings in KDE? I have a custom Motif Widget and I'd like to tie its behavior to the Keyboard Repeat settings.
How do I programmatically get the current KDE Control Center Keyboard Repeat settings of Delay and Rate? What API exists to query and set these values?
Also, how can I register to find out when the user changes these values?
A: The XKB library functions XkbGetAutoRepeatRate and XkbSetAutoRepeatRate can be used to access the X server repeat delay and rate settings. The functions are documented on their own man pages. There is also XAutoRepeatOn and XAutoRepeatOff in the basic X library.
Note that the rate and delay settings are provided by the XKB extension and are not available in the raw X protocol, but nowadays you can probably assume that the XKB extension is always available.
You will need KDE toolkit functions if you want to save the settings for future sessions, since it is not possible at the raw X level. Unfortunately I don't know anything about them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Asp Net MVC 3 - Moving through Actions and Views, SessionState How can I keep some values between different Views in MVC 3?
I tried using TempData and HiddenField to keep these values but in our hosting this tecnique seems to have short life so exceptions are coming out furthermore if user uses Back button every starts to fail.
I would like to understand the better way to keep values between views in MVC 3, thanks in advice!
A: By design, MVC3 TempData values are removed after they are used.
The most simple answer is to use the Session object directly in your controllers.
There are other related questions with detailed answers such as these:
Session variables in ASP.NET MVC
Asp.Net MVC and Session
A: Your question is about the lifecycle of objects in between requests. It's important to understand that webapplications are used over the HTTP(S) protocol which is a stateless protocol. This means that every request is a completely new request for the webserver and there's no state shared between requests.
However it would be foolish to send the credentials of a user to the server each and every time so a webserver can create a thing they call a Session (and session-state). This object is an object that remains available for the lifetime of the session of the current user (most of the times from logging in until logging out). You can use this object to store items that you wish to share over various requests of the same user.
If the values you're trying to keep are specific to the page you can probably use a hidden field or something like that. However if the data is more related to the user than to a specific page and it must have a lifecycle longer than a single request then sessionstate is the best place to store the data.
A: You could use the Session (as you mention in your title and tags). Or store a cookie on the user's machine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I initialize normal array member variable in initializer list? I would like to do the following:
class MyClass {
public:
MyClass() : arr({1,2,3,4,5,6,7,8}) {}
private:
uint32_t arr[8];
};
but it doesn't work (compiler: expected primary expression before '}' token.). I've looked at other SO questions and people were passing around things like std::initializer_list, and trying interesting things like placing the array initializer in double braces like so:
MyClass() : arr( {{1,2,3,4,5,6,7,8}} ) {}
but I'm unfamiliar with the purpose of std::initializer_list and also I'm not quite sure why there's double braces in the above code (though it doesn't work anyway, so I'm not sure why it matters).
Is there a normal way to achieve initialization of my arr variable in a constructor initializer list?
A: Your syntax is correct. Alternatively, you can say arr{1,2,3,...}.
Most likely is that your compiler just doesn't support this construction yet. GCC 4.4.3 and 4.6.1 both do (with -std=c++0x).
A: Works perfectly on GCC 4.5.2 with -std=gnu++0x. I get a warning and a freeze with -std=c++98.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Changing webservice reference dynamically I've got a webservice written in VS2008, and I'm trying to consume it with an exe written in VS2010. I need to be able to reference the service URL dynamically from within the application.
In the past I was able to change the URL Behavior for the service from Static to Dynamic, but this is not showing up as an option for me now for some reason. When I look at the properties for the service, the only item I see is "Folder Name". In other projects I was able to see "Folder Name", "URL Behavior", and one other that I can't remember off the top of my head.
Does anybody know how I can change the URL programmatically if I can't change the URL Behavior to dynamic?
A: If you are using .NET 3.5 then you can specify the URL inside the block in the app config as shown below
<client>
<endpoint address="http://localhost/yourService.asmx"
binding="basicHttpBinding"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Issue with node cluster (nodejs) i went through this code (sample of node-cluster), its working fine without errors, but no response from http server.
as per logs it was created workers and those are running
var cluster = require('cluster')
, http = require('http');
var server = http.createServer(function(req, res){
console.log('%s %s', req.method, req.url);
var body = 'Hello World';
res.writeHead(200, { 'Content-Length': body.length });
res.end(body);
});
cluster(server)
.use(cluster.logger('logs'))
.use(cluster.stats())
.use(cluster.pidfiles('pids'))
.use(cluster.cli())
.use(cluster.repl(8888))
.listen(3000);
A: Just tested your code on node 0.4.12, it works fine. I tried to make a request with curl and it returns Hello world as it should.
Are you sure that there are no errors and you have node version 0.4? They added build-in cluster functionality since 0.5 if I recall it correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPad: UIModalPresentationFormSheet fails on landscape mode We've the next problem in our iPad version.
I've a NavigationController inside a UITabBar. I want to show a Form with a look&feel similar than the e-Mail form.
I use the same code to show a model centered:
// View to be displayed in the modal
AdhocViewController *controller = [[AdhocViewController alloc] initWithNibName:@"AdhocViewController" bundle:[NSBundle mainBundle]];
controller.caller = self;
// The form will need a navigation bar to cancel or save the form
UINavigationController *modalViewNavController = [[UINavigationController alloc]
initWithRootViewController:controller];
// Configurate the modal presentation and transition
modalViewNavController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
modalViewNavController.modalPresentationStyle = UIModalPresentationFormSheet;
// Show the new view
[self presentModalViewController:modalViewNavController animated:YES];
This code works perfectly on portrait mode, but on landscape the view appears partially out of the screen ... and I didn't found yet the way to solve it.
I test some of the solutions I found here ...
And try to add the next lines after preset the model view to resize it, but doesn't work it out
controller.view.superview.frame = CGRectMake(0, 0, 600, 700);
controller.view.superview.center = self.view.center;
Any suggestion?
Thanks,
Ivan
References in StackOverflow:
*
*iPad modalPresentationStyle UIModalPresentationFormSheet orientation problem
*UIModalPresentationFullScreen not working in iPad landscape mode?
*UIModalPresentationFormSheet on iPad in landscape mode
*How to resize a UIModalPresentationFormSheet?
A: With iOS7 the trick is to set the modalTransitionStyle to UIModalTransitionCrossDissolve.
UIViewController *viewController = [[UIViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
navigationController.modalPresentationStyle = UIModalPresentationFormSheet;
navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:navigationController animated:YES completion:nil];
navigationController.view.superview.frame = CGRectMake(0, 0, 800, 544);
navigationController.view.superview.center = self.view.center;
https://coderwall.com/p/vebqaq
A: Finally the code was the next:
// Remove the modalTransitionStyle to enable the default behaviour and change to PageSheet
modalViewNavController.modalPresentationStyle = UIModalPresentationPageSheet;
// Present the modal view and adapt the center depending of the orientation
[self presentModalViewController:modalViewNavController animated:YES];
UIDeviceOrientation _orientation = [controller interfaceOrientation];
if (UIDeviceOrientationIsPortrait(_orientation)){
modalViewNavController.view.superview.center = CGPointMake(768/2, 1024/2 + 10);
} else {
modalViewNavController.view.superview.center = CGPointMake(768/2 - 10, 1024/2);
}
The +10 and -10 is because by deafult the NavigationController of the modal was out of the screen on top.
It is ... a crappy solution :SS but works ... Although if anybody have suggestions would be nice to know.
Seams that if I need to include the same center for both orientation, maybe the orientation of the superview is not the expected one.
In this solution, when I dissmiss the modal view on Portrait orientation, at least on the iPad simulator, it rotate to portrait mode automatically ...
The final solution was to execute the presentModalViewController over the main controller, the UITabBar, and update the dismiss method to be executed also over it.
[tabbar presentModalViewController:modalViewNavController animated:YES];
UIDeviceOrientation _orientation = [controller interfaceOrientation];
if (UIDeviceOrientationIsPortrait(_orientation)){
modalViewNavController.view.superview.center = CGPointMake(768/2, 1024/2 + 10);
} else {
modalViewNavController.view.superview.center = CGPointMake(1024/2, 768/2 + 10);
}
Finally!!!!
Thank you,
Iván
A: In iOS 7, to solve the problem of the modal view controller to appear to the left after apparition of the keyboard (problem that I have when I present an EKEventEditViewController in UIModalPresentationFormSheet, I do :
[self presentViewController:modalViewController animated:YES completion:^{
modalViewController.view.superview.center = self.view.center;
}];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get each menu item from a list view by position? Let's say a list has 4 items, how can I get a view from each menu item of a list by position?
A: Unfortunately the items that are in the ListView are generally only those that are visible. You should iterate on the ListAdapter instead.
For example, in some of my code, I have this:
SimpleCursorAdapter adapter = (SimpleCursorAdapter) this.getListAdapter();
int iNum = adapter.getCount();
for(int i=0; i<iNum; i++)
{
Cursor c = (Cursor) adapter.getItem(i);
// Now you can pull data from the cursor object,
// if that's what you used to create the adapter to start with
}
EDIT:
In response to jeffamaphone's comments, here's something else... if you are trying to work with each UI element then getChildAt is certainly more appropriate as it returns the View for the sub-item, but in general you can still only work with those that are visible at the time. If that's all you care about, then fine - just make sure you check for null when the call returns.
If you are trying to implement something like I was - a "Select All / Select None / Invert Selection" type of feature for a list that might exceed the screen, then you are much better off to make the changes in the Adapter, or have an external array (if as in my case, there was nowhere in the adapter to make the chagne), and then call notifyDataSetChanged() on the List Adapter. For example, my "Invert" feature has code like this:
case R.id.selectInvertLedgerItems:
for(int i=0; i<ItemChecked.length; i++)
{
ItemChecked[i] = !ItemChecked[i];
}
la.notifyDataSetChanged();
RecalculateTotalSelected();
break;
Note that in my case, I am also using a custom ListView sub-item, using adapter.setViewBinder(this); and a custom setViewValue(...) function.
Furthermore if I recall correctly, I don't think that the "position" in the list is necessarily the same as the "position" in the adapter... it is again based more on the position in the list. Thus, even though you are wanting the "50th" item on the list, if it is the first visible, getChildAt(50) won't return what you are expecting. I think you can use ListView.getFirstVisiblePosition() to account and adjust.
A: See here, this question answers the similar problem you mentioned here
In an android ListView, how can I iterate/manipulte all the child views, not just the visible ones?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: why doesn't the script work this way? Following is a statement that should run according to me when the HTML page loads.
document.getElementById("name_field").value = "JavaScript";
But this does nothing.If i try to do the same thing the different way :
window.onload = init;
function init() {
document.getElementById("name_field").value = "JavaScript";
}
Then this works fine.
What is wrong with the first script.?
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="valtest.js">
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
<input type="submit" value="submit" />
</form>
</body>
</html>
A: Onload runs after the HTML has been rendered in the page. So in your first example the element is not yet available for JavaScript processing.
Most use "document ready", which means the document has been rendered.
jQuery example:
$(document).ready(function() {
init()
});
A: Your HTML probably looks like this:
<script>
document.getElementById("name_field").value = "JavaScript";
</script>
<!--
More
code
here
-->
<input id="name_field" value="Static">
If that's the case, when the JavaScript is run there is no element with the ID "name_field" in the DOM yet.
window.onload is executed only after the entire DOM has been loaded and parsed ... which is why running the function then works. (It would also work if it was attached to any other event handler that ran after the DOM was loaded, or even if the order of the script and input tags were reversed.)
A: The element with id 'name_field' isn't available in the DOM yet because the whole document gets loaded in the sequencial order.
The second example will execute once the document has been loaded and your element is available.
A: the javascript in your first sample execute immediately, before any DOM has rendered. You have to wait for the DOM to render before you try to operate on it, which you are doing in your second sample.
A: The first script may or may not work depending on where it is placed within your HTML. If the script is before the field itself (the <input id="name_field" />), the script will run before the browser acknowledges the existence of the field, so it will do nothing (actually, it should throw an error stating that you are trying to access the value property of an undefined object).
The second version runs after the page finishes loading. By then, the browser already knows about your field, to the script works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server To MySQL conversion script error surrounding UUID()? ALTER TABLE aspnet_Paths ALTER PathId SET DEFAULT UUID();
I've ran a converter program on "generate" scripts from a SQL Server database.
I seem to be having uuid in the above statement highlighted in work benches query window with the statement "Error Syntax near uuid()",
I'm moving to MySQL. What's the correct implementation of this statement?
Any help/advise is much appreciated
A: Try to use a BEFORE INSERT trigger -
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE INSERT
ON aspnet_paths
FOR EACH ROW
BEGIN
IF NEW.PathId IS NULL THEN
SET NEW.PathId = UUID();
END IF;
END
$$
DELIMITER ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Difference between JBPM and BPEL/ESB what is difference between JBPM and BPEL(and ESB)?
Would you please explain them?
RGDS
A: I am not much familiar with JBPM. But it seems to be a Business work flow which can work with java services or basically java based process. Not only with web services.
BPEL is a standard to write work follows with web services. Always BPEL language used to integrate the web services and define processes based on that. Here is an sample I have written for that[1].
ESB is primarily used for mediation and transform messages. When you integrate different types of systems, the message flow between them may vary. So people can use ESB as a mediator. And also some ESBs provides service integration as well. WSO2 ESB[2] is such an ESB you can use.
[1] http://wso2.org/library/articles/2011/05/integrate-business-rules-bpel
[2] http://wso2.org/library/esb
A: Exactly, ESB + BPEL is a technical solution for an integration problem. If you want to use jBPM5 just to do integrations thats fine and you probably will use jBPM5 with an ESB for all your mediation and transformation of your messages. The power of BPMN2, a standard notation to describe business processes will help you to describe more high level/business oriented scenarios than just simple system integrations. The concept of human interaction is heavily embedded in the language and in the jBPM5 infrastructure. Think about the fact that your models (business processes) can be shared and understood by business/non technical people and they will be able to validate, improve and change those definitions when the business reality changes.
Hope it helps!
A: jBPM is BPMN based. This is a java based solution to your workflow problem.
BPEL is also solves the workflow problem, but the approach is entirely different. It is web service based.
BPEL from a syntax perspective is more complex than BPMN but is considered more extensive.
The right comparison should actually be between BPMN and BPEL I guess.
A: Similarity
*
*>Both can be used for orchestration
difference in terms of technology.
JBPM has BPMN2.0 Notation for Workflow designer and workflow XML it generate is BPM2.0 compliance(which means you can import it in any BPMN2.0 tool) .It is assumed to be Product Analyst friendly whereas BPEL has its own specifications and its considered more developer oriented
BPM should only be used where there is a human task otherwise ESB fulfills everything from orchestration to transformation to Rules to CEP
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Actionscript 3 writing a XML element inside a another with code I'm having a bit of problems with simple XML coding. I'm using a simple flash application to write a XML containing customer data (simple stuff, like phone number, name, email, etc).
I understand how to write XML manually, but my issue comes when I want to create a element inside another element. I'm using AS3.
So, for example, I have the following xml.
<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
</xmlcontainer>
If I want to add a new element, thats fine. But i'm not sure how to add a element INSIDE once its done in code.
I have been using .appendChild(<client/>) so far, but errors pop up as I do element inside element. I tried writing as a text element (i.e., manually) by just doing .appendChild("<client><name>Marco</name></client>"), but the less than and great than symbols don't pass along correctly.
Can someone help me out here?
EDIT: As requested, here is the full code.
function appendXML():void{
var xmlData:XML = new XML();
var xmlrequest:URLRequest = new URLRequest(String("xml/clientelist.xml"));
xmlLoader.load(xmlrequest);
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
function LoadXML(e:Event):void
{
xmlData = new XML(e.target.data);
xmlData.appendChild(<pessoa/>);
xmlData.appendChild(<id/>);
xmlData.id.appendChild(idfield.text);
xmlData.appendChild(<nome/>);
xmlData.nome.appendChild(nomefield.text);
xmlData.appendChild(<email/>);
xmlData.email.appendChild(emailfield.text);
xmlData.appendChild(<contacto/>);
xmlData.contacto.appendChild(contacto1field.text);
trace(xmlData);
var fileb:FileReference = new FileReference;
fileb.save( xmlData, "clientelist.xml" );
}
(pessoa = person, nome = name, contacto = phonenumber)
A: I get no errors with your code.
I modified the text field values and hard coded as a string for testing .
So what errors are you getting?
Sounds to me like your xml response from the server might be broken.
The following code is a working example, although I don't thinkthe data is structured the way you want.
var xmlData:XML = new XML(<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
</xmlcontainer>
);
xmlData.appendChild(<pessoa/>);
xmlData.appendChild(<id/>);
xmlData.id.appendChild('idFieldText');
xmlData.appendChild(<nome/>);
xmlData.nome.appendChild('nameFieldText');
xmlData.appendChild(<email/>);
xmlData.email.appendChild('email');
xmlData.appendChild(<contacto/>);
xmlData.contacto.appendChild('phone');
trace(xmlData);
// output is
<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
<pessoa/>
<id>idFieldText</id>
<nome>nameFieldText</nome>
<email>email</email>
<contacto>phone</contacto>
</xmlcontainer>
// And to build on it dont forget to add CDATA tags to all user input fields.<br/>
var xmlData:XML = new XML(<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
</xmlcontainer>
);
var userID:String = '123456789'
var userName:String = 'John doe'
var email:String = 'my@email.com'
var phone:String = '888-555-1212'
xmlData.appendChild(<pessoa/>);
xmlData.appendChild(<id/>);
xmlData.id.appendChild( new XML( "\<![CDATA[" + userID + "]]\>" ));
xmlData.appendChild(<nome/>);
xmlData.nome.appendChild( new XML( "\<![CDATA[" + userName + "]]\>" ));
xmlData.appendChild(<email/>);
xmlData.email.appendChild( new XML( "\<![CDATA[" + email + "]]\>" ));
xmlData.appendChild(<contacto/>);
xmlData.contacto.appendChild( new XML( "\<![CDATA[" + userID + "]]\>" ));
trace(xmlData);
//output is
<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
<pessoa/>
<id><![CDATA[123456789]]></id>
<nome><![CDATA[John doe]]></nome>
<email><![CDATA[my@email.com]]></email>
<contacto><![CDATA[123456789]]></contacto>
</xmlcontainer>
// to expand farther and clean up
var xmlData:XML = new XML(<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
</xmlcontainer>
);
var userID:String = '123456789'
var userName:String = 'John doe'
var email:String = 'my@email.com'
var phone:String = '888-555-1212'
var client:XML = new XML(<client/>)
//client.appendChild(<id/>);
client.appendChild( new XML( "<id>\<![CDATA[" + userID + "]]\></id>" ));
client.appendChild( new XML( "<nome>\<![CDATA[" + userName + "]]\></nome>" ));
client.appendChild( new XML( "<email>\<![CDATA[" + email + "]]\></email>" ));
client.appendChild( new XML( "<contacto>\<![CDATA[" + userID + "]]\></contacto>" ));
xmlData.appendChild(client);
trace(xmlData);
// output is
<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
<client>
<id><![CDATA[123456789]]></id>
<nome><![CDATA[John doe]]></nome>
<email><![CDATA[my@email.com]]></email>
<contacto><![CDATA[123456789]]></contacto>
</client>
</xmlcontainer>
And to sum up your question.
When you add a node "client" in your case you can only target it in 2 ways.
The first way is to create an XMLList and loop through it until you find the one you are looking for. This is due to the fact that you have multiple "clients".
The second method would be to Id the clients somehow for example an attribute.
If you know the Id you can target that specific node easy.
A: Try:
var xml:XML = <a/>
xml.appendChild(new XML("<b>hello</b>"))
trace(xml.toXMLString());
You should get
<a><b>hello</b></a>
A: You can use in the XML { here_my_var_to_replace } notation for example to replace your dynamic data
Here an example :
function addClient(xml:XML, name:String, phone:String):void {
// will replace into tpl replace {name} and {phone} by their values
var tpl:XML=<client><name>{name}</name><phone>{phone}</phone></client>;
// append the new node to the xml
xml.appendChild(tpl);
}
// test
var myXML:XML=<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
</xmlcontainer>;
addClient(myXML, "foo", "12345678");
trace(myXML.toXMLString());
// output:
<xmlcontainer>
<client>
<name>Marco</name>
<phone>123456789</phone>
</client>
<client>
<name>Roberto</name>
<phone>987654321</phone>
</client>
<client>
<name>foo</name>
<phone>12345678</phone>
</client>
</xmlcontainer>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I initialize a SparseVector in Eigen How can I initialize a SparseVector in Eigen ? The following code:
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>
using namespace Eigen;
SparseVector<float> vec(3);
main()
{
vec(0)=1.0;
}
gives me the following error
error: call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
vec(0)=1.0;
by the way, vec[0]=1.0 doesn't work either.
A: Looking at the documentation I noticed Scalar& coeffRef(Index i), and it says:
Returns a reference to the coefficient value at given index i. This operation involes a log(rho*size) binary search. If the coefficient does not exist yet, then a sorted insertion into a sequential buffer is performed. (This insertion might be very costly if the number of nonzeros above i is large.)
So the following should work:
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>
using namespace Eigen;
SparseVector<float> vec(3);
main()
{
vec.coeffRef(0)=1.0;
}
Not sure why they did it that way instead of using array overloading. Perhaps when it becomes IS_STABLE then they'll do it in a more typical C++ way?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: IIS Web request to different service based on incoming IP address? Can IIS be configured to direct a web request to different page based on the incoming connection's IP address?
I have devices connect to an .aspx page by going to a URL that looks like:
http://myhost/myservice/mypage.aspx
Depending on the inbound IP address, I would like to configure IIS to direct communications to a URL like:
http://myhost/myservice2/mypage.aspx
I do not want my back-end code to have any logic to check the IP addresses. I would like to configure IIS to manage this. Is this possible?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Easiest way to enable Google authentication for GWT application? (non-GAE-hosted) What is the easiest way to enable existent GWT application authenticate users using Google account? I tried googling (lol) it but have found no solutions that could work out of the box. Is there a library to solve this problem in like 10 lines of code?
P.S. The application I've mentioned isn't hosted at Google Apps if it matters.
A: I have been looking at gwt-oauth2 for this purpose recently. It looks pretty decent, and the docs are straightforward. Perhaps it could be of interest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Node.js url.parse result back to string I am trying to do some simple pagination.
To that end, I'm trying to parse the current URL, then produce links to the same query, but with incremented and decremented page parameters.
I've tried doing the following, but it produces the same link, without the new page parameter.
var parts = url.parse(req.url, true);
parts.query['page'] = 25;
console.log("Link: ", url.format(parts));
The documentation for the URL module seems to suggest that format is what I need but I'm doing something wrong.
I know I could iterate and build up the string manually, but I was hoping there's an existing method for this.
A: If you look at the latest documentation, you can see that url.format behaves in the following way:
*
*search will be used in place of query
*query (object; see querystring) will only be used if search is absent.
And when you modify query, search remains unchanged and it uses it. So to force it to use query, simply remove search from the object:
var url = require("url");
var parts = url.parse("http://test.com?page=25&foo=bar", true);
parts.query.page++;
delete parts.search;
console.log(url.format(parts)); //http://test.com/?page=26&foo=bar
Make sure you're always reading the latest version of the documentation, this will save you a lot of trouble.
A: Seems to me like it's a bug in node. You might try
// in requires
var url = require('url');
var qs = require('querystring');
// later
var parts = url.parse(req.url, true);
parts.query['page'] = 25;
parts.query = qs.stringify(parts.query);
console.log("Link: ", url.format(parts));
A: The other answer is good, but you could also do something like this. The querystring module is used to work with query strings.
var querystring = require('querystring');
var qs = querystring.parse(parts.query);
qs.page = 25;
parts.search = '?' + querystring.stringify(qs);
var newUrl = url.format(parts);
A: To dry out code and get at URL variables without needing to require('url') I used:
/*
Used the url module to parse and place the parameters into req.urlparams.
Follows the same pattern used for swagger API path variables that load
into the req.params scope.
*/
app.use(function(req, res, next) {
var url = require('url');
var queryURL = url.parse(req.url, true);
req.urlparams = queryURL.query;
next();
});
var myID = req.urlparams.myID;
This will parse and move the url variables into the req.urlparams variable. It runs early in the request workflow so is available for all expressjs paths.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Getting credit_balance I've got a whitelisted app for credits on FB and I'm trying to get the balance for a user but I keep getting error 13. That credits_balance is not part of the user table.
The docs say to re-authenticate the user after being whitelisted and I believe I've done.
However, is their "authentication" just FB.login? I read through the permissions page to see if there was a special permission I needed to ask for, but haven't had any luck.
I'm not sure what else they mean by authenticate users if it's not that.
Any info is appreciated!
A: I had the same problem. I requested for credits special incentives for my apps, and nothing happened for a while and I didn't have permissions to get user's balance.
I contact Facebook's support and listed my apps ids, and then they got me whitelisted and now I can access user's balance.
Are you sure you're whitelisted? How?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to develop a program that install SQL Express and add a database in it I would need to create a program that only install SQL Express and install a database at the same time (either from a bak or mdf, whichever is prefered) At the end of the creation, this program would generate a text file.
I found on the web how to install SQL Express, but I can't seem to find anything to add a database after the installation.
So far I don't have anything to install else than that because the application that will use the application will be installed on another machine.
Thanks
A: One simple way would be to make a simple batch file, with a line to run the SQL Express command line install and then the next to run sqlcmd to do the restore.
How to: Install SQL Server 2008 R2 from the Command Prompt
Backup and Restore Your SQL Server Database from the Command Line
If you want to make your life easier then use some kind of installer tool. I have used Advanced Installer, InstallAware, and InstallShield at various times to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hot to get and set cookie in an API call from Blackberry app? Can anybody please, help me out in get/set cookie in http get request from a blackberry application ?
I was able to get the cookie by iterating through the response header. I don't know whether this is the best practice to retrieve the cookie. Please advise.
A: Iterating through the headers is pretty much all you can do to read cookies from an Http response.
To set the cookie, you have to use the "Set-Cookie" header and have name=value defined for the Http requests. If you don't know how to set headers for HttpRequests in Blackberry, you have to use the setRequestProperty method for an HttpConnection object.
Here, the method call would be something like this:
con.setRequestProperty ("Set-Cookie", "NAME=VALUE");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fullscreen Web App for Android I want to run my Web App, which i programmed with HTML5, in fullscreen mode on Android.
(hide the status bar, and the adress/navigation bar)
for iOS you only write:
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
But that did not work on Android.
There are a lot of solution´s with Javascript, but all solutions which I tried are inoperative.
Somebody know the solution?
A: This worked for me on Chrome for Android.
Add this to the head tags:
<meta name="mobile-web-app-capable" content="yes">
Then in the chrome browser menu, Goto Add to Homepage. This Icon will now open your website up in fullscreen.
A: I do not think you will find a global solution for that since not everybody uses the default android webbrowser (e.g. I prefer dolphin).
Facing that fact you will need to try every dirty javascript hack to force that behavior.
The only reason why this works for apple devices is the fact that apple is very restrictive about developing a custom browser and everybody sticks to the default app.
A: You can achieve this with googles new progressive web app adding the service worker. Have a look here: https://addyosmani.com/blog/getting-started-with-progressive-web-apps/ and https://developers.google.com/web/progressive-web-apps/ .
You can add icon in homescreen for your webapp,get fullscreen, can use push notification etc.
A: I use a mix of the HTML meta tag for iOS and a JavaScript solution.
It takes away the address bar on iOS and android devices. It does not take out the bottom bar on iOS as this will only disappear when the user installs the web page as a HTML5 app on his home screen.
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
<script type='text/javascript' charset='utf-8'>
// Hides mobile browser's address bar when page is done loading.
window.addEventListener('load', function(e) {
setTimeout(function() { window.scrollTo(0, 1); }, 1);
}, false);
</script>
I use PHP in the backend to only render the JavaScript for mobile browser with the following mobile browser detection
if (preg_match('/iphone|ipod|android/',strtolower($_SERVER['HTTP_USER_AGENT'])))
A: <meta name="apple-mobile-web-app-capable" content="yes" />
This tag is designed to show a chromeless environment after you have added your site to the iPhone's home screen.
I wouldn't rely on this to work for android.
To make the browser bar scroll out of the way once your page has loaded see this question's answer:
Removing address bar from browser (to view on Android)
A: As indicated by Google
Since Chrome M31, you can set up your web app to have an application
shortcut icon added to a device's homescreen, and have the app launch
in full-screen "app mode" using Chrome for Android’s "Add to
homescreen" menu item.
See https://developer.chrome.com/multidevice/android/installtohomescreen
A: From the Android side and for versions lower than honeycomb, this should be done using:
Window w = getWindow();
w.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
w.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
If the Android Browser doesn't do something like that when it reads the meta info, I would try looking into phonegap to check if they solve this issue.
A: This code might help...
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); --> hide the Top Android Bar.
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: implementing convenience constructors for automatic reference counting Without automatic reference counting you often write code like this, when adding a new class:
assuming the classname is "Foo"
+ (id) foo
{
return [[[self alloc] init] autorelease];
}
- (id) init
{
self = [super init];
// do some initialization here
return self;
}
Well, how are you supposed, to write this for arc?
Just like the code below?
+ (id) foo
{
return [[self alloc] init];
}
- (id) init
{
self = [super init];
// do some initialization here
return self;
}
A: Yes. Are you expecting something different?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Load mod_h264_streaming.dll in Windows Apache2 Hi I am trying to stream video from static html5 pages serve by Windows Apache2. According to Apache guide on http://h264.code-shop.com/trac/wiki/Mod-H264-Streaming-Apache-Version2
this only for Linux, so I get the mod_h264_streaming.dll from http://h264.code-shop.com/trac/wiki/Mod-H264-Streaming-Internet-Information-Services-IIS7-Version2 but when I LoadModule h264_streaming_module modules/mod_h264_streaming.dll in httpd.conf it return
httpd.exe: Syntax error on line 129 of C:/Program Files (x86)/Apache Software Fo
undation/Apache2.2/conf/httpd.conf: Can't locate API module structure `h264_stre
aming_module' in file C:/Program Files (x86)/Apache Software Foundation/Apache2.
2/modules/mod_h264_streaming.dll: No error
Any help would be appreciated, thanks in advanced!
A: That dll you downloaded is only for IIS not apache
A: Step by Step
1- At first Download Visual Studio 2008 x64 SP1, be sure to install the Visual C++ 2008 x64 SP1 Redistributable Package
it can be downloaded from;
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=BA9257CA-337F-4B40-8C14-157CFDFFEE4E
2- Download Apache module mod_h264_streaming from ; https://www.apachehaus.net/modules/mod_h264_streaming/ in the below.Before download Please careful about your apache version.consider it.
3- Extrach files , copy "mod_h264_streaming.so"
3- If you are using Wamp server go the C:\wamp\bin\apache\Apache2.4.4\modules and drop(add,copy what ever you say) mod_h264_streaming file to the path. If you are not using wamp go to C:/Apache24/modules/ and add mod_h264_streaming.
4- Then Go to httpd.conf (in the C:\wamp\bin\apache\Apache2.4.4\conf path) , open with notepad++ find load modules line
just like ;
LoadModule auth_basic_module modules/mod_auth_basic.so // opened module
#LoadModule auth_digest_module modules/mod_auth_digest.so // closed module
#LoadModule authn_anon_module modules/mod_authn_anon.so
When you find the lines add this ;
LoadModule h264_streaming_module modules/mod_h264_streaming.so
save and quit. Finally restart the apache server. Module is ready to serve you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: translating from javascript to jquery i'm trying to translate code from javascript to jquery and i need a little help
so , i have this code:
$('input[type=file]#upload_input_general_uploader').change(function(e){
var browserName=navigator.appName;
if (browserName=="Microsoft Internet Explorer"){
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
}
}
and i tried to translate it to jquery , that's what i got but that seems to not work
$('input[type=file]#upload_input_general_uploader').change(function(e){
$browserName=navigator.appName;
if ($browserName=="Microsoft Internet Explorer"){
$myFSO = new ActiveXObject("Scripting.FileSystemObject");
$filepath = document.$(this).val();
$thefile = $myFSO.getFile($filepath);
$filesize = thefile.size;
}
}
e.g for those who asked why - i need this code to be with jquery to be dynamic , i need to work with $(this) because this function get active for few inputs.
so , what's the problem here?
A: Start with this line:
document.$(this).val();
$ is not a property of document, so you'll get an error like TypeError: undefined_method when that line is executed.
A: How about:
$('input[type=file]#upload_input_general_uploader').change(function(e){
if ($.browser.msie){
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = $(this).val();
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
}
}
You don't really need to translate it if you don't need to. It's all javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Library of Custom Controls in Winforms I wanted a TextBox with just digits as entry. So i wrote following code in the KeyPress events of the textbox
if(!char.IsDigit(e.KeyChar))
{
e.handled = true;
}
and it worked great. But I generally need them in many places of my application so then i wrote a partial class with following codes:
public partial class digitTextBox : TextBox
{
public digitTextBox()
{
this.KeyPress += new KeyPressEventHandler(digitTextBox_KeyPress);
}
void digitTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
build my solution and I got a control in my toolbox and even this was working perfectly fine.
But i had many TextBoxes with some or the other specification like, some should not accept special characters, some should accept decimals, some with decimals up to 2 digits after point....and so on and i do need these kind of controls in many applications.
So I thought of writing a Library(.dll) of my custom controls and if possible even for there validations. Honestly speaking I don't have much idea about using libraries. So I made a library with 2 different kind of textboxes and created a .dll file out of them. Now I created a different winform application and I added reference of my custom control .dll file. But nothing happened.
So i just wanted to know what should be my approach in achieving it. Is there a better way to achieve these kind of tasks. and any new suggestions are also welcome. Thanks in advance.
A: Try right-mouse clicking the ToolBox and select "Choose Items..." and then select your controls from the available list. If you don't see them, then click on the Browse button and select your DLL.
On a side note, you might be able to combine your two textboxes by adding properties:
public class MyTextBox : TextBox
{
public bool AllowDigitsOnly { get; set; }
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (this.AllowDigitsOnly)
{
if (!char.IsDigit(e.KeyChar))
e.Handled = true;
}
base.OnKeyPress(e);
}
}
A: I would suggest implementing a single custom control, which controls input based on a regular expression. Instead of limiting keypresses, I would prevent the control loosing focus if its text does not match the regular expression. Some change in background color or a popup ballon can be used to display errors and/or a description of what the input is supposed to be.
A: I did something similar and what helped me was to add properties to my textbox instead of creating 2 different types for integers and doubles (basically allowing a decimal for my requirements).
By creating a property, you can actually choose whether you want the textbox as integer or double in the Properties view at design-time. Just like how you have Font, ReadOnly etc that you set during design time.
Here is my code to make the properties,
/// <summary>
/// Identify textbox type as integer or double
/// </summary>
public enum numericID
{
Integer,
Double
};
/// <summary>
/// Textbox type property, default is integer
/// </summary>
private numericID numericType = numericID.Integer;
/// <summary>
/// Getter and setter for property
/// </summary>
[Browsable(true),
DisplayName("TextBoxType"),
DefaultValue(numericID.Integer),
Description("Indicates whether the textbox must only accept integers or doubles."),
Category("Behavior")]
public numericID NumericType
{
get { return numericType; }
set { numericType = value; }
}
and the onKeyPress event is actually quite handy from the msdn website. It handles all different types of characters for numerics and you can choose whichever one works best for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python 2.5 time.time() as decimal Is it possible to receive the output of time.time() in Python 2.5 as a Decimal?
If not (and it has to be a float), then is it possible to guarantee that inaccuracy will always be more than (rather than less than) the original value. In other words:
>>> repr(0.1)
'0.10000000000000001' # More than 0.1 which is what I want
>>> repr(0.99)
'0.98999999999999999' # Less than 0.99 which is unacceptable
Code example:
import math, time
sleep_time = 0.1
while True:
time_before = time.time()
time.sleep(sleep_time)
time_after = time.time()
time_taken = time_after - time_before
assert time_taken >= sleep_time, '%r < %r' % (time_taken, sleep_time)
EDIT:
Now using the following (which does not fail in testing but could still theoretically fail):
import time
from decimal import Decimal
def to_dec(float_num):
return Decimal('%2f' % float_num)
sleep_time = to_dec(0.1)
while True:
time_before = to_dec(time.time())
time.sleep(float(sleep_time))
time_after = to_dec(time.time())
time_taken = time_after - time_before
assert time_taken >= sleep_time, '%r < %r' % (time_taken, sleep_time)
print 'time_taken (%s) >= sleep_time (%s)' % (time_taken, sleep_time)
A: You could simply multiple time.time() by some value to get the precision you want (note that many calls can't guarantee sub-second accuracy anyways). So,
startTime = int(time.time() * 100)
#...
endTime = int(time.time() * 100)
Will satisfy your condition that endTime - startTime >= sleepTime
A: You could format your float value as so:
>>> '%.2f' % 0.99
'0.99'
See Python's String Formatting Operations
A:
It is for a timing function which needs to register a time before and after a call that may sleep. So time after - time before >= sleep time, which is not always the case with floats.
I think your requirements are inconsistent. You seem to want to call the same function twice, and have the first call round the result downwards, and the second call to round the result upwards.
If I were you:
*
*I'd time many calls instead of just one.
*When drawing any conclusions I'd take into account the resolution of the timer and any floating-point issues (if relevant).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Column ' ' in where clause is ambiguous Error in mysql SELECT tbl_user.userid,
tbl_user.firstname,
tbl_user.lastname,
tbl_user.email,
tbl_user.created,
tbl_user.createdby,
tbl_organisation.organisationname
FROM tbl_user
INNER JOIN tbl_organisation
ON tbl_user.organisationid = tbl_organisation.organisationid
WHERE organisationid = @OrganisationID;
I am using this statement to do a databind. I am getting a error here.
Column 'OrganisationID' in where clause is ambiguous
What should I do is it wrong to name the OrganisationID in tbl_user same as tbl_organisation.
OrganisationID is a foreign key from tbl_Organisation
A: Since you have two columns with the same name on two different tables (and that's not a problem, it's even recommended on many cases), you must inform MySQL which one you want to filter by.
Add the table name (or alias, if you were using table aliases) before the column name. In your case, either
WHERE tbl_user.OrganisationID
or
WHERE tbl_Organisation.OrganisationID
should work.
A: You just need to indicate which table you are targeting with that statement, like "tbl_user.OrganisationID". Otherwise the engine doesn't know which OrganisationID you meant.
It is not wrong the have the same column names in two tables. In many (even most) cases, it is actually perferred.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse/Java equivalent to Microsoft ASP.NET Model View Control Framework Does anyone know if there is any equivalent to Microsoft's ASP.NET Model View Control Framework with Visual Studio/C# but for Eclipse with Java?
Or put it another way one could build a website in C# using MS Visual Studio with ASP.NET MVC, is there anything similar for Java using the Eclipse IDE?
I've built up good knowledge with Java and the Eclipse IDE creating some Android Apps that I'd like to leverage, now I need to turn my attention to web apps and I'd like to stick with Java and the Eclipse IDE. Cheers!
A: There are a bunch. I'd check out Play!
but there are also: Apache Wicket, Spring MVC and some others.
There is also a version of Play! for Scala which is a bonus if you intend on moving up from Java to Scala one day.
There is also a similar question with a more detailed answer here:
Choosing a Java Web Framework now?
A: Spring MVC is worth a look. Spring goes way beyond "just" MVC, with APIS for DB, JMS, and loads more, which may be a little offputting if you're just keen to get to grips with an MVC platform, but it's arguably worth it.
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
http://static.springsource.org/docs/Spring-MVC-step-by-step/
A: Tapestry or Wicket is worth trying.
A: Yes, there are a lot of them. Your problem is that there are too many, actually. Narrowing down the list can be a challenge. Everybody has their favorites (mine is Apache Tapestry, because it's actually fun to use, and very powerful).
My recommendation is to pick 3 or 4 (I'd go with Tapestry, GWT, Spring MVC and Wicket), and then spend a couple days working through the introductory tutorial that each of them offers. You'll soon know which one feels right to you, and you'll be basing your decision on your own experience rather than the strongly-worded opinions of strangers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Adding pages to the side navigation in Sharepoint I'm currently creating a site using Sharepoint, I notice when I add a page into the root it automatically adds them onto the top navigation, but I'd like to have a side navigation too (with sub pages)
Unfortunately this is quite different to any project I've worked on before, and find when compared to other CMS it is very tricky to find much information online about how to perform relatively simple tasks in Sharepoint, so I'd really appreciate any help!
Thank you
A: Check that your pages are published and approved
A: You did not state the version of SharePoint you are using, so this explanation is for SP2010:
*
*Go to Site Settings --> Navigation
There you can add/remove pages to the "global navigation" (that would be the top navigation) and the "current navigation" (that would be the side).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Best practices for managing memory in a PHP script? Memory management is not something that most PHP developers ever need to think about. I'm running into an issue where my command line script is running out of memory. It performs multiple iterations over a large array of objects, making multiple database requests per iteration. I'm sure that increasing the memory ceiling may be a short term fix, but I don't think it's an appropriate long-term solution. What should I be doing to make sure that my script is not using too much memory, and using memory efficiently?
A: The golden rule
The number one thing to do when you encounter (or expect to encounter) memory pressure is: do not read massive amounts of data in memory at once if you intend to process them sequentially.
Examples:
*
*Do not fetch a large result set in memory as an array; instead, fetch each row in turn and process it before fetching the next
*Do not read large text files in memory (e.g. with file); instead, read one line at a time
This is not always the most convenient thing in PHP (arrays don't cut it, and there is a lot of code that only works on arrays), but in recent versions and especially after the introduction of generators it's easier than ever to stream your data instead of chunking it.
Following this practice religiously will "automatically" take care of other things for you as well:
*
*There is no longer any need to clean up resources with a big memory footprint by closing them and losing all references to them on purpose, because there will be no such resources to begin with
*There is no longer a need to unset large variables after you are done with them, because there will be no such variables as well
Other things to do
*
*Be careful of creating closures inside loops; this should be easy to do, as creating such inside loops is a bad code smell. You can always lift the closure upwards and give it more parameters.
*When expecting massive input, design your program and pick algorithms accordingly. For example, you can mergesort any amount of text files of any size using a constant amount of memory.
A: You could try profiling it puting some calls to memory_get_usage(), to look for the place where it's peaking.
Of course, knowing what the code really does you'll have more information to reduce its memory usage.
A: When you compute your large array of objects, try to not compute it all at once. Walk in steps and process elements as you walk then free memory and take next elements.
It will take more time, but you can manage the amount of memory you use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: "Place Order" button on Magento onepage checkout isn't responding. (Inline JS not executing.) Currently trying to get onepage checkout working properly on an installation of Magento 1.6.0.0.
Each step works fine until the final review order box, the Place Order button gives the error review not defined, when trying to fire the review.save() OnClick event.
The following script should create this review object. It's in the same file as the button, and is called via AJAX when the user reaches the final step of the order process. If I access the file directly, this code is executed and the object created, it's only when it's pulled in by the checkout page that it doesn't run.
<script type="text/javascript">
//<![CDATA[
review = new Review('http://example.org/checkout/onepage/saveOrder/', 'http://example.org/checkout/onepage/success/', $('checkout-agreements'));
SageServer = new EbizmartsSagePaySuite.Checkout
({
'checkout': checkout,
'review': review,
'payment': payment,
'billing': billing,
'accordion': accordion
});
//]]>
</script>
I can't seem to find anyone else who's encountered this problem, every version of this code (from various different modules) does it in this manner, so I'm not sure why this JS isn't being executed.
Does anyone have any ideas?
A: We were migrating to a newer Magento version (1.8), and the "Place Order" button was not working for us as well.
Mukesh's answer pointed me to the right direction. However, the posted code was not working.
This worked for me:
review = new Review('<?php echo $this->getUrl('checkout/onepage/saveOrder', array('form_key' => Mage::getSingleton('core/session')->getFormKey())) ?>', '<?php echo $this->getUrl('checkout/onepage/success') ?>', $('checkout-agreements'));
A: Is this an upgrade? If so, try this: http://sree.cc/magento_ecommerce_tips/checkout-not-working-on-magento-version-1-4-x
Try even if it's not an upgrade. I fixed that exact same issue several times with this solution.
I would do a diff. with a software like WinMerge. Check the differences on your checkout design folders, and the base Magento one.
app/design/frontend/base/default/template/checkout
vs.
app/design/frontend/default/YOUR_THEME/template/checkout
also check the XML file:
app/design/frontend/base/default/layout/checkout.xml
vs.
app/design/frontend/default/YOUR_THEME/layout/checkout.xml
Hope this helps.
Francois
A: In app/design/frontend/mypackage/mytheme/template/checkout/onepage/review/info.phtml, I replaced & working grt.
<?php echo $this->getChildHtml('button') ?>
with
<button type="submit" title="<?php echo $this->__('Place Order') ?>" class="button btn-checkout" onclick="review.save();"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
A: I Got solution of the same Issue by followwing code, May this will help you.
Replace the base file the following path
app/design/frontend/default/your_theme/template/checkout/onepage/review/info.phtml
(or)
Replace the line number 81 in info.phtml
review = new Review(’getUrl('checkout/onepage/saveOrder', array('form_key' => Mage::getSingleton('core/session')->getFormKey())) ?>’, ‘getUrl('checkout/onepage/success') ?>’, $(’checkout-agreements’));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Problem with JSR286 rendering portlet and WebSphere Portal7 Another question for all WP7 lovers!
We have the following problem: we have creates a portal page with a JSR286 local rendering portlet that show a lotus wcm content.
When the portal render the JSR portlet, it show the following exception "Error 500: java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0"
On the IBM developerWorks, I've found this post developerWorks Thread that tell to install the IBM 7.0.0.1 Combined Cumulative Fix 004 to solve this problem IBM PM33952
Being a Combined Cumulative Fix, we've installed the Combined Cumulative Fix 007 (that containes the 004 fix)!
But after installation, the exception seems to be remained!
Have you solved this problem? What's your solution?
Thanks in advance!
A: These are most likely caused by menu or navigator components that are unable to render themselves if the resultset is zero for some reason. What you should do is to gather WCM general information mustgather and reproduce the problem in traces. Then you can see what component causes the exceptions and what was the used rendering context. Inspect the context (sitearea/content) and the component. If you can't spot anything wrong with them, please submit a PMR with the traces.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generating activation key from serial number I have devices with unique serial number (string incremetation) ex : AS1002 and AS1003.
I need to figure out an algorithm to produce a unique activation key for each serial number.
What would be the best approach for this ?
Thanks !
(This has to be done offline)
A: You have two things to consider here:
- Whatever key you generate must be able to be entered easily, so this eliminates some weird hash which may produce characters which will be cumbersome to type, although this can be overcome, it’s something you should consider.
- The operation as you stated must be done online
Firstly, there will be no way to say with absolute certainty that someone will not be able to decipher your key generation routine, no matter how much you attempt to obfuscate. Just do a search engine query for “Crack for Xyz software”.
This has been a long battle that will never end, hence the move to deliver software as services, i.e. online where the producer has more control over their content and can explicitly authorize and authenticate a user. In your case you want to do this offline. So in your scenario someone will attach your device to some system, and the accompanying software that you intend to write this routine on will make a check against the serial number of the device v/s user input.
Based on @sll’s answer, given the offline nature of your request. Your best, unfortunately would be to generate a set of random codes, and validate them when user’s call in.
Here is a method borrowed from another SO answer, I've added digits as well
private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; //Added 1-9
private string RandomString(int size)
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
So, generating one for each of your devices and storing them somewhere might be your only option because of the offline considerations.
This routine will produce strings like this when set to create a 10 digit string, which is reasonably random.
3477KXFBDQ
ROT6GRA39O
40HTLJPFCL
5M2F44M5CH
CAVAO780NR
8XBQ44WNUA
IA02WEWOCM
EG11L4OGFO
LP2UOGKKLA
H0JB0BA4NJ
KT8AN18KFA
A: Activation Key
Here is a simple structure of the activation key:
Part
Description
Data
A part of the key encrypted with a password. Contains the key expiration date and application options.
Hash
Checksum of the key expiration date, password, options and environment parameters.
Tail
The initialization vector that used to decode the data (so-called "salt").
class ActivationKey
{
public byte[] Data { get; set; } // Encrypted part.
public byte[] Hash { get; set; } // Hashed part.
public byte[] Tail { get; set; } // Initialization vector.
}
The key could represent as text format: DATA-HASH-TAIL.
For example:
KCATBZ14Y-VGDM2ZQ-ATSVYMI.
The folowing tool will use cryptographic transformations to generate and verify the key.
Generating
The algorithm for obtaining a unique activation key for a data set consists of several steps:
*
*data collection,
*getting the hash and data encryption,
*converting activation key to string.
Data collection
At this step, you need to get an array of data such as serial number, device ID, expiration date, etc. This purpose can be achieved using the following
method:
unsafe byte[] Serialize(params object[] objects)
{
using (MemoryStream memory = new MemoryStream())
using (BinaryWriter writer = new BinaryWriter(memory))
{
foreach (object obj in objects)
{
if (obj == null) continue;
switch (obj)
{
case string str:
if (str.Length > 0)
writer.Write(str.ToCharArray());
continue;
case DateTime date:
writer.Write(date.Ticks);
continue;
case bool @bool:
writer.Write(@bool);
continue;
case short @short:
writer.Write(@short);
continue;
case ushort @ushort:
writer.Write(@ushort);
continue;
case int @int:
writer.Write(@int);
continue;
case uint @uint:
writer.Write(@uint);
continue;
case long @long:
writer.Write(@long);
continue;
case ulong @ulong:
writer.Write(@ulong);
continue;
case float @float:
writer.Write(@float);
continue;
case double @double:
writer.Write(@double);
continue;
case decimal @decimal:
writer.Write(@decimal);
continue;
case byte[] buffer:
if (buffer.Length > 0)
writer.Write(buffer);
continue;
case Array array:
if (array.Length > 0)
foreach (var a in array) writer.Write(Serialize(a));
continue;
case IConvertible conv:
writer.Write(conv.ToString(CultureInfo.InvariantCulture));
continue;
case IFormattable frm:
writer.Write(frm.ToString(null, CultureInfo.InvariantCulture));
continue;
case Stream stream:
stream.CopyTo(stream);
continue;
default:
try
{
int rawsize = Marshal.SizeOf(obj);
byte[] rawdata = new byte[rawsize];
GCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned);
Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
writer.Write(rawdata);
handle.Free();
}
catch(Exception e)
{
// Place debugging tools here.
}
continue;
}
}
writer.Flush();
byte[] bytes = memory.ToArray();
return bytes;
}
}
Getting the hash and data encryption
This step contains the following substeps:
*
*create an encryption engine using a password and stores the initialization vector in the Tail property.
*next step, expiration date and options are encrypted and the encrypted data is saved into the Data property.
*finally, the hashing engine calculates a hash based on the expiration date, password, options and environment and puts it in the Hash property.
ActivationKey Create<TAlg, THash>(DateTime expirationDate,
object password,
object options = null,
params object[] environment)
where TAlg : SymmetricAlgorithm
where THash : HashAlgorithm
{
ActivationKey activationKey = new ActivationKey();
using (SymmetricAlgorithm cryptoAlg = Activator.CreateInstance<TAlg>())
{
if (password == null)
{
password = new byte[0];
}
activationKey.Tail = cryptoAlg.IV;
using (DeriveBytes deriveBytes =
new PasswordDeriveBytes(Serialize(password), activationKey.Tail))
{
cryptoAlg.Key = deriveBytes.GetBytes(cryptoAlg.KeySize / 8);
}
expirationDate = expirationDate.Date;
long expirationDateStamp = expirationDate.ToBinary();
using (ICryptoTransform transform = cryptoAlg.CreateEncryptor())
{
byte[] data = Serialize(expirationDateStamp, options);
activationKey.Data = transform.TransformFinalBlock(data, 0, data.Length);
}
using (HashAlgorithm hashAlg = Activator.CreateInstance<THash>())
{
byte[] data = Serialize(expirationDateStamp,
cryptoAlg.Key,
options,
environment,
activationKey.Tail);
activationKey.Hash = hashAlg.ComputeHash(data);
}
}
return activationKey;
}
Converting to string
Use the ToString method to get a string containing the key text, ready to be transfering to the end user.
N-based encoding (where N is the base of the number system) was often used to convert binary data into a human-readable text. The most commonly used in
activation key is base32. The advantage of this encoding is a large alphabet consisting of numbers and letters that case insensitive. The downside is that this encoding is not implemented in the .NET standard library and you should implement it yourself. You can also use the hex encoding and base64 built into mscorlib. In my example base32 is used, but I will not give its source code here. There are many examples of base32 implementation on this site.
string ToString(ActivationKey activationKey)
{
if (activationKey.Data == null
|| activationKey.Hash == null
|| activationKey.Tail == null)
{
return string.Empty;
}
using (Base32 base32 = new Base32())
{
return base32.Encode(activationKey.Data)
+ "-" + base32.Encode(activationKey.Hash)
+ "-" + base32.Encode(activationKey.Tail);
}
}
To restore use the folowing method:
ActivationKey Parse(string text)
{
ActivationKey activationKey;
string[] items = text.Split('-');
if (items.Length >= 3)
{
using (Base32 base32 = new Base32())
{
activationKey.Data = base32.Decode(items[0]);
activationKey.Hash = base32.Decode(items[1]);
activationKey.Tail = base32.Decode(items[2]);
}
}
return activationKey;
}
Checking
Key verification is carried out using methodes GetOptions an Verify.
*
*GetOptions checks the key and restores embeded data as byte array or null if key is not valid.
*Verify just checks the key.
byte[] GetOptions<TAlg, THash>(object password = null, params object[] environment)
where TAlg : SymmetricAlgorithm
where THash : HashAlgorithm
{
if (Data == null || Hash == null || Tail == null)
{
return null;
}
try
{
using (SymmetricAlgorithm cryptoAlg = Activator.CreateInstance<TAlg>())
{
cryptoAlg.IV = Tail;
using (DeriveBytes deriveBytes =
new PasswordDeriveBytes(Serialize(password), Tail))
{
cryptoAlg.Key = deriveBytes.GetBytes(cryptoAlg.KeySize / 8);
}
using (ICryptoTransform transform = cryptoAlg.CreateDecryptor())
{
byte[] data = transform.TransformFinalBlock(Data, 0, Data.Length);
int optionsLength = data.Length - 8;
if (optionsLength < 0)
{
return null;
}
byte[] options;
if (optionsLength > 0)
{
options = new byte[optionsLength];
Buffer.BlockCopy(data, 8, options, 0, optionsLength);
}
else
{
options = new byte[0];
}
long expirationDateStamp = BitConverter.ToInt64(data, 0);
DateTime expirationDate = DateTime.FromBinary(expirationDateStamp);
if (expirationDate < DateTime.Today)
{
return null;
}
using (HashAlgorithm hashAlg =
Activator.CreateInstance<THash>())
{
byte[] hash =
hashAlg.ComputeHash(
Serialize(expirationDateStamp,
cryptoAlg.Key,
options,
environment,
Tail));
return ByteArrayEquals(Hash, hash) ? options : null;
}
}
}
}
catch
{
return null;
}
}
bool Verify<TAlg, THash>(object password = null, params object[] environment)
where TAlg : SymmetricAlgorithm
where THash : HashAlgorithm
{
try
{
byte[] key = Serialize(password);
return Verify<TAlg, THash>(key, environment);
}
catch
{
return false;
}
}
Example
Here is a full example of generating the activation key using your own combination of any amount of data - text, strings, numbers, bytes, etc.
Example of usage:
string serialNumber = "0123456789"; // The serial number.
const string appName = "myAppName"; // The application name.
// Generating the key. All the parameters passed to the costructor can be omitted.
ActivationKey activationKey = new ActivationKey(
//expirationDate:
DateTime.Now.AddMonths(1), // Expiration date 1 month later.
// Pass DateTime.Max for unlimited use.
//password:
null, // Password protection;
// this parameter can be null.
//options:
null // Pass here numbers, flags, text or other
// that you want to restore
// or null if no necessary.
//environment:
appName, serialNumber // Application name and serial number.
);
// Thus, a simple check of the key for validity is carried out.
bool checkKey = activationKey.Verify((byte[])null, appName, serialNumber);
if (!checkKey)
{
MessageBox.Show("Your copy is not activated! Please get a valid activation key.");
Application.Exit();
}
A: If your device has some secured memory which can not be read by connecting an programmator or an other device -you can store some key-code and then use any hashing algorithm like MD5 or SHA-1/2 to generate hash by:
HASH(PUBLIC_SERIALNUMBER + PRIVATE_KEYCODE)
And pairs of SERIALNUMBER + KEYCODE should be stored in local DB.
In this way: (offline)
*
*Client calling you and asking for the Activation Code
*You asking for a SERIALNUMBER of particular device
*Then you search for a KEYCODE by a given SERIALNUMBER in your local DB and generate Activation Code (even using MD5 this will be sacure as long KEYCODE is privately stored in your DB)
*Client enter Activation Code into the device, device able to generate hash
by own SERIALNUMBER and KEYCODE and then compare to Activation Code entered by user
This could be simplified by storing activation code itself if device has a secured memory onboard (like SmartCards has). In this way you can just keep own database of SerialCode - ActivationCode pairs.
A: By far the most secure way to do it is to have a centralized database of (serial number, activation key) pairs and have the user activate over the internet so you can check the key locally (on the server).
In this implementation, the activation key can be completely random since it doesn't need to depend on the serial number.
A: You want it to be easy to check, and hard to "go backwards". You'll see a lot of suggestions for using hashing functions, those functions are easy to go one way, but hard to go backwards. Previously, I phrased that as "it is easy to turn a cow into a hamburger, but hard to turn a hamburger into a cow". In this case, a device should know its own serial number and be able to "add" (or append) some secret (usually called "salt") to the serial and then hash or encrypt it.
If you are using reversible encryption, you want to add some sort of "check digit" to the serial numbers so that if someone does figure your encryption scheme out, there is another layer for them to figure out.
An example of a function that is easy enough to "go backwards" was one I solved with Excel while trying to avoid homework.
And you probably want to make things easier for your customers by making the encoding less likely to be messed up when the activation codes are handwritten (such as you write it down from the email then walk over to where the device is and punch the letters/digits in). In many fonts, I and 1, and 0 and O are similar enough that many encodings, such as your car's VIN do not use the letters i and o (and I remember older typewriters that lacked a key for the digit 1 because you were expected to use lowercase L). In such cases, Y, 4 and 7 can appear the same depending on some handwriting. So know your audience and what are their limits.
A: How about: Invent a password that is not revealed to the user. Then concatenate this password with the serial number and hash the combination.
Anything you do can be broken by a dedicated enough hacker. The question is not, "Can I create absolutely unbreakable security?" but "Can I create security good enough to protect against unskilled hackers and to make it not worth the effort for the skilled hackers?" If you reasonably expect to sell 10 million copies of your product, you'll be a big target and there may be lots of hackers out there who will try to break it. If you expect to sell a few hundred or maybe a few thousand copies, not so much.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: get absolute path to apache webcontents folder from a java class file Need to get absolute path in java class file, inside a dynamic web application...
*
*Actually i need to get path of apache webapps folder... where the webapps are deployed
*e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg
*Need to get this in a java class file, not on jsp page or any view page...
any ideas?
A: If you have a javax.servlet.ServletContext you can call:
servletContext.getRealPath("/images/imagetosave.jpg")
to get the actual path of where the image is stored.
ServletContext can be accessed from a javax.servlet.http.HttpSession.
However, you might want to look into using:
servletContext.getResource("/images/imagetosave.jpg")
or
servletContext.getResourceAsStream("/images/imagetosave.jpg")
A: String path = MyClass.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
This should return your absolute path based on the class's file location.
A: Method -1 :
//step1 : import java.net.InetAddress;
InetAddress ip = InetAddress.getLocalHost();
//step2 : provide your file path
String filepath="GIVE YOUR FILE PATH AFTER WEB FOLDER something like /images/grid.png"
//step3 : grab all peices together
String a ="http://"+ip.getHostAddress()+":"+request.getLocalPort()+""+request.getServletContext().getContextPath()+filepath;
Method - 2 :
//Step : 1-get the absolute url
String path = request.getRequestURL().toString();
//Step : 2-then sub string it with the context path
path = path.substring(0, path.indexOf(request.getContextPath()));
//step : 3-provide your file path after web folder
String finalPath = "GIVE YOUR FILE PATH AFTER WEB FOLDER something like /images/grid.png"
path +=finalPath;
MY SUGGESTION
*
*keep the file which you want to open in the default package of your source folder and open the file directly to make things simple and clear.
NOTE : this happens because it is present in the class path of your IDE if you are coding without IDE then keep it in the place of your java compiled class file or in a common folder which you can access.
HAVE FUN
A:
Actually i need to get path of apache webapps folder... where the webapps are deployed
e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg
As mentioned by many other answers, you can just use ServletContext#getRealPath() to convert a relative web content path to an absolute disk file system path, so that you could use it further in File or FileInputStream. The ServletContext is in servlets available by the inherited getServletContext() method:
String relativeWebPath = "/images";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath, "imagetosave.jpg");
// ...
However, the filename "imagetosave.jpg" indicates that you're attempting to store an uploaded image by FileOutputStream. The public webcontent folder is the wrong place to store uploaded images! They will all get lost whenever the webapp get redeployed or even when the server get restarted with a cleanup. The simple reason is that the uploaded images are not contained in the to-be-deployed WAR file at all.
You should definitely look for another location outside the webapp deploy folder as a more permanent storage of uploaded images, so that it will remain intact across multiple deployments/restarts. Best way is to prepare a fixed local disk file system folder such as /var/webapp/uploads and provide this as some configuration setting. Finally just store the image in there.
String uploadsFolder = getItFromConfigurationFileSomehow(); // "/var/webapp/uploads"
File file = new File(uploadsFolder, "imagetosave.jpg");
// ...
See also:
*
*What does servletcontext.getRealPath("/") mean and when should I use it
*Where to place and how to read configuration resource files in servlet based application?
*Simplest way to serve static data from outside the application server in a Java web application
A: I was able to get a reference to the ServletContext in a Filter. What I like best about this approach is that it occurs in the init() method which is called upon the first load the web application meaning the execution only happens once.
public class MyFilter implements Filter {
protected FilterConfig filterConfig;
public void init(FilterConfig filterConfig) {
String templatePath = filterConfig.getServletContext().getRealPath(filterConfig.getInitParameter("templatepath"));
Utilities.setTemplatePath(templatePath);
this.filterConfig = filterConfig;
}
I added the "templatepath" to the filterConfig via the web.xml:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.myapp.servlet.MyFilter</filter-class>
<init-param>
<param-name>templatepath</param-name>
<param-value>/templates</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
A: You can get path in controller:
public class MyController extends MultiActionController {
private String realPath;
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
realPath = getServletContext().getRealPath("/");
String classPath = realPath + "WEB-INF/classes/" + MyClass.ServletContextUtil.class.getCanonicalName().replaceAll("\\.", "/") + ".java";
// add any code
}
A: You could write a ServletContextListener:
public class MyServletContextListener implements ServletContextListener
{
public void contextInitializedImpl(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
String contextpath = servletContext.getRealPath("/");
// Provide the path to your backend software that needs it
}
//...
}
and configure it in web.xml
<listener>
<listener-class>my.package.MyServletContextListener</listener-class>
</listener>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: WCF - Streaming file upload over http I am trying to build a WCF service that will allow my WPF desktop clients to upload files to a server.
I adapted a code sample from The Code Project (WCF Streaming: Upload/Download Files Over HTTP) and I've looked at several SO posts as well, but can't seem to get this working.
When I execute the code, it fails with a null reference exception at the point that the server tries to read the stream that has been passed through the interface.
At this point, I am rather lost and don't know how to fix this up. Any suggestions are appreciated.
Code samples follow:
CustomerDocumentModel is the data element that I pass through the WCF interface with the stream to read the client side file:
[DataContract]
[KnownType(typeof(System.IO.FileStream))]
public class CustomerDocumentModel : IDisposable
{
public CustomerDocumentModel()
{
}
public CustomerDocumentModel(string documentName, string path)
{
DocumentName = documentName;
Path = path;
}
[DataMember]
public string DocumentName;
[DataMember]
public string Path;
[DataMember]
public System.IO.Stream FileByteStream;
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
IBillingService is the interface definition for my WCF service:
[ServiceContract]
public interface IBillingService
{
// other methods redacted...
[OperationContract]
void UploadCustomerDocument(CustomerDocumentModel model);
}
The class BillingService implements the WCF service:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class BillingService : IBillingService
{
// Other methods redacted ...
public void UploadCustomerDocument(CustomerDocumentModel model)
{
string path = HttpContext.Current.Server.MapPath(
String.Format("/Documents/{1}",
model.DocumentName));
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int size = 0;
try
{
// The following Read() fails with a NullReferenceException
while ((size = model.FileByteStream.Read(buffer, 0, bufferSize)) > 0)
{
stream.Write(buffer, 0, size);
}
}
catch
{
throw;
}
finally
{
stream.Close();
model.FileByteStream.Close();
}
}
}
}
A few relevant bits from the web.config on my WCF web server:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="360"/>
</system.web>
<system.serviceModel>
<serviceHostingEnvironment
aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="userHttps" transferMode="Streamed" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
The client is a WPF/MVVM app that creates a CustomerDocumentModel model, uses an OpenFileDialog to Open() the file stream and then passes the model to the UploadCustomerDocument method on WCF Service.
If I am missing any relevant details, please ask.
A: I know this rather very late reply for your question and I'm sure you must have resolved your problem as well. This could be helpful to someone else :-)
Use Messagecontract over Datacontract and only one MessageBodyMember with datatype Stream and rest all parameter are MessageHeader.
Here is the example:
[MessageContract]
public class CustomerDocumentModel : IDisposable
{
public CustomerDocumentModel(string documentName, string path)
{
DocumentName = documentName;
Path = path;
}
[MessageHeader]
public string DocumentName{get;set;}
[MessageHeader]
public string Path{get;set;}
[MessageBodyMember]
public System.IO.Stream FileByteStream{get;set;}
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
Note: Make sure your in your configuration transfer mode is StreamedResponse, also you may want to change the MessageEncoding to MTOM for better performance.
public void UploadCustomerDocument(CustomerDocumentModel model)
{
var filename = //your file name and path;
using (var fs = new FileStream(filename, FileMode.Create))
{
model.FileByteStream.CopyTo(fs);
}
}
A: Your data type is what is making the streaming fail. This is documented on MSDN here: http://msdn.microsoft.com/en-us/library/ms731913.aspx
The relevant passage is:
Restrictions on Streamed Transfers
Using the streamed transfer mode causes the run time to enforce
additional restrictions.
Operations that occur across a streamed transport can have a contract
with at most one input or output parameter. That parameter corresponds
to the entire body of the message and must be a Message, a derived
type of Stream, or an IXmlSerializable implementation. Having a return
value for an operation is equivalent to having an output parameter.
Some WCF features, such as reliable messaging, transactions, and SOAP
message-level security, rely on buffering messages for transmissions.
Using these features may reduce or eliminate the performance benefits
gained by using streaming. To secure a streamed transport, use
transport-level security only or use transport-level security plus
authentication-only message security.
SOAP headers are always buffered, even when the transfer mode is set
to streamed. The headers for a message must not exceed the size of the
MaxBufferSize transport quota. For more information about this
setting, see Transport Quotas.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What PHP chunk of code is FASTER? We all know that xHTML/CSS and JS minification and compression benefits large traffic sites.
Take a look at the following code:
include("template.funcs.php");
include("country-redirect.php");
if(($country=='PL')||($country=='POL'))
{
header('Location: index_pol.php');
exit();
}
$include_path = './global_php/';
$page = "couture";
include $include_path."shop.inc.php";
$movie_num = 1 ;
Now see the minifed version:
include("template.funcs.php");include("country-redirect.php");
if(($country=='PL')||($country=='POL')){header('Location: index_pol.php');
exit();}
$include_path='./global_php/';$page="couture";include $include_path."shop.inc.php";
$movie_num=1;
Which one do you think is faster - in general, I want to start also minifying my programming too, small var and string names like $a rather than $apple and trying to remove as much extra character as possible. Will the PHP Compiler like a compressed chunk or spaced out one?
A: PHP code stays on the server, so it's size is essentially irrelevant.
Removing those newlines is a really bad idea. Make your code readable for humans.
A: PHP doesn't care if your code is minified or not.
Write code so you can edit it cleanly later. Minification has no measurable impact on performance.
The reason that you see minified CSS/JavaScript is not for parsing/execution speed... it is for cutting down the file size for data transfer. Your PHP is processed server-side. The only thing that is sent is the output of your code.
A:
Will the PHP Compiler like a compressed chunk or spaced out one?
It does not matter. Any difference between these will be in the microseconds at best.
Making code readable is the only thing that matters.
A: The minified version won't be faster for 2 reasons:
*
*The script is not sent to the client, but interpreted, and then the result
is sent
*Minifying a php script has very little impact on performance
If you want to seed up your php code, you can install a php accelerator
A: As others have said, minification of PHP code will make no real difference in execution speed. That is the answer to your question, but I think that this quote is also relevant:
Always code as if the guy who ends up maintaining your code will be a
violent psychopath who knows where you live.
Please don't minfiy the primary version of your code. Please don't use variable names like $a instead of $apple. The ability to read and understand your code is far more valuable than any space savings or marginal speed increase that you may get from minification.
A: Well, when the PHP engine parser does its magic on your code it automatically removes all white space and comments any ways. The difference would be maybe 1/10 of a second if you start getting up in the megabytes worth of text. But this is simply the webserver parsing the files.
If you want real over head ideas search Google for "Best PHP Practices" and get into good habits. I can see from your above snippet you might need some. Just some advice.
A: This really doesn't matter, as it's not transfered by internet to the client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it ok to store plugin DLLs in a /Plugin folder instead of /Bin? I have a pretty straightforward question.
Is it ok to store plugin DLLs in a /Plugin folder instead of /Bin? I'm experimenting with plugin design in the context of ASP.NET WebForms (and MVC) and I am wondering if there could be an issue with storing plugin DLLs in a /Plugin folder instead of the /Bin folder.
Thanks for any help.
Update
I'm coming at this from the perspective of this article: http://www.c-sharpcorner.com/UploadFile/40e97e/7192/.
I am going to load plugins using Reflection.
Sample Code:
public class PluginLoader
{
public static IList<IPlugin> Load(string folder)
{
IList<IPlugin> plugins = new List<IPlugin>();
// Get files in folder
string[] files = Directory.GetFiles(folder, "*.plug.dll");
foreach(string file in files)
{
Assembly assembly = Assembly.LoadFile(file);
var types = assembly.GetExportedTypes();
foreach (Type type in types)
{
if (type.GetInterfaces().Contains(typeof(IPlugin)))
{
object instance = Activator.CreateInstance(type);
plugins.Add(instance as IPlugin);
}
}
}
return plugins;
}
}
A: The only thing you generally need to watch for is when you are trying to use types from those plugin assemblies in your views (or pages), they'll likely fail to resolve at runtime. This is due to the nature of the dynamic compilation model ASP.NET uses for non-precompiled applications.
Essentially, your views (and pages) will be dynamically compiled by the ASP.NET runtime, not a compile time, so when the assembly binder attempts to resolve those types, because they are not in the default bin location, it won't find them. A simple easy fix would be to use AppDomain.CurrentDomain.AppendPrivatePath, passing in the path of your plugins folder, e.g. Server.MapPath("~/plugins")
The method itself is marked as obselete and might be removed in future versions of the framework, (as generally you would configure the probing path through AppDomainSetup), but it does work.
If at all you are unhappy about this approach, you could always deploy your plugin assemblies within your bin directory instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Duplicate Hierarchical Data to the same table - Oracle How to duplicate hierarchical data to insert them at the same table, generating new Ids but keeping parent-child relationship
A: Re-insert the data but add the same large number to every ID.
Update:
If I understand your problem correctly, you want to copy data like this:
EMPLOYEE_ID MANAGER_ID
1 <null>
2 1
3 1
4 3
In this case, just adding 4 to every parent and child ID will create new rows but have the same relationships:
EMPLOYEE_ID MANAGER_ID
5 <null>
6 5
7 5
8 8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Drupal render() forcing other divs closed? I'm new to Drupal theming and am attempting to create a custom theme template for a specific content type I have.
I am attempting the following:
<div<?php print $content_attributes; ?>>
<?php print render($content['field_property_media']); ?>
<div class="field-label-above property-information">
<div class="field-label">Property Information</div>
<?php print render($content['address']); ?>
</div>
</div>
However, when the content actually render the address portion gets booted out of its parent div and looks like this:
<div class="field-label-above property-information">
<div class="field-label">Property Information</div>
</div>
<div class="field field-name-field-property-address field-type-addressfield field-label-inline clearfix"><div class="field-label">Address: </div><div class="field-items"><div class="field-item even"><div class="street-block"><div class="thoroughfare">55 Duchess Ave</div></div><div class="addressfield-container-inline locality-block"><span class="locality">London</span> <span class="state">Ontario</span> <span class="postal-code">N6C 1N3</span></div><span class="country">Canada</span></div></div></div>
I can't figure out why this is happening or what the solution is to keep the address within the div I manually created.
Thoughts?
A: The only possible way this could happen is if you've got a custom or contributed module intercepting your template file and changing it, or if you have some javascript enabled that's moving the <div> out of it's container. Drupal does absolutely no re-ordering of content when it processes a template file so it can't be anything in Drupal core that's causing the problem.
If the <div> is just displaying outside the container (i.e. it's inside when you inspect the source code) then you're probably just facing a floating issue; just add the clearfix class to the containing element.
EDIT
Just a thought, have you cleared your cache since you added the template file? If not, do that, it won't be picked up until the caches are cleared.
Also if this is a custom node template (i.e. node--page.tpl.php), make sure you've also copied node.tpl.php to your theme's folder. Then clear your cache again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Public accessors vs public properties of a class
Possible Duplicate:
What is the difference between a field and a property in C#
Can someone explain the diffrence if any between these two properties?
public string City { get; set; }
public string City;
A: The first one is an actual property. The second one is just a field.
Generally speaking, fields should be kept private and are what store actual data. Properties don't actually store any data, but they point to fields. In the case of the auto-property above, it will auto-generate a hidden field like _city behind the scenes to hold the data.
Hope this helps!
A: First one is CLR property, while the second is just public field (not a property).
In WPF and Silverlight, binding doesn't work with public fields, it works only with public properties. That is one major difference in my opinion:
//<!--Assume Field is a public field, and Property is a public property-->
<TextBlock Text="{Binding Field}"/>
<TextBlock Text="{Binding Property}"/>
First one wouldn't work but the second one would work.
A: as mellamokb said. the first type is Property,the compiler will auto-generate access function and private field like:
private String _city;
public String City(){ return _city ;}
.....
use Properties,you can control the access of _city,for example"
public String City(){
doXxxFunction();
return _city ;
}
so,you should always use the property,and make sure all field is private.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7517413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.