text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: is possible write/read a file using a string data type structure? for write something in a file i use for example this code:
procedure MyProc (... );
const
BufSize = 65535;
var
FileSrc, FileDst: TFileStream;
StreamRead: Cardinal;
InBuf, OutBuf: Array [0..bufsize] of byte;
begin
.....
FileSrc := TFileStream.Create (uFileSrc, fmOpenRead Or fmShareDenyWrite);
try
FileDst := TFileStream.Create (uFileTmp, fmCreate);
try
StreamRead := 0;
while ((iCounter < iFileSize) or (StreamRead = Cardinal(BufSize)))
begin
StreamRead := FileSrc.Read (InBuf, BufSize);
Inc (iCounter, StreamRead);
end;
finally
FileDst.Free;
end;
finally
FileSrc.Free;
end;
end;
And for I/O file i use a array of byte, and so is all ok, but when i use a string, for example declaring:
InBuf, OutBuf: string // in delphi xe2 = unicode string
then not work. In sense that file not write nothing. I have understood why, or just think to have understood it.
I think that problem maybe is why string contain just a pointer to memory and not static structure; correct?
In this case, there is some solution for solve it? In sense, is possible to do something for i can to write a file using string and not vector? Or i need necessary use a vector?
If possible, can i can to do ?
Thanks very much.
A: There are two issues with using strings. First of all you want to use RawByteString so that you ensure the use of byte sized character elements – a Unicode string has elements that are two bytes wide. And secondly you need to dereference the string which is really just a pointer.
But I wonder why you would prefer strings to the stack allocated byte array.
procedure MyProc (... );
const
BufSize = 65536;
var
FileSrc, FileDst: TFileStream;
StreamRead: Cardinal;
InBuf: RawByteString;
begin
.....
FileSrc := TFileStream.Create (uFileSrc, fmOpenRead Or fmShareDenyWrite);
try
FileDst := TFileStream.Create (uFileTmp, fmCreate);
try
SetLength(InBuf, BufSize);
StreamRead := 0;
while ((iCounter < iFileSize) or (StreamRead = Cardinal(BufSize)))
begin
StreamRead := FileSrc.Read (InBuf[1], BufSize);
Inc (iCounter, StreamRead);
end;
finally
FileDst.Free;
end;
finally
FileSrc.Free;
end;
end;
Note: Your previous code declared a buffer of 65536 bytes, but you only ever used 65535 of them. Probably not what you intended.
A: To use a string as a buffer (which I would not recommend), you'll have to use SetLength to allocate the internal buffer, and you'll have to pass InBuf[1] and OutBuf[1] as the data to read or write.
var
InBuf, OutBuf: AnsiString; // or TBytes
begin
SetLength(InBuf, BufSize);
SetLength(OutBuf, BufSize);
...
StreamRead := FileSrc.Read(InBuf[1], BufSize); // if TBytes, use InBuf[0]
// etc...
You can also use a TBytes, instead of an AnsiString. The usage remains the same.
But I actually see no advantage in dynamically allocating TBytes, AnsiStrings or RawByteStrings here. I'd rather do what you already do: use a stack based buffer. I would perhaps make it a little smaller in a multi-threaded environment.
A: Yes, you can save / load strings to / from stream, see the following example
var Len: Integer;
buf: string;
FData: TStream;
// save string to stream
// save the length of the string
Len := Length(buf);
FData.Write(Len, SizeOf(Len));
// save string itself
if(Len > 0)then FData.Write(buf[1], Len * sizeof(buf[1]));
// read string from stream
// read the length of the string
FData.Read(Len, SizeOf(Len));
if(Len > 0)then begin
// get memory for the string
SetLength(buf, Len);
// read string content
FData.Read(buf[1], Len * sizeof(buf[1]));
end else buf := '';
A: On a related note, to copy the contents from one TStream to another TStream, you could just use the TStream.CopyFrom() method instead:
procedure MyProc (... );
var
FileSrc, FileDst: TFileStream;
begin
...
FileSrc := TFileStream.Create (uFileSrc, fmOpenRead Or fmShareDenyWrite);
try
FileDst := TFileStream.Create (uFileTmp, fmCreate);
try
FileDst.CopyFrom(FileSrc, 0); // or FileDst.CopyFrom(FileSrc, iFileSize)
finally
FileDst.Free;
end;
finally
FileSrc.Free;
end;
...
end;
Which can be simplified by calling CopyFile() instead:
procedure MyProc (... );
begin
...
CopyFile(PChar(uFileSrc), PChar(uFileTmp), False);
...
end;
Either way, you don't have to worry about read/writing the file data manually at all!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java - Generically handling the creation of subclasses I have three classes that are quite similar, excepting a single method. Therefore, I chose to put the rest of their functionality into an abstract superclass. When it comes to creating instances of these classes, however, I'm at a loss for how to implement what seems to me like the "obvious" or "elegant" approach. Their constructors are essentially identical, and I need multiple instances of each, so I wanted to do something like the following:
private SubclassA[] subclassA_array, SubclassB[] subclassB_array, SubclassC[] subclassC_array;
subclassA_array = new SubclassA[getNumInstancesOfClassANeeded()]
subclassB_array = new SubclassA[getNumInstancesOfClassBNeeded()]
subclassC_array = new SubclassA[getNumInstancesOfClassCNeeded()]
// might have my syntax wrong here; array of the three subclass arrays
private Superclass[][] superArray = new Superclass[][3];
superArray[0] = subclassA_array;
superArray[1] = subclassA_array;
superArray[2] = subclassA_array;
for ( Superclass[] array: superArray )
for(int i = 0; i< array.length; i++)
// array[i] = new..... what goes here?
}
}
How would I find the appropriate class to construct in that innermost loop? Is this actually a really oddball way of approaching the problem; have I missed something more obvious? Should I just say "to hell with it!" and just have three separate loops?
A:
Should I just say "to hell with it!" and just have three separate loops?
IMO, yes.
You could do the following:
*
*Use array.getClass() to get the class of the array,
*Use getConmponentType() to get the array's base type
*Use newInstance() to create an instance
*Assign the instance reference to the array.
... but this results in fragile code and is like using a sledge-hammer to crack a walnut.
A: You could work with reflection in your inner loop, something like array.getClass().getComponentType().newInstance(), but I think there might be better solutions to the overall problem (To answer that, I'd need more information about what you want to code)
A: You can create an static method
public static subclassA[] getNewInstances(int numberOfInstances);
static methods can be accessed without the need to create a new instance SubclassA.getNewInstances(3).
In your definition of the matrix, you need to define first the first dimension (so it becomes new Superclass[3][]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I pass query parameters on in the MVC default route? I have an MVC2 project where I want the default route to pass on query parameteres to the default action.
Right now I have a route like this
routes.MapRoute(
"Default", // Route name
"", // URL pattern
new { controller = "Search", action = "Index" }
);
If I now go to http://mysite, that is correctly routed to the Index action on the Search controller, but if enter http://mysite?theme=yellow, then the theme parameter is not passed to the same action.
How can I make a default route that passes on any given query parameter?
A: routing has nothing to do with query parameters. They will be accessible from the controller that matches the url pattern.
so, "{controller}/{action}/{id}", // URL pattern should suffice
and in the controller you can get to query parameters through the Request property:
var theme = Request["theme"];
or you can be explicit if you want to:
var theme = Request.QueryString["theme"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Paypal Hidden variables doesn't work
Possible Duplicate:
Variables upon submitting Paypal form
//Buy.php
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="hosted_button_id" value="EWE57TOG6A1GO">
<input type="hidden" name="user_id" value="12345">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
</form>
After the successful payment.
You'll be redirected to
www.thankyou.com/thankyou.phptx=2TB90771KK039521H&st=Completed&amt=1.00&cc=PHP&cm=&item_number=11
//Thankyou.php
<?php
extract($_REQUEST);
echo $user_id;
?>
I am trying to print the user_id but it is empty.
So my Question is:
1) How can I send variable from my site to paypal? (talking about the user_id)
2) How to get the value of that user_id when redirected to thankyou.php?
Thanks in ADVANCE!
A: Try this. It worked for me when I implemented PayPal.
<?php
$user_id = $_REQUEST['user_id'];
echo $user_id;
?>
Slight edit: The array parameter should be in quotes and the double quotes are unnecessary in the echo statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scala: filtering a collection of Options Say I have a function that checks whether some operation is applicable to an instance of A and, if so, returns an instance of B or None:
def checker[A,B]( a: A ) : Option[B] = ...
Now I want to form a new collection that contains all valid instances of B, dropping the None values. The following code seems to do the job, but there is certainly a better way:
val as = List[A]( a1, a2, a3, ... )
val bs =
as
.map( (a) => checker(a) ) // List[A] => List[Option[B]]
.filter( _.isDefined ) // List[Option[B]] => List[Option[B]]
.map( _.get ) // List[Option[B]] => List[B]
A: This should do it:
val bs = as.flatMap(checker)
A: The answer above is correct, but if you can rewrite checker, I suggest you use PartialFunction and collect. PartialFunction is a function of type A=>B that is not necessary defined for all values of A. Here is a simple example:
scala> List(1, 2, 3, 4, "5") collect {case x : Int => x + 42}
res1: List[Int] = List(43, 44, 45, 46)
collect takes an instance of PartialFunction as argument and applies it to all elements of the collection. In our case the function is defined only for Ints and "5" is filtered. So, collect is a combination of map and filter, which is exactly your case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: how to show pdf in android emulator i want to show pdf in emulator.the following code i use.
public class PdfActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
URL url;
Button btn;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.setProperty("http.proxyHost","192.168.0.2");
System.setProperty("http.proxyPort","8080");
btn=(Button)findViewById(R.id.press);
try
{
//url=new URL("http://litofinter.es.milfoil.arvixe.com/PDF/Book6.pdf");
}catch(Exception e)
{
e.printStackTrace();
}
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Uri uri = Uri.parse("http://litofinter.es.milfoil.arvixe.com/PDF/Book6.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
But it show me errors that is my logcat-
09-28 13:16:24.697: ERROR/WindowManager(283): Activity com.android.browser.BrowserActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f601d8 that was originally added here
09-28 13:16:24.697: ERROR/WindowManager(283): android.view.WindowLeaked: Activity com.android.browser.BrowserActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f601d8 that was originally added here
09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.ViewRoot.<init>(ViewRoot.java:247)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.view.Window$LocalWindowManager.addView(Window.java:424)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.app.Dialog.show(Dialog.java:241)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.browser.BrowserActivity.onDownloadStartNoStream(BrowserActivity.java:2871)
09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.browser.BrowserActivity.onDownloadStart(BrowserActivity.java:2808)
09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.browser.Tab$4.onDownloadStart(Tab.java:1306)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:387)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.os.Handler.dispatchMessage(Handler.java:99)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.os.Looper.loop(Looper.java:123)
09-28 13:16:24.697: ERROR/WindowManager(283): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-28 13:16:24.697: ERROR/WindowManager(283): at java.lang.reflect.Method.invokeNative(Native Method)
09-28 13:16:24.697: ERROR/WindowManager(283): at java.lang.reflect.Method.invoke(Method.java:521)
09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-28 13:16:24.697: ERROR/WindowManager(283): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-28 13:16:24.697: ERROR/WindowManager(283): at dalvik.system.NativeStart.main(Native Method)
A: There is no easy way to do it:
Render a PDF file using Java on Android
A: you want to open a pdf which is present on this location http://litofinter.es.milfoil.arvixe.com/PDF/Book6.pdf
So basically you want to show a html page so use webview.
A: If you want to open pdf in android app try using google docs-
String pdfurl = "http://www.example.com/yourfile.pdf";
String googleDocsUrl = "http://docs.google.com/viewer?url="+pdfurl;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(googleDocsUrl ), "text/html");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to clone a Java object with the clone() method I don't understand the mechanism of cloning custom object. For example:
public class Main{
public static void main(String [] args) {
Person person = new Person();
person.setFname("Bill");
person.setLname("Hook");
Person cloned = (Person)person.clone();
System.out.println(cloned.getFname() + " " + cloned.getLname());
}
}
class Person implements Cloneable{
private String fname;
private String lname;
public Object clone() {
Person person = new Person();
person.setFname(this.fname);
person.setLname(this.lname);
return person;
}
public void setFname(String fname) {
this.fname = fname;
}
public void setLname(String lname){
this.lname = lname;
}
public String getFname(){
return fname;
}
public String getLname() {
return lname;
}
}
This is example shows right way of cloning as a in the books write. But I can delete implements Cloneable in the class name definition and I receive the same result.
So I don't understand the proposing of Cloneable and why clone() method is defined in class Object?
A: The clone() in class Object does a shallow copy of the memory instead of calling methods like the constructor. In order to call clone() on any object that doesn't implement clone() itself, you need to implement the Clonable interface.
If you override the clone() method you don't have to implement that interface.
Just as the JavaDoc says, this would result in an exception:
class A {
private StringBuilder sb; //just some arbitrary member
}
...
new A().clone(); //this will result in an exception, since A does neither implement Clonable nor override clone()
If A in the example would implement Clonable calling clone() (the Object version) would result in a new A instance that references the very same StringBuilder, i.e. changes to sb in the cloned instance would result in changes to the sb in the original A instance.
That's meant with a shallow copy and that one reason why it is generally better to override clone().
Edit: just as a sidenote, using return type covariance would make your overridden clone() more explicit:
public Person clone() {
...
}
A: The JVM is able to clone the object for you, and you're thus not supposed to construct a new person by yourself. Just use this code:
class Person implements Cloneable {
// ...
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
or
class Person implements Cloneable {
// ...
@Override
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new Error("Something impossible just happened");
}
}
}
This will work even if the Person class is subclassed, whereas your clone implementation will always create an instance of Person (and not an instance of Employee for an Employee, for example).
A: The clone method is meant to make a deep copy. Make sure you understand the difference between deep and shallow copies. In your case a copy constructor may be the pattern you want. In some cases you can't use this pattern however, for example because you're subclassing class X and you don't have access to the constructor of X that you need. If X overrides its clone method correctly (if necessary) then you could make a copy in the following way:
class Y extends X implements Cloneable {
private SomeType field; // a field that needs copying in order to get a deep copy of a Y object
...
@Override
public Y clone() {
final Y clone;
try {
clone = (Y) super.clone();
}
catch (CloneNotSupportedException ex) {
throw new RuntimeException("superclass messed up", ex);
}
clone.field = this.field.clone();
return clone;
}
}
In general when overriding your clone method:
*
*Make the return type more specific
*Start with calling super.clone()
*Do not include throws clause when you know clone() will also work for any subclass (weakness of the clone-pattern; make class final if possible)
*Leave immutable and primitive fields alone, but clone mutable object fields manually after the call to super.clone() (another weakness of the clone-pattern, since these fields cannot be made final)
The clone() method of Object (which will eventually be called when all superclasses obey the contract) makes a shallow copy and takes care of the correct runtime type of the new object. Note how no constructor is called in the entire process.
If you want to be able to call clone() on instances, then implement the Cloneable interface and make the method public. If you don't want to be able to call it on instances, but you do want to make sure subclasses can call their super.clone() and get what they need, then don't implement Cloneable and keep the method protected if your superclass hasn't declared it public already.
The clone pattern is difficult and has a lot of pitfalls. Be sure it's what you need. Consider copy constructors, or a static factory method.
A: There's no need to create the object explicitly here in clone() method. Just by calling super.clone() will create the copy of this object. It will perform the shallow clone.
A: clone is not mature as Joshua bloch say:
http://www.artima.com/intv/bloch13.html
A: It's the same purpose as any such interface. Primarily it allows methods (etc.) to accept ANY Clonable object and have access to the method they need without limiting themselves to one specific object. Admittedly Clonable is probably one of the less useful interfaces in this respect, but there's certainly places where you might want it. If you want more of an idea consider the interface Comparable which for example allows you to have sorted lists (because the list doesn't need to know what the object is, only that they can be compared).
A: if you dont declare cloneable interface you should be getting CloneNotSupportException when you call clone method.If you declare and then call clone method it will make shallow copy.
A: In your example you are not doing actual cloning.you are overridden the clone() method of object class and given your own implementation. but in your clone method you are creating a new Person object. and returning it.So in this case the actual object is not cloned.
So your clone method should be like :
public Object clone() {
return super.clone();
}
So here clone will be handled by superclass method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: How do I select TOP 5 PERCENT from each group? I have a sample table like this:
CREATE TABLE #TEMP(Category VARCHAR(100), Name VARCHAR(100))
INSERT INTO #TEMP VALUES('A', 'John')
INSERT INTO #TEMP VALUES('A', 'John')
INSERT INTO #TEMP VALUES('A', 'John')
INSERT INTO #TEMP VALUES('A', 'John')
INSERT INTO #TEMP VALUES('A', 'John')
INSERT INTO #TEMP VALUES('A', 'John')
INSERT INTO #TEMP VALUES('A', 'Adam')
INSERT INTO #TEMP VALUES('A', 'Adam')
INSERT INTO #TEMP VALUES('A', 'Adam')
INSERT INTO #TEMP VALUES('A', 'Adam')
INSERT INTO #TEMP VALUES('A', 'Lisa')
INSERT INTO #TEMP VALUES('A', 'Lisa')
INSERT INTO #TEMP VALUES('A', 'Bucky')
INSERT INTO #TEMP VALUES('B', 'Lily')
INSERT INTO #TEMP VALUES('B', 'Lily')
INSERT INTO #TEMP VALUES('B', 'Lily')
INSERT INTO #TEMP VALUES('B', 'Lily')
INSERT INTO #TEMP VALUES('B', 'Lily')
INSERT INTO #TEMP VALUES('B', 'Tom')
INSERT INTO #TEMP VALUES('B', 'Tom')
INSERT INTO #TEMP VALUES('B', 'Tom')
INSERT INTO #TEMP VALUES('B', 'Tom')
INSERT INTO #TEMP VALUES('B', 'Ross')
INSERT INTO #TEMP VALUES('B', 'Ross')
INSERT INTO #TEMP VALUES('B', 'Ross')
SELECT Category, Name, COUNT(Name) Total
FROM #TEMP
GROUP BY Category, Name
ORDER BY Category, Total DESC
DROP TABLE #TEMP
Gives me the following:
A John 6
A Adam 4
A Lisa 2
A Bucky 1
B Lily 5
B Tom 4
B Ross 3
Now, how do I select the TOP 5 PERCENT records from each category assuming each category has more than 100 records (did not show in sample table here)? For instance, in my actual table, it should remove the John record from A and Lily record from B as appropriate (again, I did not show the full table here) to get:
A Adam 4
A Lisa 2
A Bucky 1
B Tom 4
B Ross 3
I have been trying to use CTEs and PARTITION BY clauses but cannot seem to achieve what I want. It removes the TOP 5 PERCENT from the overall result but not from each category. Any suggestions?
A: select Category,name,CountTotal,RankSeq,(50*CountTotal)/100 from (
select Category,name,COUNT(*)
over (partition by Category,name ) as CountTotal,
ROW_NUMBER()
over (partition by Category,name order by Category) RankSeq from #TEMP
--group by Category,Name
) temp
where RankSeq <= ((50*CountTotal)/100)
order by Category,Name,RankSeq
Output:
Category name CountTotal RankSeq 50*CountTotal)/100
A Adam 4 1 2
A Adam 4 2 2
A John 6 1 3
A John 6 2 3
A John 6 3 3
A Lisa 2 1 1
B Lily 5 1 2
B Lily 5 2 2
B Ross 3 1 1
B Tom 4 1 2
B Tom 4 2 2
I hope this helps :)
A: You could use a CTE (Common Table Expression) paired with the NTILE windowing function - this will slice up your data into as many slices as you need, e.g. in your case, into 20 slices (each 5%).
;WITH SlicedData AS
(
SELECT Category, Name, COUNT(Name) Total,
NTILE(20) OVER(PARTITION BY Category ORDER BY COUNT(Name) DESC) AS 'NTile'
FROM #TEMP
GROUP BY Category, Name
)
SELECT *
FROM SlicedData
WHERE NTile > 1
This basically groups your data by Category,Name, orders by something else (not sure if COUNT(Name) is really the thing you want here), and then slices it up into 20 pieces, each representing 5% of your data partition. The slice with NTile = 1 is the top 5% slice - just ignore that when selecting from the CTE.
See:
*
*MSDN docs on NTILE
*SQL Server 2005 ranking functions
*SQL SERVER – 2005 – Sample Example of RANKING Functions – ROW_NUMBER, RANK, DENSE_RANK, NTILE
for more info
A: ;WITH SlicedData AS
(
SELECT Category, Name, COUNT(Name) Total,
**PERCENT_RANK() OVER(PARTITION BY Category ORDER BY COUNT(Name) DESC) * 100** AS 'Percent'
FROM #TEMP
GROUP BY Category, Name
)
SELECT *
FROM SlicedData
WHERE Percent < 5
NTile will not work if number of records is less than your tile number.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Getting the width of a Dynamic TextView inside a Table Row I am stuck up here trying to get the width of a TextView in a Table Row after setting some random text to it.
I am using the getWidth(), but it returns zero always. Is there a way to find out the width of a dynamically created TextView.
Here is my code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
customer_id=(TextView)findViewById(R.id.customer_id);
comapny_name=(TextView)findViewById(R.id.compnay_name);
line1=(ImageView)findViewById(R.id.line1);
TableLayout tl=(TableLayout)findViewById(R.id.linlay);
TableRow tr1 =null;
for(int i=0;i<20;i++)
{
tr1 = new TableRow(this);
tr1.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(this);
textview.setText("data");
textview.setTextColor(Color.YELLOW);
textview.setTextSize(30);
TextView textview1 = new TextView(this);
textview1.setText("data1");
textview1.setTextColor(Color.YELLOW);
textview1.setTextSize(30);
tr1.addView(textview);
tr1.addView(textview1);
tl.addView(tr1);
int width=textview.getWidth();
Log.i("Width",width+"");
}
A: Ok actually the layout is inflated but not yet drawn so in order to get width you will have to
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
System.out.println("...111Height..."+textview.getMeasuredWidth());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Question on CSS % height If I define a CSS as follows;
div {height: 50%;}
Will this work across most modern desktop browsers (IE8+, FF, Safari) and mobile browsers (iPhone/iPad, etc)
Is there any need to specify the following 2 additional attributes for cross-browser support
min-height: 50%; height: auto;
I am asking this question in the context of fluid design (i.e. same page will scale for multiple devices...desktop/tablet/mobile)..So please let me know what should be the preferred approach.
A: No, you don't need those.
BUT: Height is only relative to the parent. And the parent by default has no height (more accurately it's the height of the children inside it).
So you need:
body,html { height: 100%; }
So specify a "starting" height, and you may need to keep the "height chain" alive as well.
The reason for min-height instead of height is that height is fixed - it can't get bigger than that no matter what is inside it. This may not work right. So instead people do min-height so it's as least as tall as they want, but is allowed to grow.
The trouble with min-height is that it doesn't work on all browsers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to select background color in selenium can any budy explain how to select background color from
<div class="shc" style="background-color:#814c1b;">About Me</div>
in selenium.
i've source code like this
<div class="gwt-Label mock-tab selected-tab">My Account</div>
and i need to select color from it.
i'm using firebug to get xpath or css.
i'm using python and i'm new to selenium. please help.
A: In Javascript:
var xx = document.getElementsByClassName("gwt-Label");
var bgColorIs = xx[0].style.backgroundColor
With CSS Selectors
div.gwt-Label.mock-tab.selected-tab.background-color
XPath:
[div@class='gwt-Label mock-tab selected-tab']
XPath samples
CSS Selectors by Class
Javascript - getting an element by class name or tag name
A: This is the answer which i finally got for all color, font size and alignment related questions. Thx for all who tried to help.
sel.get_eval("el = this.browserbot.findElement('xpath or css'); bold
=window.document.defaultView.getComputedStyle(el,null).getPropertyValue('font-weight');")
A: You can use value_of_css_property on the element after you find it. Something like:
current_element = sel.find_element(By.CSS_SELECTOR, 'div.shc')
background_color = current_element.value_of_css_property('background-color')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: What control to use to display main & sub tables ASP.NET 3.5 & SQL 2008
I have this main table & a subtable. For each set of calculation, 1 record is added to the main table & several records to the subtotal.
Most of user entered data goes into the subtable & some into the main table.
Currently I have a web page set up with several textboxes to get the data from the user & the resulting calculations are displayed in a gridview.
The gridview shows all the records from the Main table.
Each time the user selects a record from the gridview, I want to invoke another page where the user can change the data for the selected record.
It will be nice if I can display the 1 record from the main tablle & all the related records form the subtable.I don't want to use free floating textboxes.
What controls will be the easiest to use for such an application?
A: you can use grid view in two pages it self...
Here you have to use session variables to store the value of gridview rows in first page then retrieve the session value and display the row in gridview control in the second page.
If you use gridview control to display the data which get from database in the first page ,as far as I know you can also just pass the unique value of record(such as id) to an other page ,then use the unique value as a condition to search the record in database and display the record by using gridview control in the second page.
Sample:
1.Code in the first page(.aspx):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>PassValue</HeaderTemplate>
<ItemTemplate>
<a href='OtherPage.aspx?id=<%# Container.DataItemIndex %>' target="_blank">Pass</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
2.Code in the first page(.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
public void Bind()
{
this.GridView1.DataSource = Get_source();
this.GridView1.DataBind();
}
// You can get the datatbale form your own database.
// I get the datasource like this in order to run the sample convenient.
public DataTable Get_source()
{
DataTable dt = new DataTable();
DataRow dr;
string XM = "true,false,false,true";
string XMM = "1,2,3,4";
string[] list1 = XM.Split(',');
string[] list2 = XMM.Split(',');
dt.Columns.Add(new DataColumn("ActiveStatus"));
dt.Columns.Add(new DataColumn("number"));
for (int i = 0; i < list1.Length; i++)
{
dr = dt.NewRow();
dr["ActiveStatus"] = list1[i];
dr["number"] = list2[i];
dt.Rows.Add(dr);
}
return dt;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int i = e.Row.RowIndex;
Session["row"+i] = e.Row;
}
3.Code in the second page(which named as OtherPage.aspx)
OtherPage.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
4.Code in the second page(.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
string i = Request.QueryString["id"].ToString();
if (Session["row"+i] != null)
{
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
GridViewRow row = (GridViewRow)Session["row" + i];
for (int xm = 0; xm < row.Cells.Count; xm++)
{
dt.Columns.Add(new DataColumn());
dr[xm] = row.Cells[xm].Text;
}
dt.Rows.Add(dr);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
}
if you want to modify the data in second page, you can modify ... I hope it will helps you...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: c #Asynchronous capture from a process output and display it in a RichTextBox I have a richTextBoxLog which is public and static.
After I declare it, I start a new thread which initializes new variable named proba. richTextBoxLog should get the value from proba.
The problem is, proba needs time to be initialized, and I want richTextBoxLog to initialize while proba is initializing.
I want to write something like:
richTextBoxLogFile.richTextBoxLog.Text += proba;
But, when I write it in the method which is called by the previously mentioned thread, I get an exception: "Cross-thread operation not valid: Control 'richTextBoxLog' accessed from a thread other than the thread it was created on."
I try to use this:
context.Post(new SendOrPostCallback(newMethod), (object)proba);
where context is the context of the main thread and newMethod initializes the value of richTextBoxLog. However, this call is in the method which is started by the new thread, in a while loop:
while (-1 != (ch = _reader.Read()))
{
Console.Write((char)ch);
proba += ((char)ch).ToString();
context.Post(new SendOrPostCallback(newMethod), (object)proba);
}
_complete.Set();
}
The problem I have now is that I want newMethod to be called every time when I enter in the while loop. But, what's happening is: the while loop finishes and after that newMethod is entered about thousand times.
A: You can use Control.InvokeRequired and MethodInvoker combination. See a similar post here:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/b9e6c83e-e36b-4f99-893e-0b242f4f225c
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenEJB cannot use javax.persistence.jtaDataSource The following configuration is ok for WebLogic, but in OpenEJB it raises a error "javax.naming.NameNotFoundException: Name "AppDB" not found."
And if I removed the property javax.persistence.jtaDataSource, it works. And why set 2 duplicated datasource? Because it's a bug of Eclipselinks (see http://bugs.eclipse.org/246126)
<persistence-unit name="app1" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>AppDB</jta-data-source>
<properties>
<property name="javax.persistence.jtaDataSource" value="AppDB" />
</properties>
</persistence-unit>
The following is jndi.properties
java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory
openejb.validation.output.level=VERBOSE
openejb.nobanner=false
jdbc/AppDB = new://Resource?type=DataSource
jdbc/AppDB.provider = org.eclipse.persistence.jpa.PersistenceProvider
jdbc/AppDB.JdbcDriver = oracle.jdbc.OracleDriver
jdbc/AppDB.JdbcUrl = jdbc:oracle:thin:@xx.xx.xx.xx:xxxx:xxxx
jdbc/AppDB.JtaManaged = false
jdbc/AppDB.UserName = xxxx
jdbc/AppDB.Password = xxxx
Because this is a jar packaged by other team, I cannot change the content but I still want to use it in my OpenEJB, any suggestion? thanks.
A: Not at all sure how EclipseLink processes the javax.persistence.jtaDataSource property. I have to assume it's a JNDI lookup of some kind, but there's incredible significance in how they might do that. If they prepend java:comp/env/ for example, that significantly changes the semantics.
Maybe try overriding javax.persistence.jtaDataSource to use the OpenEJB global JNDI name for your datasource. So in your jndi.properties file, add
app1.javax.persistence.jtaDataSource = openejb:Resource/jdbc/AppDB
Definitely let me know if that works. Seems that might a good feature to add to OpenEJB even though the property is actually used by the JPA provider. Fixing invalid JNDI names could be more than convenient.
On a side note, there should be a logging statement saying 'jdbc/AppDB.provider' is not a property supported by the datasource. Probably best to delete that property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get index creation date from SQL server How can I find the create date of an index. I am using SQL2008 R2.
I checked sys.indexes but it does not have a create date so I joined the query with sys.objects. The thing is that the object id for an index and the table containing that index is same.
I am using this query...
select i.name, i.object_id, o.create_date, o.object_id, o.name
from sys.indexes i
join sys.objects o on i.object_id=o.object_id
where i.name = 'Index_Name'
Thanks!
A: This is now quite a long dead thread but the below query from SQLPanda got me the info I needed on Azure SQL for a non clustered index:
SELECT OBJECT_NAME(i.object_id) AS TableName, i.object_id, i.name, i.type_desc,o.create_date, o.modify_date,o.type,i.is_disabled
FROM sys.indexes i
INNER JOIN sys.objects o ON i.object_id = o.object_id
WHERE o.type NOT IN ('S', 'IT')
AND o.is_ms_shipped = 0
AND i.name IS NOT NULL
ORDER BY modify_date DESC
Credit to http://www.sqlpanda.com/2013/10/how-to-check-index-creation-date.html
I just added the modified date since that was the info I was interested in.
A: Try this:
SELECT
i.name 'Index Name',
o.create_date
FROM
sys.indexes i
INNER JOIN
sys.objects o ON i.name = o.name
WHERE
o.is_ms_shipped = 0
AND o.type IN ('PK', 'FK', 'UQ')
The object_id refers to the table the index is created on....
A: When PK or UK is created, SQL Server automatically creates unique index for that constraints. The create_date of those constraints will be the same as the create date for the corresponding indexes.
Since the sys.indexes view does not have create_date column it is absolutely useless for searching this kind of information. Furthermore, object_id column in this view will never refer to the corresponding constraint. It will point to the table the index belongs to.
The following test will demonstrate the point:
CREATE TABLE dbo.TEST_T1
(
COLUMN_1 INT NOT NULL,
COLUMN_2 INT NOT NULL,
CONSTRAINT PK_TEST_T1 PRIMARY KEY (COLUMN_1)
)
GO
WAITFOR DELAY '00:00:01';
ALTER TABLE dbo.TEST_T1
ADD CONSTRAINT UK_TEST_T1 UNIQUE (COLUMN_2)
GO
SELECT O.name, O.object_id, O.create_date, I.object_id, I.name AS index_name
FROM sys.objects AS O
LEFT OUTER JOIN sys.indexes AS I ON O.object_id = i.object_id
WHERE O.name IN ('TEST_T1', 'PK_TEST_T1', 'UK_TEST_T1')
The result is:
name object_id create_date object_id index_name
PK_TEST_T1 272720024 2015-03-17 11:02:47.197 NULL NULL
TEST_T1 256719967 2015-03-17 11:02:47.190 256719967 PK_TEST_T1
TEST_T1 256719967 2015-03-17 11:02:47.190 256719967 UK_TEST_T1
UK_TEST_T1 288720081 2015-03-17 11:02:48.207 NULL NULL
So, if you want to see create_date for PK or UK indexes there is no need to join with sys.indexes. You should select from sys.objects:
SELECT name, object_id, create_date
FROM sys.objects
WHERE name IN ('PK_TEST_T1', 'UK_TEST_T1')
AND type IN ('PK', 'UQ')
The result is:
name object_id create_date
PK_TEST_T1 272720024 2015-03-17 11:02:47.197
UK_TEST_T1 288720081 2015-03-17 11:02:48.207
A: For indexes that are constraints, then see marc_s' answer
For other indexes, you'd have to use STATS_DATE to get the creation time of the associated index (every index has statistics on it)
Something like (not tested)
SELECT STATS_DATE(OBJECT_ID('MyTable'),
(SELECT index_id FROM sys.indexes WHERE name = 'Index_Name'))
This relies on the sys.indexes to sys.stats links
Edit: there is no way to find out as far as anyone can find out. Sorry.
A: Simple query to list indexes in descending date (of statistics) order.
This date is the sate of last statistics update, so is only reliable for recently created indexes.
select STATS_DATE(so.object_id, index_id) StatsDate
, si.name IndexName
, schema_name(so.schema_id) + N'.' + so.Name TableName
, so.object_id, si.index_id
from sys.indexes si
inner join sys.tables so on so.object_id = si.object_id
order by 1 desc
A: USE [YourDB Name]
SET NOCOUNT ON
DECLARE @Table_Name varchar(200)
DECLARE @Index_Name varchar(200)
DECLARE @Index_Type varchar(50)
DECLARE Indx_Cursor CURSOR
STATIC FOR
select s_tab.name as Table_Name,
s_indx.name as Index_Name,
s_indx.type_desc as Index_Type
from sys.indexes s_indx
inner join sys.tables s_tab
on s_tab.object_id=s_indx.object_id
where s_indx.name is not null;
OPEN Indx_Cursor
IF @@CURSOR_ROWS > 0
BEGIN
FETCH NEXT FROM Indx_Cursor INTO @Table_Name,@Index_Name,@Index_Type
WHILE @@Fetch_status = 0
BEGIN
INSERT INTO INDEX_HISTORY(table_name,index_name,Index_Type,Created_date)
SELECT @Table_Name,@Index_Name,@Index_Type,
STATS_DATE(OBJECT_ID(@Table_Name),
(SELECT index_id FROM sys.indexes
WHERE name = @Index_Name))as Index_create_Date
FETCH NEXT
FROM Indx_Cursor
INTO @Table_Name,@Index_Name,@Index_Type
END
END
CLOSE Indx_Cursor
DEALLOCATE Indx_Cursor
select distinct * from index_history
But the main problem with indexes is that when we rebuild or reorganize indexes then the index creation date gets changed to the date when the index was last rebuilt or reorganized.
A: select
crdate, i.name, object_name(o.id)
from
sysindexes i
join
sysobjects o ON o.id = i.id
where
i.name = 'My_Index_Name'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: Maintaining two Xcode versions in parallel on a Mac Can we maintain two versions of Xcode (like Xcode 3.2 and Xcode 4) in parallel on a single Mac machine?
A: Yes - this works fine - normally when you install Xcode 4 if you already have an older version of Xcode it gets moved to /Developer-old and the new Xcode 4 installation goes in /Developer. Many people such as myself do this so that they can have both Xcode 3.x and Xcode 4.x installed at the same time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do i execute a process in C# that installs a printer driver? I have to start an executable (installPrint.exe) within my C# code. For this purposes I used the System.Diagnostics.Process class. The exe file installs a printer driver and copy several files into different directories. I can execute the exe from command line and everything work fine. But if i execute the file with the Process class from my C# application, the printer driver will not be installed.
I start my C# application as a admin user on a Windows XP SP2 x86 machine. Why do my executable dont work in the context of my C# application? What possibilities do i have to get it work?
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = "-i \"My Printer\" -dir . -port myPort -spooler";
startInfo.CreateNoWindow = true;
startInfo.FileName = @"C:\Printer\install.exe";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
//startInfo.Verb = "runas";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory = @"C:\Printer\";
session.Log("Working Directory: " + startInfo.WorkingDirectory);
session.Log("Executing " + startInfo.FileName);
try
{
Process process = new Process();
//process.EnableRaisingEvents = false;
process.StartInfo = startInfo;
process.Start();
session.Log("installer.exe started");
StreamReader outReader = process.StandardOutput;
StreamReader errReader = process.StandardError;
process.WaitForExit();
//session.Log(outReader.ReadToEnd());
//session.Log(errReader.ReadToEnd());
session.Log("RETURN CODE: " + process.ExitCode);
}
catch (Exception ex)
{
session.Log("An error occurred during printer installation.");
session.Log(ex.ToString());
}
A: I take it, you are running your program on Windows Vista or 7. Then, you have to request elevation for your newly created process to run with full access rights. Look at those questions for details:
Request Windows Vista UAC elevation if path is protected?
Windows 7 and Vista UAC - Programmatically requesting elevation in C#
Ok, I see now, that you're using Win XP. Then it may be because of some settings of Process when you start it. Try to start you process as ShellExecute, this way it will be most close to normal starting by the user.
Here's a sample:
var p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = "yourfile.exe", UseShellExecute = true };
p.Start();
A: I use this class in many parts of my projects:
public class ExecutableLauncher
{
private string _pathExe;
public ExecutableLauncher(string pathExe)
{
_pathExe = pathExe;
}
public bool StartProcessAndWaitEnd(string argoment, bool useShellExecute)
{
try
{
Process currentProcess = new Process();
currentProcess.EnableRaisingEvents = false;
currentProcess.StartInfo.UseShellExecute = useShellExecute;
currentProcess.StartInfo.FileName = _pathExe;
// Es.: currentProcess.StartInfo.Arguments="http://www.microsoft.com";
currentProcess.StartInfo.Arguments = argoment;
currentProcess.Start();
currentProcess.WaitForExit();
currentProcess.Close();
return true;
}
catch (Exception currentException)
{
throw currentException;
}
}
}
I hope to have answered at your question.
M.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Notification not working (htc wildfire) I am trying to play a sound, and flash the backlight of android phone using notification manager. I have used the following code. All the required permissions are there in the manifest file. But I am not sure why this is not giving any notification in emulator or in the device (htc wildfire). If you know any feasible solution please let me know
XYNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int NOTFICATION_ID = 1331;
Notification notifyDetails = new Notification();
notifyDetails.icon = R.drawable.icon12;
notifyDetails.tickerText = "Message Received!!!";
notifyDetails.when = System.currentTimeMillis();
notifyDetails.vibrate = new long[] {0,1000,1000,1000,1000,1000,1000,1000}; //vibrate;
Intent notifyIntent = new Intent(this, XYReceiverAppActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0,notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
CharSequence contentTitle = "XYs Notification";
CharSequence contentText = "Get back to XY HOME screen by clicking me";
notifyDetails.setLatestEventInfo(this, contentTitle, contentText, pIntent);
Uri xysound = Uri.parse("android.resource://" + getPackageName() +"/"+ "soundxy");
notifyDetails.ledARGB = Color.BLUE;
notifyDetails.ledOnMS = 10000;
notifyDetails.ledOffMS = 1000;
notifyDetails.flags |= Notification.FLAG_SHOW_LIGHTS;
notifyDetails.sound = xysound;
XYNotificationManager.notify(NOTFICATION_ID, notifyDetails);
The device is not vibrating neither is there any sound alert. LED light is same. how do I send the notification?
A: Here is a code I use in one of my programs, it always worked...
int icon = R.drawable.alerte;
CharSequence tickerText = getString(R.string.lieuproche);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Intent intent = new Intent(getApplicationContext(),
ActivityToLaunch.class);
notification.setLatestEventInfo(
MainActivity.this,
"title",
"action", PendingIntent.getActivity(
this.getBaseContext(), 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT));
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(0, notification);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get Client IP from a Server JSP [Security] I want to know security issue using jsp method request.getRemoteAddr();.
I want to filter some client IP (I can't use firewall :-().
I was wondering in this way an attacker can change the ip source of HTTP Request?
Or the client ip is build from layer 3?
I want to check the security of this method against forging of HTTP Request (similar to ip spoofing that instead is based on layer 3 IP).
Thanks to all,
Andrea
A: The "client" IP address of an HTTP request is actually the IP of the last HTTP proxy. The client can't spoof it, but if the client uses a proxy (and many do) then the IP address won't be much help in identifying the source of the request.
I want just to be sure that the all the request come to my server through a proxy, and I don't want that a client can change this information in order to let the server think that is coming from a proxy while it's not...
It is theoretically possible for a client to spoof the IP address of the proxy, but it is not easy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linux USB driver probe() problem I'm currently work on kernel-mode USB driver for Seowon SWU-3220A WiMAX USB modem. It is a complex device (after plugging it appear in system as USB CDROM, and driver needs to switch it to modem mode). My problem is that the probe() function from my driver is never called. I think it because OS uses standard usb mass storage driver instead of my own.
I initialize driver as follow:
#define GDM7213_VENDOR_ID 0x1076
#define GDM7213_PRODUCT_ID 0x7f40
static struct usb_device_id gdm7213_table [] = {
{ USB_DEVICE(GDM7213_VENDOR_ID, GDM7213_PRODUCT_ID) },
{ }
};
MODULE_DEVICE_TABLE(usb, gdm7213_table);
static struct usb_driver gdm7213_driver = {
.name = "gdm7213",
.probe = gdm7213_probe,
.disconnect = gdm7213_disconnect,
.suspend = gdm7213_suspend,
.resume = gdm7213_resume,
.pre_reset = gdm7213_pre_reset,
.post_reset = gdm7213_post_reset,
.id_table = gdm7213_table,
};
static int gdm7213_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
printk(KERN_INFO "GDM7213 gdm7213_probe()\n");
return 0;
}
static int __init gdm7213_init_module(void)
{
int result;
printk(KERN_INFO "GDM7213 init_module()\n");
result = usb_register(&gdm7213_driver);
if (result)
err("usb_register failed. Error number %d", result);
return result;
}
static void __exit gdm7213_cleanup_module(void)
{
printk(KERN_INFO "GDM7213 cleanup_module()\n");
usb_deregister(&gdm7213_driver);
}
module_init(gdm7213_init_module);
module_exit(gdm7213_cleanup_module);
Can anybody say me where is a bug or suggest any workaround?
A: If it is the USB mass storage driver stealing it before you get a chance you might want to blacklist the VID/PID for the device with that driver.
Since you mentioned it's a USB WiMAX adapter I'm going to have a wild guess though that it's presenting a USB mass storage device that contains a driver for it on Windows. If that's the case you would be better off working with USB Modeswitch, which already handles this for 3G modems. Typically the devices expect some magic bytes (which often is actually a SCSI eject command) to persuade them to stop being mass storage devices and become the real modem. (That has a different PID normally too).
Even if your device can't be persuaded to show the real device instead of the driver with one of the existing USB Modeswitch rules it would be more appropriate to fix the problem with that than a kernel hack.
Doing it with USB Modeswitch has a number of advantages over what you proposed:
*
*Keeps everything modular:
*
*Your driver only has to care about WiMAX and one VID/PID for the device
*The mass storage driver doesn't need to care about crazy devices - it just looks like plugging and unplugging a device. Teaching the mass storage driver about every single one of these sort of devices isn't appropriate, your device doesn't seem to be a special case.
*The knowledge about the split personalities of the device is only relevant to USB Modeswitch, which only exists to solve this problem.
*It doesn't break the USB mass storage aspects of the device - users might want to view the Windows driver under Linux for some reason, blacklisting this device would make that impossible. This might be important if you end up using some firmware shipped with the Windows driver under Linux too.
*It follows the existing setup and keeps your changes local to your module. This might well be important if you want to get your driver in the mainline kernel ever.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rhodes or Sinatra for iphone development? i wanted to develop an iphone app in Ruby, so i was confused to go for which framework.. Rhodes or Sinatra..
My app has to integrate google maps, GPS etc..
Please suggest me :)
A: iPhones run on iOS. iOS will only run compiled Objective C. If you do decide to code in something other than Objective C, you will have to convert it to Objective C before it will run on an iPhone.
Short version: use Objective C. You'll need an Apple computer that uses an Intel processor. You'll need the XCode software.
Rhodes is an example of "convert it to Objective C" after writing in another language.
Either way, you'll need an Apple computer with XCode and an Apple iOS Developer license ($99/year) in order to publish and install your app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I assume an executable file as a snapshot image of an execution state? I read some unix manual (http://pubs.opengroup.org/onlinepubs/009695399/functions/posix_spawn.html), and there was a mention about execution.
The new process image shall be constructed from a regular executable
file called the new process image file.
The expression process image caught my eyes.
I have been thought executable file is just a kind of sequence of command. Just as the word program means. But actually, I don't know the concept and structure of the executable file. And I felt executable file could be looks like an execution state image from the mention.
Could you explain me something about this? About the concept and structure of regular executable files in nowadays. In any OS.
A: Usually the executable file does not contain only instructions but also global data, readonly data and many more. I suggest you briefly look e.g. on the ELF format widely used in UNIX-like operating systems or PE format used in Windows.
The OS may also need for example to replace some addresses of functions (jump targets) with the real addresses of these functions in the memory, although this technique is probably not used anymore in common OSes. Anyway, there can be more work to do than just copy the file into memory and start executing from the first byte.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript Image loading Facebook style so I was browsing through this page: http://360langstrasse.sf.tv/
It basically is a Javascript-Street View, but only allowing one direction. Therefore its kinda like playing a movie.
When moving fast I notived that the images are grainy/pixelated, the same way as when browsing through Facebook.
I was wondering how to implement this?
I tried with sending small base64 encoded images in the markup, and then draw it on a canvas until the 'real' image was loaded.
This worked fine, but left me thinking if this would indeed increase performance, or do sites like facebook do it differently?
Thanks in advance for any help.
Regards Jens
Edit: Or do they only display the images differently? Have another render process than usual?
As I don't see any small images beeing loaded?
Edit 2: The below mentionewd option to load small images first is descriped nicely here: http://www.phpied.com/picassa-progressive-image-rendering/
But basically it is pretty simple.
A: I suppose caching (having in-page) bad-resolution images and fetching better is a real way to accomplish this.
The other way would be linking to small images in a normal way, and fetching bigger with JS - small images should load really fast, or you can subscribe to their load event (tricky in IE) and show the page (remove some overlay) once they are loaded.
BTW, instead of using canvas you can put base64 directly into src
<img src="data:image/png;base64,...
A: The answer is Progressive JPEG's!
One create such with imagemagick for example. This way the browser renders progressively until aborted or completed. Those images may be bigger than normal images, but not always.
Furthermore they provide the ability to be seen before completely downloaded.
Thanks for the help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Automatic redirection to start page-C# asp.net In gridview ,there is a templatefield which is imagebutton.i'm binding imageurl at runtime(on pageload) based on the document type.if i'm not binding the image,on next postback it loads the startup page.can somebody give the reason for this?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to handle this situatiuon in Perl I am having a configuration INI file to store all configuration required for my script to run. I have a Logger.PM which uses Log4Perl, and ConfigReader.PM which reads the INI file and stores the value in global variable. My Start.PL is the entry point where i call the methods from Logger and configreader.
What I do currently
*
*In Start.PL I hardcoded the INI file path
*In Logger.Pm I harcoded the directory name where log files should be stored
What I want
*
*I want the INI file path as configurable
*I want the log folder path to be taken from the INI file
I could do this by following
*
*Pass the INI file path as a parameter to the start.pl
*Read the INI file and get the folder path from INI file
What I could face is that
*
*I cannot use the Logger.PM in ConfigReader (partially) since the
folder name required for logger is part of INI file
I want to log every step of my script (for logging/debugging purpose in case of failure. )
I can use print but this will write to console and to capture i need to use >>log.txt. Then i will be forced to maintain 2 logs for my application which is not what I wanted
Anyone have a good solution for this scenario?
A: You can pass INI file path in command line using Getopt::Long, and command line switches for istance:
Start.pl --ini=/path/to/INI_file
Here is a code sample to show what changes are needed in Start.pl, in order to have switches:
#!/usr/bin/env perl
use v5.12;
use strict;
use Getopt::Long;
# That little tiny 's' after 'ini=' is for string
GetOptions ( 'ini=s' => \my $ini_file );
say $ini_file;
After this change, you can read all options from your INI file, including log folder path ( are you already using a module to manage INI files like Config::IniFiles? ).
There is something still unclear in your question about print: although one of my master said that print with a pair of square brackets is the best debugger in the world, why use print when you have set up Log::Log4perl?
When you say that Logger.PL can't be used in ConfigReader, are you referring to the log object?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AlertDialog inside alertdialog android I am trying to add an alertdialog within an alertdialog.But not able to see the second alertdialog..please help me
here is my code shown
AlertDialog alertDialog = new AlertDialog.Builder(myclass.this).create();
alertDialog.setTitle("First alert");
alertDialog.setMessage("first alert press");
alertDialog.setButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
dialog.cancel();
AlertDialog alertDialog1 = new AlertDialog.Builder(myclass.this).create();
alertDialog1.setTitle("second alert dialog");
alertDialog1.setMessage("second alert dialog details");
alertDialog1.setButton("Scan Another", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}}); }
A: It is gonna be a late answer but you can create an AlertDialog inside onClickListener just like this:
public void onClick(DialogInterface dialog, int which) {
if (options[which] == "Manage") {
//Do smtg
} else {
dialog.dismiss();
final AlertDialog alert;
AlertDialog.Builder dialog2 = new AlertDialog.Builder(CategoryPage.this);
alert = dialog2.create();
alert.setTitle("Delete " + title + "?");
alert.setMessage("Are you sure you want to delete this category?");
alert.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(CategoryPage.this, "YESS", Toast.LENGTH_LONG).show();
}
});
alert.setButton2("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
alert.dismiss();
}
});
alert.show();
}
}
A: I found the way might be it will be helpful for someone so thats why i am sharing:
//2nd Alert Dialog
AlertDialog.Builder alertDialogBuilderSuccess = new AlertDialog.Builder(
context);
alertDialogBuilderSuccess.setTitle("TopUp Success");
// set dialog message
alertDialogBuilderSuccess
.setMessage(
"You voucher is printed, please go to the cashier.")
.setCancelable(false)
.setIcon(R.drawable.ic_launcher2)
.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
finish();
}
});
// create alert dialog
final AlertDialog alertDialogSuccess = alertDialogBuilderSuccess.create();
//////////////////////////////////
//1st Alert
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("TopUp Request");
// set dialog message
alertDialogBuilder
.setMessage(
"Please confirm: " + vendor_name + ", "
+ tvLoadAmount.getText())
.setCancelable(false)
.setIcon(R.drawable.ic_launcher2)
.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
//calling the second alert when it user press the confirm button
alertDialogSuccess.show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
A: AlertDialogs aren't supposed to let another AlertDialog to be open. If it is really what you want, then change your main AlertDialog to Dialog. This way you can manually add the buttons and functionality you require for manage the secondary AlertDialog
A: import android.widget.TextView;
import android.widget.Button;
import android.view.View;
import android.content.DialogInterface;
public class MainActivity extends AppCompatActivity {
Button click;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button)findViewById(R.id.btnId);
click.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
txtSubmit();
}
});
}
protected void txtSubmit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This is alert title");
builder.setMessage("This is message for Alert dialog");
builder.setPositiveButton("Yup", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
builder1.setTitle("This is alert title inside");
builder1.setMessage("This is message for Alert dialog inside");
builder1.show();
}
});
builder.show();
}
}
The txtSubmit function calling from the onClick event listener.
Also for the second alert dialog need to open I have to pass
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
Here, we have to bind the this event using className
When we click on the yup button in the first dialog,it shows the second dialog that insides in the first one
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Retrieving data from a POST method in ASP.NET I am using ASP.NET.
There is a system that needs to POST data to my site and all they asked for is for me to provide them with a URL.
So I gave them my URL http://www.example.com/Test.aspx.
Now I do not know exactly how they POST it but now on my Test.aspx page I need to write code that will save that data to a database.
But how would this work and what must I do on my Test.aspx page?
I wrote some code in my Page Load Event that sends me an email on Page Load to see if they actually hit the page and it does not seem like they are even?
A: The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
To navigate through the all inputs
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
string value = HttpContext.Current.Request.Form[key];
}
A: You can get a form value posted to a page using code similiar to this (C#) -
string formValue;
if (!string.IsNullOrEmpty(Request.Form["txtFormValue"]))
{
formValue= Request.Form["txtFormValue"];
}
or this (VB)
Dim formValue As String
If Not String.IsNullOrEmpty(Request.Form("txtFormValue")) Then
formValue = Request.Form("txtFormValue")
End If
Once you have the values you need you can then construct a SQL statement and and write the data to a database.
A: You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: XSL for each loop selecting position of first occurrence In the following code snippet, I'm trying to get position of EMP_ID field from the available fields. This works fine if there's just one occurrence of EMP_ID.
But if there are more than one occurences then variable 'empid_field' will have positions of all the occurrences appended one after the other. i.e if EMP_ID is at postions 1, 8, and 11, then 'empid_field' would be '1811'.
Is there any way I get position of first occurrence only? Or Can I get comma separated positions atleast? (Code sample would be highly appreciated as I'm new to XSL programming)
<xsl:variable name="empid_field">
<xsl:for-each select="$fields">
<xsl:if test="internalName='EMP_ID'">
<xsl:value-of select="position()"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
A: The easiest solution which is in my mind is to extend this. But I think there are also solutions which look more pretty.
<xsl:variable name="empid_field">
<xsl:for-each select="$fields">
<xsl:if test="internalName='EMP_ID'">
<xsl:value-of select="position()"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="first_empid_field">
<xsl:value-of select="$empid_field[1]"/>
</xsl:variable>
The variable $first_empid_field will only have the first position value.
A: Ok got something ...
Created a comma separated string and picked the part before the delimiter.
<xsl:variable name="empid_fields" >
<xsl:for-each select="$fields">
<xsl:if test="internalName='EMP_ID'">
<xsl:value-of select="position()" />
<xsl:text >, </xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="empid_field" >
<xsl:value-of select="substring-before($empid_fields, ', ')" />
</xsl:variable>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Working with Java JAR files from cmdline Let us have a Java application, contained in files A.java and B.java with dependency on somejar.jar file. The questions are:
*
*how to create a self-runnable JAR file with all the dependencies and sources compiled within? The main condition is using the standard Java utilities only (given with JDK; e.g.: java, javac and jar) and NOT any of build tools like Maven, Ant or any other.
*how to use external JAR files within my application? For example, the algorithm is: if the 'otherjar.jar' is present near the main application JAR, we should call method Moo::method1 from that class, passing the new instance of Foo class to it. Moo and Foo should be present in 'otherjar.jar' file. Still, the 'config.xml' file should be there too.
A: This should answer most of your questions: http://download.oracle.com/javase/tutorial/deployment/jar/basicsindex.html
A: From the link that @michael667 gave, you may be more interested in this section: Adding Classes to the JAR File's Classpath. In particular this note:
Note:
The Class-Path header points to classes or JAR files on the local network, not JAR files within the JAR file or classes accessible over internet protocols. To load classes in JAR files within a JAR file into the class path, you must write custom code to load those classes. For example, if MyJar.jar contains another JAR file called MyUtils.jar, you cannot use the Class-Path header in MyJar.jar's manifest to load classes in MyUtils.jar into the class path.
It's not a possible thing to do with the standard java tools if you don't code your own classloader. There are tools out there, like One-jar which can provide you of such classloader.
Of course, you could always manually use the exploding-jar approach, but that doesn't seem to be what you really want.
You may also find the answers to this question useful: Classpath including JAR within a JAR
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to move Activity to mapActivity in android application I have one application. I need to display a map view when we click on Help button. Actually the Help button is in one class and google map is in another class. Now how can we call one map activity class from another activity class.
A: You launch the activity using an Intent:
*
*http://getablogger.blogspot.com/2008/01/android-how-to-launch-activity.html
*http://developer.android.com/guide/topics/intents/intents-filters.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Open Graph actions adding problem I've added test application then created graph action "XXXXX" in that app, then I deleted that application and created new one and tryed to add the same action (cos the action deleted with app I guess) the system did not allow me to add the action and showed me an error that I've already created that action. So I can neither use the action nor create new one.
Can someone help me in this ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to count the number of 1's surrounding a given element in a 2D list with Haskell? Suppose I have the following nested list:
list =
[[0, 1, 0],
[1, 9, 1],
[1, 1, 0]]
Assuming you are only given the x and y coordinate of 9. How do I use Haskell code to find out how many 1's surrounds the number 9?
Let me clarify a bit more, assume the number 9 is positioned at (0, 0).
What I am trying to do is this:
int sum = 0;
for(int i = -1; i <= 1; i++){
for(int j = -1; j <= 1; j++){
if(i == 0 || j == 0) continue;
sum += list[i][j];
}
}
The positions surrounding (0,0) are the following coordinates:
(-1, -1) (0, -1) (1, -1)
(-1, 0) (1, 0)
(-1, 1) (0, 1) (1, 1)
A: list = [[0,1,0],[1,9,1],[1,1,0]]
s x y = sum [list !! j !! i | i <- [x-1..x+1], j <- [y-1..y+1], i /= x || j /= y]
--s 1 1 --> 5
Note that I there is no error correction if the coordinates are at the edge. You could implement this by adding more conditions to the comprehension.
A list of lists isn't the most efficient data structure if things get bigger. You could consider vectors, or a Map (Int,Int) Int (especially if you have many zeros that could be left out).
[Edit]
Here is a slightly faster version:
s x y xss = let snip i zs = take 3 $ drop (i-1) zs
sqr = map (snip x) $ snip y xss
in sum (concat sqr) - sqr !! 1 !! 1
First we "snip out" the 3 x 3 square, then we do all calculations on it. Again, coordinates on the edges would lead to wrong results.
A: Edit: switched to summing surrounding 8 rather than surrounding 4
How often do you just want the surrounding count for just one entry? If you want it for all the entries, lists still perform fairly well, you just have to look at it holistically.
module Grid where
import Data.List (zipWith4)
-- given a grid A, generate grid B s.t.
-- B(x,y) = A(x-1,y-1) + A(x,y-1) + A(x+1,y-1)
-- + A(x-1,y) + A(x+1,y)
-- + A(x-1,y+1) + A(x,y+1) + A(x+1,y+1)
-- (where undefined indexes are assumed to be 0)
surrsum :: [[Int]] -> [[Int]]
surrsum rs = zipWith3 merge rs ([] : init rs') (tail rs' ++ [[]])
where -- calculate the 3 element sums on each row, so we can reuse them
rs' = flip map rs $ \xs -> zipWith3 add3 xs (0 : xs) (tail xs ++ [0])
add3 a b c = a+b+c
add4 a b c d = a+b+c+d
merge [] _ _ = []
-- add the left cell, right cell, and the 3-element sums above and below (zero-padded)
merge as bs cs = zipWith4 add4 (0 : init as) (tail as ++ [0]) (bs ++ repeat 0) (cs ++ repeat 0)
-- given a grid A, replace entries not equal to 1 with 0
onesOnly :: [[Int]] -> [[Int]]
onesOnly = map . map $ \e -> if e == 1 then 1 else 0
list :: [[Int]]
list = [[0, 1, 0]
,[1, 9, 1]
,[1, 1, 0]]
Now you can drop down to ghci to see it work:
*Grid Control.Monad> mapM_ (putStrLn . unwords . map show) list
0 1 0
1 9 1
1 1 0
*Grid Control.Monad> mapM_ (putStrLn . unwords . map show) $ onesOnly list
0 1 0
1 0 1
1 1 0
*Grid Control.Monad> mapM_ (putStrLn . unwords . map show) . surrsum $ onesOnly list
2 2 2
3 5 2
2 3 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Print new line to a text file without carriage return (CR) in windows I am writing a program in C that prints a random hexadecimal value to a text file. The printed value has a carriage return (CR) along with a line feed (LF). However, the CR (visible in notepad++) is causing issues when the file is used. Is there a way to print a new line with just the LF and no CR.
This is the code:
#include <stdio.h>
#include <stdlib.h>
void main(){
int hexa_address, numberofAddress;
char tracefile[50]; //name of file
int seq_or_rand; //1 for random address; 2 for sequential address
srand(time(NULL)); //reset the value of the random
printf("This generator generates 32bits hexadecimal.\n\n");
printf("Name of file: ");
scanf("%s", tracefile);
printf("Random (1) or Sequential (2): ");
scanf("%d", &seq_or_rand);
FILE *file;
file = fopen(tracefile,"w"); // create file
if(seq_or_rand == 1){ //random generator
file = fopen(tracefile,"w"); // create file
for(numberofAddress = 0; numberofAddress<10000;numberofAddress++){ //create 10000 address
//if(numberofAddress!=0)
fprintf(file, "0 ");
int space = 0;
for(space; space<8; space++){ //remove any 0 from the left
hexa_address = rand() % 16;
if(hexa_address != 0){
fprintf(file,"%x", hexa_address);
space++;
break;
}
else if(hexa_address == 0 && space == 7){ //in condition of 00000000
fprintf(file, "0");
space++;
}
}
for(space; space<8; space++){ //continue generating the remaining address
hexa_address = rand() % 16;
fprintf(file,"%x", hexa_address);
}
if(numberofAddress!=99999)
fprintf(file,"\t"); //start a new line, but not on the last one
}
}
else if(seq_or_rand == 2){ //sequential generator
file = fopen(tracefile,"w"); // create file
for(numberofAddress = 0; numberofAddress<10000;numberofAddress++){ //create 10000 address
if(numberofAddress!=0)
fprintf(file,"\n"); //start a new line, but not on the first one
fprintf(file,"0 ");
fprintf(file,"%x", numberofAddress*4);
}
}
else{ //invalid input
printf("Invalid Input");
exit(1);
}
fclose(file); //done
}
A: Open/create the file in binary mode
file = fopen(tracefile, "wb");
^ Binary mode
Otherwise
fprintf(file,"\n"); /* In text mode this appends two characters. */
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Xcode 4 in my Mac App Store says its installed, but it's not I can't seem to re download xcode 4 as the mac app store thinks that I already have it. I've had this problem before with another app, but could really do with a solution to this problem now as I need xcode for a new work project.
Any help anyone could offer would be much appreciated.
A: What you download from the app store is actually the Xcode installer, not Xcode itself. You might have the installer knocking around somewhere even if you've removed Xcode.
A: Execute the downloaded installer located at /Applications/Install Xcode/Install Xcode.app
A: Are you sure? See Macintosh HD/Developer/Applications
A: Follow the steps:
*
*Open Xcode → About Xcode ( Check the Version)
*If the version is not 4.2
*Search → App Store → Click on "App Store" result → Search Xcode → Click "Update Xcode
*After update, it will not update Xcode automatically.
*Search "Applications" → Click "Applications" folder.
*Sort by "Date modified", Select Name: "Install Xcode" Size:1.81 GB Kind: Application.
*Click "Install Xcode". (Follow the steps)
*After Update, check the Version. It will be 4.2.1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to identify the websphere MQ listner port is down from code level I want to monitor mq listener status whether is up or down. If the connection is down i want to track it down and made a changes accordingly through my program. Is there a way to achieve this using java ?
A: I would consider monitoring your listener this way if using Websphere MQ :
You can send messages to your listener with Programmable Command Formats known as websphere PCF.
Possible Uses
These PCF classes can be used to develop applications for general-purpose WebSphere MQ administration and monitoring, or in specialized applications that need to query or alter WebSphere MQ definitions.
http://www-01.ibm.com/support/docview.wss?uid=swg24000668
A: You can also use MBeans (we did in the past before we switched to SIBus). At one time the MBean type was named "ListenerPort".
If you want to use Java code you can access the AdminClient through a jar. For WebSphere version 7, it looks like that class is in the com.ibm.ws.admin.core.jar (should be somewhere in your WebSphere installation, or even in your install for Rational Application Developer or Rational Software Architect, if you use either of those).
Anyway, once you've looked up the MBean you want to run
//instance of AdminClient
adminClient.invoke(mBean, "start", null, null);
That's how we did it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to execute commandline application (bat) before mercurial commit? I would like to execute command line application before each commit (push) to central repository. If application will execute with errors, commit should fail with some message.
I have found some examples of python hooks, but nothing about calling bats or exe.
A: You just put the exe/batch file as the command for the hook (you probably dont need the bat and exe extensions):
[hooks]
pre-commit.example1 = /path/to/somebatfile.bat
pre-commit.example2 = /path/to/someexefile.exe
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: facet_grid of back to back histogram failing I am having some trouble creating a facet grid of a back-to-back histogram created with ggplot.
# create data frame with latency values
latc_sorted <- data.frame(
subject=c(1,1,1,1,1,2,2,2,2,2),
grp=c("K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I"),
lat=c(22,45,18,55,94,11,67,22,64,44)
)
# subset and order data
x.sub_ki<-subset(latc_sorted, grp=="K_I")
x.sub_kn<-subset(latc_sorted, grp=="K_N")
x.sub_k<-rbind(x.sub_ki,x.sub_kn)
x=x.sub_ki$lat
y=x.sub_kn$lat
nm<-list("x","y")
# make absolute values on x axis
my.abs<-function(x){abs(x)}
# plot back-to-back histogram
hist_K<-qplot(x, geom="histogram", fill="inverted", binwidth=20) +
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..),
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() +
scale_fill_hue("variable")
hist_K
this plots fine but if I try the following I get the error:
Error: Casting formula contains variables not found in molten data: x.sub_k$subject
hist_K_sub<-qplot(x, geom="histogram", fill="inverted", binwidth=20) +
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..),
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() +
scale_fill_hue("variable")+
facet_grid(x.sub_k$subject ~ .)
hist_K_sub
any ideas what is causing this to fail?
A: The problem is that the variables referenced in facet_grid are looked for in the data.frames that are passed to the various layers. You have created (implicitly and explicitly) data.frames which have only the lat data and do not have the subject information. If you use x.sub_ki and x.sub_kn instead, they do have the subject variable associated with the lat values.
hist_K_sub <-
ggplot() +
geom_histogram(data=x.sub_ki, aes(x=lat, fill="inverted", y= ..count..), binwidth=20) +
geom_histogram(data=x.sub_kn, aes(x=lat, fill="not inverted", y=-..count..), binwidth=20) +
facet_grid(subject ~ .) +
scale_y_continuous(formatter="my.abs") +
scale_fill_hue("variable") +
coord_flip()
hist_K_sub
I also converted from qplot to full ggplot syntax; that shows the parallel structure of ki and kn better.
A: The syntax above doesn't work with newer versions of ggplot2, use
the following instead for the formatting of axes:
abs_format <- function() {
function(x) abs(x)
}
hist_K_sub <- hist_K_sub+ scale_y_continuous(labels=abs_format())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Windows 7 - JAVA - starting or stopping apache 2 (httpd) service I would like to know how to stop, start, and restarting the Apache (2.0.64) service installed under Windows 7 in my program JAVA (executed in the same machine).
Initially, I developed my apps in Linux environment and I had no problem to do that. Now, I'm migrating in Windows 7, and I can't do it. I have an error message like : "(OS 5)Access denied. : failed to open Apache2 service".
At the beginning, I thought that error is due to the fact that my account system doesn't have enough rights to do so. I tried to change proprietary of folder c:\Program Files(x86)\Apache2, and in Services (open session as my account). It still no working and I get the same message every time.
I need absolutely to control Apache2 process.
If anyone have any ideas that could help me?
Thank you.
A: One more strange stuff of Windows ....
I figured out why my apps in JAVA didn't work in Windows 7 environment. It juste because since Windows Vista, MS tries to hide the "popup flooding" stuff with something called "UAC - User Account Control".
And in the default configuration, whatever you do; change proprietary of files or services, you still execute them in "limited user" so you don't have trace, you don't know why your programs don't work properly, and you can't even debug it ...
So, if you want to execute an exec stuff in Windows that was installed as "Administrator" role from you apps (Java in my case) , you must play with levels that provide UAC and restart your computer to take effect of that modification.
For me, i set i to the lowess level and it work. I remarked that when i do "Windows"+R, i have a message like "This task's going to be executed as admnistrator privileges"... OK
In short, when you develop with Windows you must debug Windows first, then your apps
....
Welcome to Windows and long life Linux !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Update JTable in runtime I have a JTable which represents a database table. In runtime when I click a button I want to update my table from database. It is working if the button is in that panel where the table is. When I try to create an object from other class it is not working.
How can I update a JTable from outside of the class in running?
A: Yes, you can. Just pass a reference to the TableModel to the other class. When the other class changes the TableModel, the JTable will be automatically updated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jqgrid/mvc 3 - Export to excel and raise a file download dialog? I have read many solutions but I haven't got the working one yet.
My problem is quite easy, export data to excel file and raise a file download dialog.
However the file download dialog doesn't show. I could be the call method from View to Controller is wrong, because I debugged to ExportToExcel function and there's no error
Thank in advance
This is View:
<script type="text/javascript">
$(document).ready(function () {
jQuery("#list").jqGrid({
url: '/documents/List',
datatype: 'json',
mtype: 'GET',
colNames: ['ID', 'File Name', 'Description', 'File', 'Modified', 'File Type', 'Access'],
colModel: [
{ name: 'ID', index: 'id', width: 40, align: 'left', key: true, editable: false, editrules: { edithidden: false }, edittype: 'text' },
{ name: 'FileName', index: 'filename', width: 315, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
{ name: 'Description', index: 'description', width: 210, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
{ name: 'File', index: 'file', hidden: true, enctype: "multipart/form-data", method: "post", editable: true, edittype: 'file', editrules: { edithidden: true, required: true }, formoptions: { elmsuffix: ' *'} },
{ name: 'Modified', index: 'modified', width: 105, align: 'left', editable: false, edittype: 'text', editoptions: { size: 20, dataInit: function (el) { $(el).datepicker({ dateFormat: 'mm/dd/yy' }); } } },
{ name: 'FileType', index: 'filetype', width: 210, align: 'left', editable: true, edittype: 'select', editrules: { required: true }, formoptions: { elmsuffix: ' *' },
editoptions: { dataUrl: '/HtmlSelectHelper/ConstructDocumentTypeList' }
},
{ name: 'Access', index: 'access', width: 114, align: 'left', editable: true, edittype: 'select', editrules: { required: true }, formoptions: { elmsuffix: ' *' },
editoptions: { value: '0:Private;1:Public' }
},
],
autowidth: false,
forceFit: false,
shrinkToFit: false,
width: 1024,
height: 600,
rowNum: 10,
rowList: [5, 10, 20, 50, 100],
pager: jQuery('#pager'),
sortorder: "desc",
sortable: true,
viewrecords: true,
caption: "Documents List",
editurl: "/documents/edit"
});
jQuery("#list").jqGrid('navGrid', '#pager',
{
add: true, edit: true, view: true, del: true
},
{
closeAfterEdit: true,
closeAfterAdd: true,
width: 400
},
{
closeAfterEdit: true,
closeAfterAdd: true,
width: 400,
serializeEditData: function (data) { return $.param($.extend({}, data, { id: 0 })); }
},
{
},
{
multipleSearch: true
});
jQuery("#list").jqGrid('navButtonAdd', '#pager', { caption: "", buttonicon: "ui-icon-calculator", title: "choose columns",
onClickButton: function () {
jQuery("#list").jqGrid('columnChooser');
}
});
jQuery("#list").jqGrid('navButtonAdd', '#pager', {
caption: "", buttonicon: "ui-icon-print", title: "Excel Export",
onClickButton: function () {
$.post("/Documents/ExportToExcel", {}, function () {
});
}
});
jQuery("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "cn" });
});
</script>
This is Controller:
public ActionResult ExportToExcel()
{
var documents = db.documents as IEnumerable<document>;
var grid = new GridView
{
DataSource = from document in documents
select new
{
filename = document.filename,
description = document.description,
modified = document.modified.ToString(),
filetype = document.filetype,
access = document.access
}
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "inline; filename=Excel.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return View("Index");
}
A: I had the same problem and managed to solve by changing the view as follows:
jQuery("#list").jqGrid('navButtonAdd', '#pager', {
caption: "", buttonicon: "ui-icon-print", title: "Excel Export",
onClickButton: function () {
window.location.href = "/Documents/ExportToExcel";
}
});
A: Don't render the view at all.
Instead of returning View() return File() passing byte[] with file content.
More info here: http://msdn.microsoft.com/en-us/library/dd460208.aspx
A: Please change the code as below
Instead of returning View() return new EmptyResult();
also Response.ContentType="application/vnd.ms-excel"
If your code is not working, you can use NPOI for Excel file manipulation
A: i think the best way is to use the FileResult
public FileResult Binary(MyModel Model)
{
return new FileContentResult(bindata, "application/vnd.ms-excel")
{
FileDownloadName = "mytestfile.xls"
};
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java method overload I have 2 alternatives to implement a calculation method, and I am wondering what would be the better approach.
The method needs some int and double parameters and (in some cases) a special flag to do some different calculation.
In the first example, I could call the method with 'calculateFoo(1, 2.0d)' to have the boolean flag == FALSE.
In the second example, I always have to set the boolean flag (even if I do not need it)
Method 1: (here I'm using the '...' as an 'method overloading' parameter)
public SomeObject calculateFoo(int pIntValue, double pDoubleValue, boolean... pDoSpecialStuff) {
if (pDoSpecialStuff.length == 0 || pDoSpecialStuff[0] == false) {
// method was called without boolean flag or boolean flag was set to FALSE
// do some calculation stuff
// ...
} else {
// method was called with boolean flag == TRUE
// do some other calculation stuff
// ...
}
return SomeObject;
}
Method 2: (this is the 'common' approach)
public SomeObject calculateFoo(int pIntValue, double pDoubleValue, boolean pDoSpecialStuff) {
if (pDoSpecialStuff == false) {
// method was called with boolean flag == FALSE
// do some calculation stuff
// ...
} else {
// method was called with boolean flag == TRUE
// do some other calculation stuff
// ...
}
return SomeObject;
}
A: both your methods have code smell, boolean flags suck
here is my suggestion
public SomeObject calculateFoo(int pIntValue, double pDoubleValue) {
// normal calculation here
}
public SomeObject calculateFooSpecial(int pIntValue, double pDoubleValue) {
// special calculation here
}
A: Do the second variant as it is more explicit. Varargs would allow you to pass more than one boolean which are then not used. Better you explicitly define the interface using a single boolean.
If you want to have a default for the boolean flag use another overload:
public SomeObject calculateFoo(int pIntValue, double pDoubleValue) {
return calculateFoo(pIntValue, pDoubleValue, false);
}
A: Consider the following pattern:
public ResultType calcFoo( int i, double d ) {
return calc( i, d, false );
}
public ResultType calcFoo( int i, double d, boolean flag ) {
if( flag ) {
...
return result;
}
else {
...
return result;
}
}
Generally it's better to use an enum instead of a boolean flag. It makes your code more readable and is just as fast.
I noticed you considered using varargs. If you want to use more flags consider using an EnumSet to pass a set of flags to the method. If you want to pass 0 or 1 flags, varargs is even more definitely an antipattern.
A: I would define another one method with just two parameter to perform default calculation.
public SomeObject calcFoo(int, double) {
....
}
public SomeObject calcFoo(int i, double d, boolean b) {
if(b) {
....
} else {
return calcFoo(i, d);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS: Fixed width + Dynamic width children, filling 100% parent width? I have a parent div (- in diagram) who's width I don't know in advance.
I have two child divs (a and b):
b - is always a known fixed width, and should always be positioned on the right.
a - should fill the remaining space
-----------------------------------
- aaaaaaaaaaaaaaaaaaaaaaaaaa bbbb -
- a a b b -
- aaaaaaaaaaaaaaaaaaaaaaaaaa bbbb -
-----------------------------------
Both a and b are of equal fixed height.
I imagine there is a simple solution to this, but I haven't found it yet. I've tried floating both, but one or the other gets pushed below.
Any ideas?
A: You are looking for the holy grail :) The article has a full example and walk through but here is the summary.
Your wrapping div needs to have a right padding the same width as the static width column you want. The inner divs are floated left and the static width column is moved in to the padded region by using a negative margin.
Here is the markup from the tutorial
<div id="container">
<div id="center" class="column"></div>
<div id="left" class="column"></div>
<div id="right" class="column"></div>
</div>
and the css
#container {
padding-left: 200px; /* LC width */
padding-right: 150px; /* RC width */
}
#container .column {
position: relative;
float: left;
}
#center {
width: 100%;
}
#left {
width: 200px; /* LC width */
right: 200px; /* LC width */
margin-left: -100%;
}
#right {
width: 150px; /* RC width */
margin-right: -150px; /* RC width */
}
the tutorial is a 2 column example but if you get rid of the left column and removed the left padding from the the container you should be good to go.
A: may be you can use display:table property like this http://jsfiddle.net/sandeep/NCkL4/8/
html:
<div class="left"></div>
<div class="right">fixed</div>
css:
#parent{
overflow:hidden;
background:yellow;
position:relative;
display:table;
}
.left{
display:table-cell;
}
.right{
background:red;
width:50px;
height:100%;
display:table-cell;
}
but it's not support IE7.
or you can do it this:
html:
<div class="right">fixed</div>
<div class="left"></div>
css:
.right {float:right; width:200px; }
.left { background: green;}
check this http://jsfiddle.net/47YMn/1/
new fiddle http://jsfiddle.net/sandeep/47YMn/7/
A: http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts
Especially this since you want fixed size container at the right side:
( this does make more sense for mobile devices.. )
http://matthewjamestaylor.com/blog/perfect-2-column-right-menu.htm
Sry, actually this one i guess:
http://matthewjamestaylor.com/blog/ultimate-2-column-right-menu-pixels.htm
A: What about display: flex?
#parent{
background:yellow;
display:inline-flex;
}
.left{
display:flex;
flex: 1 1 auto;
}
.right{
display:flex;
background-color:red;
}
http://jsfiddle.net/NCkL4/1037/
A: This one uses floats, whereas the other excellent answer above uses positioning. It's up to you which you chose. Each has its merits and drawbacks.
CSS
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend, button,
table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; vertical-align: baseline; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; }
body { font: normal 100%/1.5em "Helvetica Neue", Helvectica, Arial, sans-serif; color: #353E34; background: #FFF; text-align: left; }
html>body { font-size: 16px; }
.content-wrapper { width: 100%; float: left; }
.content { margin-right: 220px; background: #9CC; }
.sidebar { float: right; width: 200px; margin-left: -200px; background: #FDE95E; }
.inner { margin: 10px; }
.footer { clear: left; width: 100%; background: black; color: #FFF; text-align: center; padding: 4px 0; }
HTML
<div class="content-wrapper">
<div class="content">
<div class="inner">
<p>Content</p>
</div>
</div>
</div>
<div class="sidebar">
<div class="inner">
<p>Sidebar</p>
</div>
</div>
<div class="footer">
<p>Footer</p>
</div>
A: This is a clean and very acceptable way. Making good use of how floats work here, used the clear fix here but to clear the floats you could also use an extra div with clear:right on it, just before the container closing tag.
http://jsfiddle.net/sg3s/sSJvT/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: GCC error: cannot convert 'const shared_ptr<...>' to 'bool' in return I'm switching to GCC 4.6.1, and it starts to complain about code which works fine with GCC 4.4 and MSVC10. It seems that it doesn't want to convert between shared_ptr and bool when returning from a function like this:
class Class { shared_ptr<Somewhere> pointer_; };
bool Class::Function () const
{
return pointer_;
}
using
return static_cast<bool> (pointer_);
everything works. What the heck is going on? This is with --std=cpp0x.
A: In C++11, shared_ptr has an explicit operator bool which means that a shared_ptr can't be implicitly converted to a bool.
This is to prevent some potentially pitfalls where a shared_ptr might accidentally be converted in arithmetic expressions and the similar situations.
Adding an explicit cast is a valid fix to your code.
You could also do return pointer_.get() != 0;, return pointer_.get(); or even return pointer_ != nullptr;.
A: shared_ptr has an explicit bool conversion. It can be used in a conditional expression or can be explicitly converted to bool as you did with static_cast.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: How to implement custom cell selection behavior with button for UITableViewController? I'm trying to replace standard table cell selection behavior with a button-press behavior. The result should be same - to push detailViewController on top and to present some detail info. The cell view is loaded from a separate xib file. So, I need to put a button in that cell xib and use that button for opening detail VC in table VC. I have placed the button view in cell xib, and disabled cell selection in table VC viewDidLoad, but now, I'm not sure how to handle that button press, where to place the button press code or what delegate method to use because didSelectRowAtIndexPath is not respoding (cos I disabled it). Any suggestions?
UPDATE: I need to get some info from cell (section, index) on button press in order to initialize the data for detail VC. Also, should note, that there will be several buttons in each cell.
UPDATE2: I'm using rows with sections, so on button press I need to pass both section and row numbers that corresponds to cell where the button was pressed.
UPDATE3: I have tried to use unique tags for identifying cells but it looks like it's not the solution because I'm getting problems with cell reusing. The first 9 rows are created and relevant tag number are set to them. But then every row from 10 is reused from the queue, so I get the same 9 view with their tags. For example, 10th row pops me the first row button from the queue with the tag 1, 11th - second row button with tag 2 and so on. I mean, the whole dequeue cells means that it doesn't matter how much rows do you have in table, there will be reused 9 cell views for all of the table rows. That means I cannot assign unique tags for the cells because the cell views are not unique for each row
A: If i got u r question right then this will be solution
[cell.yourButton addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
//you can use tag property of button
NSUInteger tag=indexPath.row+1;
cell.yourButton.tag=tag;
this code should be in
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
& you write action as
-(IBAction)myAction:(id)sender{
UIButton *but=(UIButton *)sender;
NSLog(@"Tag-%d",but.tag);
NSUInteger index=but.tag-1;
//using tag you will come to know which button is pressed ...
}
A: The suggestions with tags didn't worked out because of a reason described in UPDATE3. However, I did succeed by calling "magic" indexPathForRowAtPoint: method. So the solutions is:
1) attach custom method for button press in cellForRowAtIndexPath:
// I have already created/loaded and got a handler to my button btn
// here comes attaching
[btn addTarget:self action:@selector(openDetailViewController:event:) forControlEvents:UIControlEventTouchUpInside];
2) Define custom method:
-(void)openDetailViewController:(id)sender event:(UIEvent *)event{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
// do my stuff
}
So, when the button gets pressed my method gets called, passing some additional parameter like event. By calling "allTouches" and "anyObject" I'm getting the touch. Then, I'm retrieving CGPoint from that touch, then passing that point to "indexPathForRowAtPoint" that returns desired indexPath with section and row number. Cool :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Perform validation only on create using php-activerecord I am creating a User Model using Codeigniter and php-activerecord and the wiki says I can use 'on' => 'create' to have a validation only run when a new record is created, like this,
static $validates_presence_of = array(
array('title', 'message' => 'cannot be blank on a book!', 'on' => 'create')
);
It also states that we have access to "save", "update" and "delete"...
None of these are working for me though and I can figure out why, here is my code,
// Validations
static $validates_presence_of = array(
array('email', 'message' => 'Please enter a valid email address.'),
array('password', 'message' => 'Password must be provided.', 'on' => 'create')
);
I want to set it up like this so that when a user updates their profile, they can leave their password blank to keep their current one.
I would appreciate any help or guidance! Thanks!
A: should be call the validation method like this:
#example
$your_obj = new Instace();
if($your_obj->is_valid()) {
// if all is correct your logical code
}
else {
// your logical to show the error messages
}
//doesnt work if you write
if(!$your_obj->is_valid())
//the other way you must be use the next method
if($your_obj->is_invalid())
A: The reason for this is most likely because it's not been implemented.
Relevant classes are lib/Model.php and lib/Validations.php
From a purely abstract standpoint, you would need to track the mode of operation between save and create. To do this, I created a public property (public $validation_mode) within lib/Model.php and set that property to 'create' or 'save' in private methods Model::insert() and Model::update() respectively. These values match the 'on' property you are trying to use.
Then within lib/Validations.php, I modified the following methods:
Validations::validates_presence_of()
public function validates_presence_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['blank'], 'on' => 'save'));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$this->record->add_on_blank($options[0], $options['message'], $options);
}
}
Errors::add_on_blank()
public function add_on_blank($attribute, $msg, $options = array())
{
if (!$msg)
$msg = self::$DEFAULT_ERROR_MESSAGES['blank'];
if (($value = $this->model->$attribute) === '' || $value === null)
{
if(array_key_exists('on', $options))
{
if($options['on'] == $this->model->validation_mode)
{
$this->add($attribute, $msg);
}
} else {
$this->add($attribute, $msg);
}
}
}
What this does basically is passes ALL the $options specified in your model (including the 'on' property) down to the Errors::add_on_blank() method where it now has enough information to differentiate between 'on' => 'create' and the default ('on' => 'save'). Using the public $validation_mode property from the Model class ($this->model->validation_mode), we can determine what the current mode of operation is and whether or not we wish to continue adding the error message or skip it this time around.
Obviously you would want to document any changes you make and test thoroughly. According to the documentation, all validation methods supposedly support this "common option" along side allow_null, allow_blank but again, if it's not implemented, you will have to make it happen yourself by making these necessary changes.
A: I'm find a answer for your question without edit library.
Add the before_validation callback and add in this callback a validation rule. It works for me.
static $before_validation_on_create = array('before_validation_on_create');
static $validates_presence_of = array(
array('login'),
);
public function before_validation_on_create() {
self::$validates_presence_of[] = array('password');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Changing a variable in php file How to add values from <input> to $var in php file?
html
<input type="text" id="align" name="align"/>
php file
<?php
$align="center";
?>
A: You mean you want to post it and put it in a PHP variable?
Try this:
<form action="somephpfile.php" method="POST">
<input type="text" name="align" value="center" />
<input type="submit" value="Send!" />
</form>
somephpfile.php
$align = $_POST['align'];
echo $align;
A: It depends on the form action.
If your form that is holding your fields has an action="post" attribute then from the php side you have to use $_POST['align']. If you have set the action to action="get" then you have to use the $_GET['align'].
<?php
$align = $_POST['align'];
// OR
$align = $_GET['align'];
?>
A: Just output it into the regular HTML value attribute:
<input type="text" id="align" name="align" value="<?php echo htmlspecialchars($align); ?>" />
The htmlspecialchars() call is there to escape things like quotes, to avoid problems if your variable contains quotes, and to make your mark-up more standards-compliant.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Oracle table SELECT rights issue My application has few tables on Oracle where user XYZ is the schema owner. Tables has been created using XYZ. And I would like to have ABCUSER to have CRUD rights on these tables. I have given the access via GRANT ALL ON TABLEABC to ABCUSER and grant is succeeded.
But when this user(ABCUSER) tries to query the DB (select * from TABLEABC) it doesn't seem to work. I get error message
ORA-00942: table or view does not exist
00942. 00000 - "table or view does not exist"
*Cause:
*Action:
Error at Line: 1 Column: 14
Could you please tell what am I missing ?
A: User ABCUSER has privileges on the table but doesn't own it. So you need to include the schema in the query:
select * from XYZ.TABLEABC
/
If you don't want to hardcode the schema name in your programs your user can build a synonym:
create synonym TABLEABC for XYZ.TABLEABC
/
Then the original query will work for ABCUSER.
Note that ABCUSER will require the CREATE SYNONYM privilege.
A: As APC says, you are missing a SYNONYM.
You might want either a PRIVATE or PUBLIC synonym depending upon who you want to be able to view the table.
A good description of the various types and their uses is here:
http://www.orafaq.com/wiki/Synonym
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What's equivalent c++ "_popen" in C#? What's equivalent c++ "_popen" in C#? I would like open file with some command into stream.
e.g.
ffmpeg -i "D:\Downloads\shakira.mp3" -ac 1 -ar 11025 -f s16le -t 20 -ss 20 - 2>nul
thanks in advance.
A: Check out:
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
Here's a snippit:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Changing positions of div panels I have 3 panels: 1 - 2 - 3
The effect i want to have is that the three panels are moving forward.
*
*First i hide the panel number one (fadeOut)
*Second, I change the id of panel number 2 to 1 , panel number 3 to 2, then I change the panel number 1(hidden) to 3.
*Finally, i set fade in for panel number 3 (old id is number 1)
I dont know where i did wrong because when i tried running, the effect is that panel 1 fade out then it fade in again , at the same position.
P/S: is there any plug-in in jquery can do this?
Thank you
A: I'd try a method that doesn't involve changing the div IDs. It's good practice to keep the ID unique to that div. Instead of changing the IDs, you could use a class for all 3 of them, and get jQuery to fade out the first instance of that class, then use the insertAfter() function to insert this element after the last instance of that class.
var elements = $('.myclass');
elements.first().insertAfter(elements.last());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to combine these two queries? SELECT htpid AS parentid
FROM likehot WHERE htpid
IN (SELECT id FROM bultin WHERE DATE >= '1317108749')
GROUP BY htpid ORDER BY COUNT( htpid )
DESC
giving result
parentid
16060
16059
16058
16057
and other query
SELECT app_id,bultin.id,photo_album_id,entcmmnt_id,link_url,youtubeLink,
link_image,id, mem_id, subj, body, bultin.date,parentid,
from_id, visible_to, image_link,post_via
FROM bultin
WHERE id IN ('16062','16059','16058','16057')
ORDER BY FIELD('16062','16059','16058','16057')
LIMIT 5
Actually I wanted the same sequence as that of in IN so I used FIELD operator
Please Suggest
thanks
A: I couldn't Understand Your Question.. If You Can Please Explain it a better way.. I can gave you the Solution.. Wel I would like to say that u can not use more then one value in side the First Query "SELECT id FROM bultin WHERE DATE >= '1317108749')". And One more thing Y don't u use the values in the ist query like this
SELECT htpid AS parentid
FROM likehot WHERE htpid
IN (16062','16059','16058','16057')
A: If I haven't miss anything, this should do the job:
SELECT b.app_id, b.id, b.photo_album_id, b.entcmmnt_id, b.link_url, b.youtubeLink,
b.link_image, b.mem_id, b.subj, b.body, b.date, b.parentid,
b.from_id, b.visible_to, b.image_link, b.post_via
FROM bultin AS b
JOIN (
SELECT htpid, COUNT( htpid ) AS htpid_count
FROM likehot
GROUP BY htpid ORDER BY COUNT( htpid )
DESC
) AS l ON l.htpid = b.id
WHERE DATE >= '1317108749'
ORDER BY l.htpid_count
LIMIT 5
Let me know if you need more details about this query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UIViewControllers in UIScrollView? I have a design question. I have a scroll view that I want to use as a means of navigation. I.e. the user can slide between screens. At present, I am creating view controllers and putting their views directly on the scroll view:
aViewController.view.frame=CGRectMake(0,0,320,200);
[self.myScrollView addSubview:[aViewController view]]
Etc, for all 3 view controllers.
I know this isn't best practice. But I can't think of any other way of doing it. Ideally I would like to get the same behaviour as a navigation controller except the fact that I'll be using a scroll view. Any help would be greatly appreciated.
A: You have to be aware that this breaks certain UIViewController behaviors because these child view controllers do not get informed about interface rotation events and their viewWill/Did(Dis)Appear: methods will not work.
The alternative (until iOS 4.x at least) is to not use UIViewController subclasses for these subviews. You could easily create your own custom controller class (derived from NSObject) to manage a child view.
It's debatable whether that approach makes it easier overall, though.
A: I'm guessing what you're trying to achieve is something similar to this app?
http://itunes.apple.com/us/app/fanhattan-for-ipad/id436928538?mt=8
This app works in the same manner, using a scroll view for navigation. You can analyze that app, you'd get some ideas from it, i'm sure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why IE does not refresh the page after a JS call to a click button? On a ASP.Net page, I am in front of a problem only with IE. Here is the description.
On a page, there is two buttons and one label. The first button is visible and calls a JS function on the click event. This JS function calls the click function of the second button. The second button has an C€ event handler on the click event. The C# event handler edit the label.
In Firefox : the label is correctly edited after the clicks.
In IE (8) : the label is not edited, despite the C€ event handler has been correctly hit.
Also, I observed, in IE, that the Page_Load event is called two times after the JS button click :
Page_Load
button2_OnClick => change of the Label Text
Page_Load => The Label Text is reset :(
In Firefox, the Page_Load is called only once.
My question is : how to make IE refresh correctly the page as Firefox does after a JS button click ?
Below is the sample test code :
1) Page ASPX
<head runat="server">
<title></title>
<script type="text/javascript">
function button1Click(sender, args) {
var button2 = document.getElementById("button2");
button2.click();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="button1" Text="Click-me!" OnClientClick="button1Click();" />
<asp:Button runat="server" ID="button2" Text="Second" OnClick="button2_OnClick" style="display:none" />
<p />
<asp:Label runat="server" ID="label1" Text="Init" />
</div>
</form>
</body>
</html>
2) C# code-behind :
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void button2_OnClick(object sender, EventArgs e)
{
label1.Text = "Changed";
}
}
A: The ID of your button will not be button1 or button2 when it's rendered. It will probably be something like ctl001_button1. Therefore your javascript will not work. In ASP.NET 4 you can override this behaviour by using an assigned ClientID.
<asp:Button runat="server" ID="button1" Text="Click-me!"
OnClientClick="button1Click();" ClientIDMode="Static" />
<asp:Button runat="server" ID="button2" Text="Second"
OnClick="button2_OnClick" style="display:none" ClientIDMode="Static" />
As an aside, this alludes to the main problem with ASP.NET Winforms - it tricks developers into thinking that the web is a connected environment.
What actually happens when you click an <asp:Button /> element by default is that a postback is invoked. I.e. Your browser sends a request to the server for a new page. It sends up something called ViewState which is how the server knows what you've done and what to render. There is no "event" handled as such.
A: I think the problem is with the way you are trying to get the hidden button
var button2 = document.getElementById("button2");
maybe change this to
var button2 = document.getElementById("<%= button2.ClientID %>");
After the buttons are rendered in the browser, the ID is changed by the ASP.Net engine, and not the same as your source.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mysql connection profiles configuration file Is there a way to save the connection params(like host, port, username, password, db) to the mysql servers I frequently access as shortcuts?
I am looking for something similar to ssh config for mysql from terminal in ubuntu. preferably with ssh tunneling support as well.
A: You could use the --defaults-file option combined with an shell alias,
for example:
% cat db01
[mysql]
user=root
password=<your_pwd>
host=<your_host>
% alias my_db01='mysql --defaults-file=db01'
% my_db01
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 41
Server version: 5.1.54-1ubuntu4 (Ubuntu)
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
So you can create different files with different settings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why gives FactoryGirl such large ID's in my testcases? I am using a Rails 2.3.x and Ruby 1.8.7 environment with FactoryGirl 1.3.3 (edit: version of FG has no influence as far as I can see)
In my console, when I do:
Factory(:user_activity)
I get:
#<UserActivity id: 25, user_id: 1, resource_id: nil, ... >
However when I do in my testcase:
@ua = Factory(:user_activity)
I get:
#<UserActivity id: 980190963, user_id: 298486374, resource_id: nil, ... >
Where are these large IDs coming from? How can I setup my testcases to use the expected IDs as seen in the console?
A: I suppose that the IDs are calculated in the same or an equivalent way as when using ActiveRecord fixtures (AR fixtures hashes the fixture label).
I don't know why using Factory in console will give you more normal IDs however.
Do you really need to know the ID in order to test? Or can you use your @ua variable to get the ID if you need it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: DataGridView ComboBox doesn't save when focus After select a value in DataGridView ComboBox and click a save button in bindingnavigator, data doesn't get update in database. User must lose focus in order to get the data updated. Is there a way to fix this problem ?
A: Weird. I have done this recently and it worked like a charm. In my application when the gridview is in Edit mode (Readonly false), and when you select the cell, it will become combobox and when you leave the cell it will behave as textbox. Here is what I did
void dgUpdateItems_CellEnter(object sender, DataGridViewCellEventArgs e)
{
DataGridView dg = (DataGridView)sender;
if (e.ColumnIndex == dg.Columns["ItemCategory"].Index)
{
if (e.ColumnIndex == e.RowIndex)
{
dg[e.ColumnIndex, e.RowIndex].ReadOnly = true;
return;
}
DataGridViewComboBoxCell cmbCell = new DataGridViewComboBoxCell();
ComboUpdate(cmbCell);
cmbCell.Value = ((DataGridView)sender)[e.ColumnIndex, e.RowIndex].Value.ToString();
((DataGridView)sender)[e.ColumnIndex, e.RowIndex] = cmbCell;
}
}
void dgUpdateItems_CellLeave(object sender, DataGridViewCellEventArgs e)
{
DataGridView dg = (DataGridView)sender;
if (e.ColumnIndex == dg.Columns["ItemCategory"].Index)
{
if (e.ColumnIndex == e.RowIndex)
return;
string str = dg[e.ColumnIndex, e.RowIndex].Value.ToString();
DataGridViewComboBoxCell cmb = (DataGridViewComboBoxCell)dg[e.ColumnIndex, e.RowIndex];
string val = cmb.Value.ToString();
dg[e.ColumnIndex, e.RowIndex] = new DataGridViewTextBoxCell();
dg[e.ColumnIndex, e.RowIndex].Value = val;
It is some part of my code if not understanding, let me know.
Here is a link check it out. It may help.
ComboBox in DatagridView in Edit Mode
And sorry, forgot to tell you most important thing, it worked even when it is focused.
And if you are looking for something else, please throw a stone on my head.
Hope it helps.
A: Try calling UpdateSource before saving like this:
ComboBox c = Keyboard.FocusedElement as ComboBox;
if ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))
c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java loop-output fact Think about the code below has a loop article.length
public String getArticle(){
String headline=article.getHeadline(); //getting a,b,c,d from here
System.out.println(article)
return blabla;
}
Lets say output is like:
1-a
2-a
3-b
4-c
5-d
6-d
What is the way of writing output like:
1-a 2-b 3-c 4-d
"I want to remove duplicate characters from a string"
A: If I understand you correctly, you want to count each character in a String?
*
*Create a map to store the character counts
*Iterate over the string
*For each character, add 1 to the current character count (or store 1 if this is the first occurrence)
*Print/use your results from the map
Edit: After reading your question again, I now think your want to remove duplicate characters from a string?
A: To keep only the first occurrence of each character in a string, you could do the following:
public String nubChars( String s ) {
final StringBuilder sb = new StringBuilder();
final Set<Character> cs = new HashSet<Character>();
final int length = s.length();
for( int i = 0; i < length; i++ ) {
final Character c = s.charAt( i );
if( cs.add( c ) ) {
sb.append( c );
}
}
return sb.toString();
}
When passed a string like hello world this method would return helo wrd.
Is this what you need?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Running liquibase in java code I'm trying to execute in Java code analogue of Ant's "updateDatabase" task:
Main.main( new String[]{"--defaultsFile=db/properties/db.test.properties --logLevel=debug update"} );
First, I could not find an updateDatabase command. I've tried: update, updateSQL, but all the time I'm getting:
Errors:
Command not passed
My db.test.properties file if it may help:
#liquibase.properties
driver: org.hsqldb.jdbcDriver
url: jdbc:hsqldb:mem:datasourcedb
username: TEST
password: TEST
changeLogFile: db/changelog/db.changelog-master.xml
I've used the ":" symbol as a separator in property file as described in liquibase.properties
What am I doing wrong? Please help.
A: Use separate strings instead of one big String:
Main.main( new String[]{
"--defaultsFile=db/properties/db.test.properties",
"--logLevel=debug",
"update"
} );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android Action Bar Problem I am trying to implement a action bar in my app.I followed the method from this link http://developer.android.com/guide/topics/ui/actionbar.html If I keep the tragetSdkversion>= 11,Then it works fine. But If I add min sdk version>=11 then the buttons shows up as part of the options menu and not in the action bar. This happens for the tablet.please help
This is part of my manifest
<uses-sdk android:minSdkVersion="4"
android:targetSdkVersion="11"/>
This is my menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/edit"
android:title="Edit"
android:icon="@drawable/icon"
android:showAsAction="ifRoom" />
<item android:id="@+id/renarration"
android:title="Renarration"
android:icon="@drawable/icon"
android:showAsAction="ifRoom"/>
<item android:id="@+id/renarration1"
android:title="Renarration"
android:icon="@drawable/icon"
android:showAsAction="ifRoom"/>
<item android:id="@+id/renarration2"
android:title="Renarration"
android:icon="@drawable/icon"
android:showAsAction="ifRoom"/>
</menu>
A: In the same link you're referring it says,
The Action Bar is included by default in all activities that target Android 3.0 or greater. Any application that targets Android 3.0 automatically receives this theme. An application is considered to "target" Android 3.0 when it has set either the android:minSdkVersion or android:targetSdkVersion attribute in the element to "11" or greater.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4"
android:targetSdkVersion="11" />
<application ... >
...
</application>
In this example, the application requires a minimum version of API Level 4 (Android 1.6), but it also targets API Level 11 (Android 3.0). This way, when the application is installed on a device running Android 3.0 or greater, the system applies the holographic theme to each activity, and thus, each activity includes the Action Bar.
However, if you want to use Action Bar APIs, such as to add tabs or modify Action Bar styles, you need to set the android:minSdkVersion to "11", so you can access the ActionBar class.
A:
If I keep the tragetSdkversion>= 11,Then it works fine. But If I add
min sdk version>=11 then the buttons shows up as part of the options
menu and not in the action bar.
=> Action bar is possible only in Android 3.0 or greater.
Haven't you marked the description clearly written in the link you have mentioned:
The Action Bar is included by default in all activities that target
Android 3.0 or greater
you can find this line in "Adding the Action Bar" section.
More specifically, all activities that use the new "holographic" theme include the Action Bar, and any application that targets Android 3.0 automatically receives this theme. An application is considered to "target" Android 3.0 when it has set either the android:minSdkVersion or android:targetSdkVersion attribute in the element to "11" or greater. (From Android doc)
A: The latest Android Support Library (18) now supports ActionBars back to API 7 (2.1). It is contained in android.support.v7.appcompat. See Android Support Library and ActionBarActivity for more information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there an ehcache jsp tag? In a current project of mine, JSPs are getting huge (lots of jstl end el logic, no Java), and due to increasing traffic, caching on many levels has become a necessity. Some components need to be dynamic, so we won't be able to use filter-based solutions. Unfortunately, the logic uses many custom tags and hardly ever uses includes, so SimplePageFragmentCachingFilter won't help either.
What I am looking for is something like this:
<ehcache:cache key="${myApp.cacheKey}">
<many />
<jsp />
<tags />
<here />
</ehcache:cache>
This tag would expose a virtual writer for pageContext.out and flush that writer to the cache and the page and on subsequent requests would write directly from the cache to pageContext.out.
Does any such beast exist?
Hint: I know we should change the design, reduce logic in JSPs etc. Unfortunately, it won't happen. I'm not the one making decisions here, so please don't go there. Oh, and: yes, I have googled it.
A: There existed two tag libraries for this: Jakarta Cache and OpenSymphony OSCache. Both are retied and the Jakarta Cache library is nowhere available for download, but you can still download the OSCache library here: OSCache 2.4.
It's supposed to be used as follows (after you just drop the JAR in /WEB-INF/lib the usual way):
<%@taglib prefix="oscache" uri="http://www.opensymphony.com/oscache" %>
...
<oscache:cache key="${myApp.cacheKey}">
<many />
<jsp />
<tags />
<here />
</oscache:cache>
A: I made such a thing: https://github.com/psiegman/ehcachetag
Haven't used it on a production system yet, but it has decent code coverage.
A: I believe the answer is no, such a beast does not exist.
A: There's an enhancement request open for this
http://jira.terracotta.org/jira/browse/CDV-1617
I recommend voting for it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mobile application: how do I provide client authentication I had an idea for a fitness mobile app and I have been developing applications based on this idea for iPhone (Obj-C based), Android (java based), WebOS (html5 based) and Nokia Qt.
I now need to provide authentication to the users of my application. The server is a typical LAMP system. I would like the users of my mobile application to log in to the server seamlessly and securely.
I am not really a web programmer and hence would appreciate ideas on how I can go about providing authentication. I've heard about OpenID...but I am not sure if it can be used for authenticating mobile clients. Some one mentioned OAuth but I am not sure if a) it would work in this use case and b) What if my client does not have a Facebook/Twitter account?
Any ideas will be appreciated!
A: I have done something similar and used gnuTLS and a x.509 certificate to authenticate from the client side. Its seamless and easy to integrate.
https://idlebox.net/2009/apidocs/gnutls-2.6.6.zip/gnutls_7.html#SEC65
The important thing about using this method for me was that the https connection was just simple method calls and the handshaking process itself would be handled by the gnuTLS library.
My app was an iOS app and i used xcode to do it which was easy. I think it will be easier on the Java side but I am not sure about the Nokia part. The coding is in C and is thus cross platform.
However if you are looking for a iOS based solution i recommend http://developer.apple.com/library/ios/#samplecode/AdvancedURLConnections/Introduction/Intro.html
But for a cross platform solution that would require the same certificate across all applications and no input or work fro the user, I still suggest gnuTLS and using the x509 certificate.
A: If you already have a LAMP server somewhere, it should be fairly easy to set implement your own API for password authentication -- the important thing is that you do it via HTTPS! (so the user-ids / passwords can not be sniffed). You will need a digital certificate (CERT) for your web-server.
On your LAMP system you can keep the user data in it's database. Your LAMP server should also allow to create a local user account (of course).
You can use this solution either separate or together with OpenID or OAuth!
That means, if your client doesn't have Facebook or Twitter, they can still create an account on your LAMP server.
http://en.wikipedia.org/wiki/OAuth
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Filtering list of tuples based on the availability of a member in a list I want to filter a list of tuples like [(1,22,1),(5,1,8),(8,3,4),(7,5,6)] using a list like [1,7] which would eventually give me the result [(1,22,1),(5,1,8),(7,5,6)]; since (8,3,4) does not have either 1 or 7, it is eliminated.
I can write a comprehensive function for this. But I am looking for a short list comprehension if possible.
Thanks.
A: >>> tup_list = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
>>> filter_list = [1,7]
>>> [tup for tup in tup_list if any(i in tup for i in filter_list)]
[(1, 22, 1), (5, 1, 8), (7, 5, 6)]
A: try with this one :
items = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]
result = [ item for item in items if (set([1,7]) & set(item))]
>>> [(1, 22, 1), (5, 1, 8), (7, 5, 6)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: PostgreSQL delete fails with ON DELETE rule on inherited table In my PostgreSQL 9.1 database I've defined RULEs that delete rows from child tables whenever a parent table row is deleted. This all worked OK, until I introduced inheritance. If the parent (referencing) table INHERITS from another table and I delete from the base table then the DELETE succeeds, but the RULE doesn't appear to fire at all - the referenced row is not deleted. If I try to delete from the derived table I get an error:
update or delete on table "referenced" violates foreign key constraint "fk_derived_referenced" on table "derived"
There is no other row in the parent table that would violate the foreign key: it's being referenced by the row that's being deleted! How do I fix this?
The following script reproduces the problem:
-- Schema
CREATE TABLE base
(
id serial NOT NULL,
name character varying(100),
CONSTRAINT pk_base PRIMARY KEY (id)
);
CREATE TABLE referenced
(
id serial NOT NULL,
value character varying(100),
CONSTRAINT pk_referenced PRIMARY KEY (id)
);
CREATE TABLE derived
(
referenced_id integer,
CONSTRAINT pk_derived PRIMARY KEY (id),
CONSTRAINT fk_derived_referenced FOREIGN KEY (referenced_id) REFERENCES referenced (id)
)
INHERITS (base);
-- The rule
CREATE OR REPLACE RULE rl_derived_delete_referenced
AS ON DELETE TO derived DO ALSO
DELETE FROM referenced r WHERE r.id = old.referenced_id;
-- Some test data
INSERT INTO referenced (id, value)
VALUES (1, 'referenced 1');
INSERT INTO derived (id, name, referenced_id)
VALUES (2, 'derived 2', 1);
-- Delete from base - deletes the "base" and "derived" rows, but not "referenced"
--DELETE FROM base
--WHERE id = 2;
-- Delete from derived - fails with:
-- update or delete on table "referenced" violates foreign key constraint "fk_derived_referenced" on table "derived"
DELETE FROM derived
WHERE id = 2
A: As I said in my comment, this seems an unusual way to do things. But you can make it work with a deferred constraint.
CREATE TABLE derived
(
referenced_id integer,
CONSTRAINT pk_derived PRIMARY KEY (id),
CONSTRAINT fk_derived_referenced FOREIGN KEY (referenced_id)
REFERENCES referenced (id) DEFERRABLE INITIALLY DEFERRED
)
INHERITS (base);
The PostgreSQL docs, Rules vs. Triggers, say
Many things that can be done using triggers can also be implemented
using the PostgreSQL rule system. One of the things that cannot be
implemented by rules are some kinds of constraints, especially foreign
keys.
But it's not clear to me that this specific limitation is what you're running into.
A: Also, you need to check if other records are still referencing the to-be-deleted rows. I added a test derived record#3, which points to the same #1 reference record.
-- The rule
CREATE OR REPLACE RULE rl_derived_delete_referenced
AS ON DELETE TO tmp.derived DO ALSO (
DELETE FROM tmp.referenced re_del
WHERE re_del.id = OLD.referenced_id
AND NOT EXISTS ( SELECT * FROM tmp.derived other
WHERE other.referenced_id = re_del.id
AND other.id <> OLD.id )
;
);
-- Some test data
INSERT INTO tmp.referenced (id, value)
VALUES (1, 'referenced 1');
-- EXPLAIN ANALYZE
INSERT INTO tmp.derived (id, name, referenced_id)
VALUES (2, 'derived 2', 1);
INSERT INTO tmp.derived (id, name, referenced_id)
VALUES (3, 'derived 3', 1);
-- Delete from base - deletes the "base" and "derived" rows, but not "referenced"
--DELETE FROM base
--WHERE id = 2;
-- Delete from derived - fails with:
-- update or delete on table "referenced" violates foreign key constraint "fk_derived_referenced" on table "derived"
EXPLAIN ANALYZE
DELETE FROM tmp.derived
WHERE id = 2
;
SELECT * FROM tmp.base;
SELECT * FROM tmp.derived;
SELECT * FROM tmp.referenced;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: html5 videos not playing in chrome and safari in stage i have a problem in playing html5 videos in chrome and safari in stage.Local its playing all browsers.its playing after 10 to 15 mints in chrome and safari in stage
.but in stage firefox playing currcetly.Pls help to me .Here i have pasted my code.
<video id="mgtvideo" width="268" height="194" control="controls" >
<source id='mp4video' src="<?php echo base_path()?>sites/default/files/videos/Srinivas_Balasubramanian.mp4" type="video/mp4" />
<source id='oggvideo' src="<?php echo base_path()?>sites/default/files/videos/Srinivas_Balasubramanian.ogg" type="video/ogg" />
<source id='webmvideo' src="<?php echo base_path()?>sites/default/files/videos/Srinivas_Balasubramanian.webm" type="video/webm" />
</video>
mp4 size:20mb
ogg size:5mb
webm size:7mb
A: Have a look at: http://html5video.org/
Sidenote: HTML5 doesn't require the solidus ( / ) to close self-closing tags anymore.
A: I've recently completed a mobile app with HTML 5 video and, strangely, I found the order in which the videos are placed in the tag mattered. In order to get cross browser compatibility I specified the formats in the following order
*
*MP4
*WebM
*OGV
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cancelling alarm from other class that the one which initiated it I set alarm from one class using this code
Intent myIntent = new Intent(ClassOne.this, AlarmService.class);
pendingIntent = PendingIntent.getService(ClassOne.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentDate.getTime());
long when = calendar.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when, (7 * 24 * 60 * 60) * 1000, pendingIntent);
Now I need to cancel the pending alarms from another class. Can I just use this code?
Intent myIntent = new Intent(ClassTwo.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(ClassTwo.this, 0, myIntent, 0);
AlarmManager alarmManagerCancel = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManagerCancel.cancel(pendingIntent);
Or there is a better/proper way to cancel pending alarms?
A: As long as the PendingIntent are equivalent as the one you used to register the alarm, it doesn't matter where you call cancel() from. Two PendingIntents are equivalent (equals() returns true) if the underlying intents and request codes are the equivalent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Webservice throws "empty" exception I've a webservice which seems to works fine, but sometimes the webservice stop working for no apparent reason. When I check the response in Firebug I see an "empty" exception:
"There was an error processing the request"
When the error occurs none of the methods on the webservice is working - even the simplest methods which does nothing else but return some data from the database. What could cause a webservice to completly stop working?
Best regards,
Steffen
A: I'd same problems a few years ago. By using PerfMon I saw that I've to increase the usable memory for the hosting AppPool..
When you're logic is fine, it has to be a configuration problem on your webserver (IIS)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails : Model with Array of object of my class I'm beginning RoR. I've designed my model like this :
User
-login:string
-password:string
-email:string
-followers:array (type user)
I have now this termainal rails command :*
rails generate model User login:string password:string email:string
but i don't know how to tell my generated model that I would like an array of User.
I think my question is a bit stupid because Ruby is like PHP (no type). But I prefer to ask ...
Thanks for your help !
A: If you want to have something like followers you have to use a many-to-many association.
Take a look at associations in the rails guide : http://guides.rubyonrails.org/association_basics.html
You have to remember that when you generate a model and you specify login:string for example you specify the name and the type of the column which will be created in your database.
The right way is to have a many-to-many relationship. You have to say that your User has_and_belongs_to_many followers (I assume if a Use has many followers he can follow many User?). You will need to create an other table which will associate a user to another.
You'll find many articles on google which explain how to create many to many relationship.
But RailsGuides are really well done, take a look at it first.
Edit:
As your follower will be also be of type User, you'll have to do something like that:
has_and_belongs_to_many :followers, :class_name => "User"
You can take a look at the documentation for other options:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why RTP/RTSP meddle with my H.264 NALs? I looked in The RFC and noting could explain why the following happens(Though the decoder can still produce the original movie).
I transmitted the H.264/AVC nals using VSS h.264 encoder, the byte stream looked something like this E5 46 0E 4F FF A0 23...
when I read the movie data one the receiver side after the RTP Broadcaster/RTSP receiver, I get extra unknown data but always in the same places, 8 bytes are added before Start Code prefix (0x00000001),
and 2 bytes are added after Start Code prefix it looks something like this.
XX XX XX XX XX XX XX XX 00 00 00 01 XX XX, then I look in the Wireshark and i could see that the RTP adds the bytes to the data payload.
Why does it happens why? and why the decoder seems to cope well with those extra bytes?!
A: Thats some messed up stream... And you can mess it up even more, and it will still work, because decoder parses it for 0x000001 start code, skipping the bytes that are added at the beginning. Those two new bytes at the end must be H264 fragmentation bytes... or something H264 related since they work.
So basically, this is due to defective packetizer/RTSP source filter. My guess is that if you ASCII encode those 8 bytes you will get the vendor name of the RTSP source filter... xD
A: As I mentioned in another post Changing NALU h.264/avc, for RTP encupsulation, H.264 is transmitted over RTP as defined in RFC 3984. This in particular defines how exactly large NAL units are broken into smaller parts that fit smaller message sizes, suchas UDP datagram size. That is, fragmentation.
Receiver depacketizes the data and restores NALUs, and it uses this extra information to do the job.
So what you essentially need is to compare raw data you have against RFC 3984 format. Also, Wireshark already does partially this for you by dissecting traffic into readable items.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Make 'To' field only show one recipient This is the PHP code I am using upon clicking 'Submit' button at the form.
Currently, when user inputs the email addresses, the message will be sent to those people. Upon checking my email when I was testing, I noticed that at the 'To:' field, it shows all the recipients.
I would like to hide the rest of the recipients' emails. How do I do this?
<?php
// request variables like beneath // important
// $name=$_REQUEST["name"];
// multiple recipients
$to = $_REQUEST['email1'] . ', '; // note the comma
$to .= $_REQUEST['email2'];
// subject
$subject = 'Movie World: Stay Tuned!';
$message = '
<html>
<head>
<title>Movie World</title>
</head>
<body>
<p>Movie World you would not wanna miss!</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'From: Movie World <movie@movieworld.com>';
// Mail it
mail($to, $subject, $message, $headers);
?>
<script type="text/javascript">
alert("Success! Thank you for your enquiry.");
<!--
window.location = "form.html"
//-->
</script>
A: You need to add an additional header for BCC, Blind Carbon Copy
$headers .= 'Bcc: ' . $_REQUEST['email2'] . "\r\n";
A: If you don't want to use a bcc then you need to use a foreach or similar.
Collect an array of email addresses using
<input type="text" name="address[]" />
then loop through them:
foreach($_POST['address'] as $email) :
$to = null;
$to = $email;
// validate the email
// set up the headers
mail($to, $subject, $message, $headers);
endforeach;
might be worth looking at a proper mail library for anything more advanced.
And be careful as this kind of form can be a goldmine to spammers unless you control the input properly by limiting the amount of emails, proper sanitization etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JQuery click function removeClass addClass sequential I want to click on a button, a div appears, when clicking the same button it should disappear.
Actually only appearing works, how to hide it again?
Skript:
$('#button').click(function() {
$('#ui-block-a').removeClass('visuallyhidden').addClass('ui-block-a'), function(){
$('#ui-block-a').addClass('visuallyhidden').removeClass('ui-block-a');
};
});
HTML:
<div class="visuallyhidden" id="ui-block-a">
<ul data-role="listview" data-filter="true" id="nav"></ul>
</div>
Here is try to use a callback, but it is not working...
A: If the classes are correctly set from the beginning, you can use .toggleClass() [docs]:
$('#ui-block-a').toggleClass('visuallyhidden ui-block-a');
Otherwise, if you explicitly want to add/remove classes, you can use .toggle():
$('#button').toggle(function() {
$('#ui-block-a').removeClass('visuallyhidden').addClass('ui-block-a');
}, function(){
$('#ui-block-a').addClass('visuallyhidden').removeClass('ui-block-a');
});
Why your code does not work:
You are not setting up a callback. You are executing two statements via the comma operator. The first part ($('#ui-block-a').addClass('...').removeClass('...')) will be executed as expected. The second part (function() {...}) will be evaluated as function expression and the result, a function, will be returned as overall result of the statement. But you are not assigning the result to anything, so it is just silently ignored.
E.g. if you'd do
// form is like `var foo = x, y;`
var foo = $('#ui-block-a').removeClass('...').addClass('...'), function(){
$('#ui-block-a').addClass('...').removeClass(...');
};
then foo would refer to the function
function() {
$('#ui-block-a').addClass('...').removeClass('...');
}
But that is not what you want anyway. So putting a function there is legal, but has not special meaning and thus no effect.
A: Use toggleClass, sometimes toggleClass can be a bit temperamental so use an if statement and and variable.
in sudo code:
variable = 0
if variable = 0
{
Show Div
variable = 1
}
else if variable = 1
{
Hide Div
variable = 0
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SSHJ Example of Public Key Auth from File Can someone give me an example of using SSHJ for Public Key Authentication? I realise this question is essentially identical to ssh example of private/public key authentication, however the answer by the author https://stackoverflow.com/users/126346/shikhar refers to a google user group that no longer exists, and I am having trouble getting it to work.
Thanks!
Phil
A: We built the overthere framework on top of SSHJ. Which can connect also connect using key files.
The following piece of code should work, but make sure you add the bouncycastle library to your classpath.
SSHClient client = new SSHClient();
String username = "johndoe";
File privateKey = new File("~/.ssh/id_rsa");
KeyProvider keys = client.loadKeys(privateKey.getPath());
client.authPublickey(username, keys);
Hope that helps.
A: I just had this issue as well. I ended up changing
client.authPublickey(user, "id_rsa.pub")
to
client.authPublickey(user, client.loadKeys("id_rsa"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: .Net 2.0 Form tag I have a .net application with aspx coded like:
...
<form id="Fac_Status" action="TEST.aspx?Section=rel" method="post" runat="server">
<asp:Button id="BTN_ActSTADD" runat="server" Text="Submit" CausesValidation="True" OnClick="BTN_ActSTADD_Click"></asp:Button>
</form>
...
Is there any possibility (environmental, settings, framework changes) that could exist where upon clicking Submit button, the button event handler is activated?
In above example, currently the page posts to the Test.aspx set in the form tag.
But some time back - according to my predecessor, this page used to trigger the button event handler. There was no code change.
A: You are posting your page(Test.aspx) to another page(another_test.aspx). This won't work. Change action="TEST.aspx?Section=rel" to action="ANOTHER_TEST.aspx?Section=rel" and set AutoEventWireup="true" in page directive and see click handler in action.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Install Ads (Advertising) Server I want to install small ads (advertising) server on my local computer, to be run on linux,
is there anybody know the program/tools of it ?.
thanks,
A: First, you'll need a way to receive requests. A static IP address. Or a service like No-IP.
Then, you'll need a way to serve the ads. A server like apache would do fine. If the ads are static, you're done.
If they need to be dynamic, install PHP or Tomcat (JSP). Or whatever you prefer.
A: If you still need a way to serve the ads, I'd recommend DFP SB. It's a free and simple ad server: www.google.com/dfp/info/sb/index.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xcode Designer: How Do I Create 2 Sliding Selector Controls?
Hi,I want to list for ex. speechers in an organization. Let's say a schedule. I've seen a couple apps in AppStore and liked this most. How do we create such controls? Like select the date then the place of speech. Those two don't have to be dependent.I couldn't see a control like this in Xcode designer.Thanks in advance.
A: You would have to write your own control. Something like that could be a UIScrollView set to paging mode that gets its 3D effect from some neatly positioned gradients. Interface Builder won't help you much (if at all) with this task.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Best option for deploying a CakePHP web app to shared hosting I have always edited code live on a site through an FTP connection in Coda or similar, however I've just written my first PHP web app for user sign ups etc and I'm very wary that i'm going to need a better plan than "live editing". I'm on shared hosting so i think things like SVN and GIT are probably out but is there any software/scripts/solutions that will allow me to push code live to a web server and have the master copy on my Mac.
What are peoples experiences with web apps/deployment and shared hosting?
A: I have written my own deployment system to avoid editing on live.
It runs in various stages - they are:
*
*SVN export from local repository (this means you don't get loads of .svn directories)
*rsync exported code to live server - but in --dry-run mode so you can see what is actually going to go up to live. This command has some excludes on it: --exclude app/tmp
*rsync in normal mode
Some extras I've put in.
*
*Because I'm running the code on multiple web servers behind a load balancer, I exclude core.php and database.php. I have then symlinked those files on each of the web servers to a centrally accessible NFS.
*The rsync to live runs, but it only uploads it once (to the NFS). The deploy script then runs a command on a remote server (via ssh) to kick off an rsync between the NFS and web servers. It's a bash script that means I can easily manage the web nodes and how the files get pushed out.
Hope that helps!
A: i use a cakephp shell tool i wrote – which uses “rsynch” and only uploads the delta (changes made so far).
with such a rsync script it is fast to upload changed files. only a matter of 1-2 seconds.
with another project I have to commit everything and manually "svn update" the server all the time. very annoying + you need to commit even "test stages".
so after all I recommend using the above delta upload.
Make sure you DON’T upload any tmp stuff or even worse, override environment based files like uploads, cached files etc.
Using batch scripts like rsynch you can usually exclude some directories.
my configuration for example is
server xxx
username xxx
password xxx
local C:\...\app\
remote /var/www/site
protocol ftp
permissions ignore
state timesize
exclude _*
exclude *__*
exclude *~*
exclude .svn
exclude .git
exclude /tmp
exclude /files/uploads/*
exclude /webroot/files/tmp
exclude /webroot/img/content/*
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use a parameterized class as resultClass in iBATIS We have the following class
public class TemporalData<T> {
private T data;
private String opCode;
private Date updateTime;
// getters, setters
}
public class Employee {
private String name;
private int age;
private Date dob;
// getters, setters
}
And say, we've an employee_log table with all fields of employee and couple of additional columns (opCode, updateTime)
Assume this is a pattern for all log tables where we have few additional columns (in this case opCode, updateTime), we would like to have one single class that can cater to all Temporal data and hence the parameterized class.
Now, if we have to fetch employees whose attributes changed in a given duration and would like to have objects of type TemporalData returned by the DAO layer, can anyone explain how to implement an ibatis TypeHandler to handle this case? How should the type handler be configured in sqlmap xml files?
A: Got to know a much better and simpler solution from one of my colleagues.
<resultMap class="Employee" id="employee">
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="bidPrice" column="bid_price"/>
<result property="dob" column="dob"/>
</resultMap>
<resultMap class="Temporal" id="temporalEmployee">
<result property="data" resultMap="employee"/>
<result property="opCode" column="opCode" javaType="String"/>
<result property="updateTime" column="updateTime" javaType="java.util.Date"/>
</resultMap>
The above approach would work well without any additional components.
A: After a lot of digging through ibatis classes in multiple packages , the following approach worked for me. (couldn't find any documentation regarding this approach nor any content in the only book available for ibatis - ibatis in action)
Step 1: Add a custom ResultObjectFactory. Classdoc of ResultObjectFactory interface explains what it is and how it behaves.
public class TemporalDataResultObjectFactory implements ResultObjectFactory {
/*
* (non-Javadoc)
*
* @see
* com.ibatis.sqlmap.engine.mapping.result.ResultObjectFactory#createInstance
* (java.lang.String, java.lang.Class)
*/
@Override
public Object createInstance(String statementId,
@SuppressWarnings("rawtypes") Class clazz)
throws InstantiationException, IllegalAccessException {
if (!statementId.startsWith("_td_")) {
return null;
}
TemporalData<Object> temporalResult = new TemporalData<Object>();
Object dataObject = clazz.newInstance();
temporalResult.setData(dataObject);
return temporalResult;
}
/*
* (non-Javadoc)
*
* @see
* com.ibatis.sqlmap.engine.mapping.result.ResultObjectFactory#setProperty
* (java.lang.String, java.lang.String)
*/
@Override
public void setProperty(String arg0, String arg1) {
// TODO Auto-generated method stub
}
}
Step 2: Add the above ResultObjectFactory to sql-map-config
<resultObjectFactory type="TemporalDataResultObjectFactory" />
Step 3: Prefix all your ibatis statement Ids whose result is temporal data with 'td'.
example:
<select id="_td_getTemporalEmployees" resultMap="temporalEmployee">
SELECT name, age, opCode, updateTime
FROM employee
WHERE updateTime BETWEEN #startTime# AND #endTime#
</select>
Step 4: Define the result map with the actual class (eg: if you want the result to be TemporalData, then set the class to 'Employee'), but with properties as per the temporalData class.
example:
<resultMap class="Employee" id="temporalEmployee">
<result property="data.name" column="name" javaType="String"/>
<result property="data.age" column="age" javaType="long"/>
<result property="data.bidPrice" column="bid_price" javaType="int"/>
<result property="data.dob" column="dob" javaType="java.util.Date"/>
<result property="opCode" column="opCode" javaType="String"/>
<result property="updateTime" column="updateTime" javaType="java.util.Date"/>
</resultMap>
Step 5: Make sure that all properties in resultMap defined above has javaType appropriately set (Otherwise, ibatis throws exceptions during validations complaining about unavailable setters)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to make sure information in pixels work on all screen sizes? I have a Gallery with images of text, and a database that contains each text's position in the images..
The position is represented in pixels, and thats the problem:
How can I make sure that the information works on each screen resolution?
The images are 300x400..
NOTE: the database already contain these values in pixel.. I cant change them.
A: Don't specify the positions in pixels, use dp instead
http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
and read this for more in formation on how to support multiple screens:
http://developer.android.com/guide/practices/screens_support.html
A: If you are unable to change to dp values, you can instead check the DisplayMetrics with:
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
with metrics.densityDpi you get the current Density.
Then implement a switch statement for each density adding a scaling factor to all your px values, similar to this:
switch (density) {
case 120:
scaleFactor = 0.75;
break;
case 160:
scaleFactor = 1;
break;
case 240:
scaleFactor = 1.5;
break;
case 320:
scaleFactor = 2;
break;
default:
break;
}
A: I prefer you following the standard sizes for hdpi,ldpi and mdpi. They are 480x800, 320x480 and 240x400 and place them in their respective folders. Your current resolution will make the image stretched to suit the devices. Name all the images with the same name. Android will take care of the rest. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Customizing facebook fan box css HTML, with CSS set to a file on localhost:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<fb:like-box href="http://www.facebook.com/pages/abc/143772917800992?created" width="200" height="550" show_faces="true" stream="false" header="false" css="http://localhost/abc/templates/index/images/fb.css?1" >
</fb:like-box>
CSS:
@charset "utf-8";
/* CSS Document */
.fan_box a:hover{
text-decoration: none;
}
.fan_box .full_widget{
height: 200px;
border: 0 !important;
background: none !important;
position: relative;
}
.fan_box .connect_top{
background: none !important;
padding: 0 !important;
}
.fan_box .profileimage, .fan_box .name_block{
display: none;
}
.fan_box .connect_action{
padding: 0 !important;
}
.fan_box .connections{
padding: 0 !important;
border: 0 !important;
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
font-weight: bold;
color: #666;
}
span.total{
color: #FF6600;
font-weight: bold;
}
.fan_box .connections .connections_grid {
padding-top: 10px !important;
}
.fan_box .connections_grid .grid_item{
padding: 0 10px 10px 0 !important;
}
.fan_box .connections_grid .grid_item .name{
font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
font-weight: normal;
color: #666 !important;
padding-top: 1px !important;
}
.fan_box .connect_widget{
position: absolute;
bottom: 0;
right: 10px;
margin: 0 !important;
}
.fan_box .connect_widget .connect_widget_interactive_area {
margin: 0 !important;
}
.fan_box .connect_widget td.connect_widget_vertical_center {
padding: 0 !important;
}
Facebook doesn't seem to be loading the CSS file. What's the problem?
A: CSS can't be loaded from localhost because Facebook needs to load (and cache) it from their servers. That is, it needs to be somewhere that's accessible to their servers.
A: Facebook has withdrawn this option. Now you can not add any such css file to your like box or fan box. It has been stopped working everywhere since 24th Jan 2013.
A: because the fan box is an iframe, and iframes cant be styled from the parant document.
asfaik facebook dont want to let you customize this the design to stay ci conform, however you can have the inverted color version and some other fonts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to name method that raises an event I have a method (Read) that raise an event when there are new logs:
public class LoggerModel: ILoggerModel {
public event System.EventHandler LogsChanged;
...
public void Read() {
if (ThereAreNewLogs()) {
OnLogsChanged(System.EventArgs.Empty);
}
}
}
but I feel that "Read()" is not expressive...any suggestions?
A: I'd call it CheckIfLogChanged()
A: It's a matter of taste, I personally use TriggerEvent, where "event" is the name of the event of course. It's also a good place to check whether the event is not null. But it's a private method in my case, whereas your Read method is public, and if raising an event requires calling some reminder-method "manually", it is at odds with the very idea of event-based communication imho.
A: Yes, it's confusing... I would call it Listen() or something like that.. perhaps StartListening()
In addition you have to check if someone has registered for the OnLogsChanged Event
by calling
if(OnLogsChanged != null)
{
OnLogsChanged(EventArgs.Empty);
}
A: The real scope of that method is to verify that and handle new entries in log.
So for me could be VerifyNewLogs, or something like this.
But the best solution it would be to add the documentation for it, where you will describe what the method is doing. This will for sure help you or someone else in the future.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ignore return type from a Expression.Call When an operation invokes an Expression.Call, it will throw an error stating that 'System.Boolean' cannot be converted to 'System.Void'
More specifically:
I am implementing a 'wait' keyword which will simply call WaitOne() on a specified EventWaitHandle, and I am not interested in the return type, as it is supposed to wait indefinitely.
I have tried Expression.Convert(expression, typeof(void)), but it didn't really do anything interesting.
edit: I found one solution: put the expression in a block. Not sure why it has any effect.
A: From the description it sounds like you were trying to create an Expression<Action>.
However, the WaitOne method has the signature bool WaitOne() thus the resulting expression was trying to return a bool.
By wrapping the expression in a block you created a small thunk method that has no return value (void).
E.g. given the following code:
bool WaitOne() { return true; }
Action a = WaitOne;
The compiler cannot directly create a delegate of type Action for WaitOne because that would unbalance the stack; ie. the return value from WaitOne needs to be removed from the stack.
So to help you the compiler silently creates a method, thus what is actually compiled is similar to:
bool WaitOne() { return true; }
void k_CompilerGenerated() { WaitOne(); }
Action a = k_CompilerGenerated;
When building the expression yourself you don't have the luxury of the compiler doing this for you. So in essence, when you created the block, you manually did this same step that the compiler would normally perform.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: T-SQL (varchar(max) vs CLR (string, SqlString, SqlChars)? I have a problem, that I can't solve. I'm using SQL Server 2005, C# CLR for using outer dll. The problem is at length of parameter. I need to use as function parameter type varchar(max). If at C# code I use string, SqlSring, I can't use T-SQL type varchar(max), just varchar(4000) of nvarchar(4000). I need to say, that can be situations, when I need to use more then 4000 symbols, so I need know, what C# type I need to use for varchar(max).
I have read a lot of articles, and several of them say, that for this I can use SqlChars. But! I have manipulations with strings. How can I have actions with string or SqlString and then convert to SqlChars? (It is possible SqlChars.ToString() or SqlChars.ToSqlString()).
I didn't find any C# code for this.
A: I found the answer. Not just only me asked about this question. I have to read posts more attentively...
Can read here http://social.msdn.microsoft.com/Forums/is/sqlnetfx/thread/391ebb98-e1b5-47fc-a72d-9f1e39829e3a The problem of CLR compatibility solves not very difficult.
All time I wanted use varchar(max) and tried to use C# types string, SqlString, SqlChars. Need to use T-SQL nvarchar(max), and you can use any of C# types string, SqlString, SqlChars!
Of course nvarchar taking up more space than varchar at two times.
A: What you need to do is add SqlFacet(MaxSize = -1) attribute to parameter:
[return: SqlFacet(MaxSize = -1)]
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]
public static SqlString YourSqlFunction([SqlFacet(MaxSize = -1)]SqlString sourceSS)
{ return new }
A: Try using length -1. Something like this:
cmd.Parameters.Add("@param", SqlDbType.VarChar, -1).Value = "hdfiophdopigherog";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Perl iterate through each match Let's say I'm scanning through a page of raw html looking for this regex. (The quote mark on the end is intentional).
m/(https?:\/\/.*?(?:'|"))/
This pattern is likely to match ~ 100 times. What is a common perl idiom/a quick way to iterate through a list of all capture group matches?
A: From the perlretut (a very fine tutorial)
while ($x =~ /(\w+)/g) {
print "Word is $1, ends at position ", pos $x, "\n";
}
You can use while together with the g modifier to iterate over all matches, with $1 you get the content of your capturing group 1, and in this example from the tutorial you get also the position with pos.
A: @Zaid: I think your approach is more compact. hope the following snippet will help to understand your example
my $str = 'file_%date%_%name%_%lang%.txt';
my @ts = $str =~ /%([\w]+)%/g;# <----------Zaid said
print join(", ", @ts);
Output:
date, name, lang
A: The global matching 'g' modifier returns a list of captured matches in list context:
say $_ for $str =~ /un($wanted)/g; # Prints only $wanted
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
}
|
Q: How do I jump to a definition (function definitions, struct definitions, ...) in Notepad++ I usually use Notepad++ to read open source, but I don't know
how to jump to a definition or jump back previous position.
How do I do that?
A: I'm using the SourceCookifier plugin for this. The file containing the definition must be open in N++. Going back is just CTRL+SHIFT+TAB.
A: I know this is an ancient question, but Notepad++ has View -> Function List now. Doesn't work across files, but most of the other plugins I tried I had lots of problems getting working.
A: TagsJump works fine: http://sourceforge.net/projects/tagsjump/
A: *
*Install SourceCookifier plugin from plugin manager.
*Open the file which you want to edit.
*Click on the function name or struct name (place the pointer in between the name)
*PressCTRL+SHIFT+ENTER
This will send you to the definition (or shows a drop down menu for definitions if function overloading is implemented from which you can select) .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: For Android's canvas, Is there a way to draw a path of variable width? I have a path that I want to draw on the canvas, but I want to change the width of different sections depending on some variables. How can I do that?
Also, is it possible to use a bitmap pattern as the stroke of the path? Similar to what Photoshop has.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Draw a Fill Rectangle with low opacity I a have a PictureBox with a picture in a Windows Form application in C# language.I want draw a FillRectangle in some location of picturebox.but i also need to see picture of picture box.how can i draw this rectangle with low opacity to see image of picturebox?
A: Do you mean:
using (Graphics g = Graphics.FromImage(pb.Image))
{
using(Brush brush = new SolidBrush(your_color))
{
g.FillRectangle(brush, x, y, width, height);
}
}
or you can use
Brush brush = new SolidBrush(Color.FromArgb(alpha, red, green, blue))
where alpha goes from 0 to 255, so a value of 128 for your alpha will give you 50%
opactity.
A: You need to create a Graphics object based on your PictureBox image and draw what you want on it:
Graphics g = Graphics.FromImage(pictureBox1.Image);
g.FillRectangle(Brushes.Red, new Rectangle(10, 10, 200, 200))
pictureBox1.Refresh()
Or as suggested by @Davide Parias you can use Paint event handler:
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Red, new Rectangle(10, 10, 200, 200));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: EJB application hosting I am studying ejb and developing an application. I want to host and see how it works. I searched everywhere ejb hostings:cloud,vps hosting. But their hosting cost is very expensive for me. Now I am thinking of a home server. but the problem is if I run it, the security risk will be there as I am willing to promote my application and invite people to use my application.I am not an expert in server security.Any one tell me how I can host my ejb application or how to establish my home server(any useful link or tutorial).
I think if I run start a home server I will have to configure security in the application server+container.(Let's forget the disadvantages of machine wast ages and power consumption as because if my home server succeeds I will continue it for future)
A: If your application will run on a tomcat server (which is not a full EJB server) you may have a look at
Amazons Elastic Beanstalk.
There you can get all the nice features from amazon like:
*
*managed application server
*load balancing
*monitoring
*database & data store
*nice management and development tools
*much much more
And if you're a new AWS-User you can get all these for a low traffic application one year for free.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql server encrypted column to be decrypted on another server How to: Encrypt a Column of Data shows how to encrypt a column of data in sql server and decrypt it in the same database instance the encryption part is exactly what I want however the decryption process would be different for me :
I will create csv files from the tables with encrypted column and will import these files into another instance of sql server where the other server should be able to decrypt .
A. how can I do the encryption on server A and do the decryption on server B ? (is it possible to send the other server the certificate file ?)
B.the encryptor server is sql server 2008 can we do the decryption on sql server 2005 or develop .net module for doing the decryption ?
A: OK I found the answer here for part A .
and for part B the answer is yes the decryption can be done in sql 2005 and I just did it .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: String Output to File So I'm trying to write a large string to a .txt file, but am having some trouble. The string I want to output is this:
0.x.y.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.1.x.y.t.x.y.t.x.y.t.2.x.y.t.s.x.y.t.s.x.y.t.s.x.y.t.s.3.x.y.t.x.y.t.4.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.x.y.t.x.y.t.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.5.
(It's a data save format, not worth getting into).
To try to test this, I first wrote this (where chunk is the above string, created outside the function, that I want to output):
void WriteToFile(std::string chunk)
{
cout << "Writing...\n";
ofstream SaveGame;
SaveGame.open("SaveGame.txt");
std::string MainString = "0.x.y.t.f.t.f.t.f.t.f.";
cout << MainString;
SaveGame << MainString;
cout << "Done!\n";
}
This test code works fine, and my output file contains 0.x.y.t.f.t.f.t.f.t.f.
But when I try this:
void WriteToFile(std::string chunk)
{
cout << "Writing...\n";
ofstream SaveGame;
SaveGame.open("SaveGame.txt");
std::string MainString = chunk;
cout << MainString;
SaveGame << MainString;
cout << "Done!\n";
}
I get gibberish:
⸰⸱⸲⸳⸴⹎慮敭琮昮洮䤮砮礮琮砮礮琮砮礮琮砮礮琮丮渮浡⹉⹎慮敭琮昮洮䤮砮礮琮砮礮琮砮礮琮砮礮琮丮渮浡⹉⸵
Needless to say, this isn't what I want.
Here is the full code of the program; note that it fails whether I use WriteToFile(Chunk) or WriteToFile(Total). The code also fails if I initialize MainString as the entire string within WriteToFile.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
void ReadFile();
void WriteToFile(std::string chunk);
int main()
{
///CHUNK SAVE FORMAT
std::string Chunk = "0.";
Chunk += "x.y.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.";
Chunk += "1.";
Chunk += "x.y.t.";
Chunk += "x.y.t.";
Chunk += "x.y.t.";
Chunk += "2.";
Chunk += "x.y.t.s.";
Chunk += "x.y.t.s.";
Chunk += "x.y.t.s.";
Chunk += "x.y.t.s.";
Chunk += "3.";
Chunk += "x.y.t.";
Chunk += "x.y.t.";
Chunk += "4.";
Chunk += "N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.";
Chunk += "N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.x.y.t.x.y.t.";
Chunk += "N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.";
Chunk += "N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.";
Chunk += "5.";
std::string Total = "0.x.y.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.t.f.1.x.y.t.x.y.t.x.y.t.2.x.y.t.s.x.y.t.s.x.y.t.s.x.y.t.s.3.x.y.t.x.y.t.4.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.x.y.t.x.y.t.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.x.y.t.N.name.t.f.m.I.x.y.t.x.y.t.x.y.t.5.";
WriteToFile(Total);
return 0;
}
void ReadFile()
{
}
void WriteToFile(std::string chunk)
{
cout << "Writing...\n";
ofstream SaveGame;
SaveGame.open("SaveGame.txt");
std::string MainString = chunk;
cout << MainString;
SaveGame << MainString;
cout << "Done!\n";
}
What's going on here?
A: Without even having tried it, I can confidently say that it works for me. The error is not in the code but elsewhere:
I suspect that you open the text file in Notepad on Windows, or a similar program. The application will try to guess the file’s encoding and (wrongly) guess that it’s a Unicode-encoded file (UTF-16).
To remedy this, specify an encoding when opening the file (if Notepad doesn’t support this use a proper text editor, such as Notepad++).
A: The 'gibberish' is the correct data, but interpreted as 16-bit unicode chars. Look at the little hex numbers in the squares:
⸰ is 0x2E and 0x30 ('.' and '0')
My guess is you're writing the file correctly, but somehow inspecting your written data in the wrong manner.
A: Do you happen to open the file using notepad? If so, notepad uses some heuristics (IsTextUnicode) to guess the encoding of the file's content if there's no BOM. In your case, that particular content makes it think it's actually Unicode...
Your code works fine. It's notepad that's broken. Read more about the notepad encoding problem here.
A: The code you present works as intended when compiled with g++ (Ubuntu/Linaro 4.5.2-8ubuntu4)
Diagnosing your problem will require information about your environment.
To clarify, does the misbehaving code echo gibberish to the terminal, as well as when you view the file?
I suspect that your function is actually generating the bits you want, but they happen to trick something into thinking that the file is unicode and not ascii.
A: There seems to be some issue in encoding. Try opening the file in editor other than notepad (wordpad or notepad++), also you will get the correct result upon reading the same file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Glazed Lists SortedList update when source object order property changed I have some object with orderProperty
class Car
{
private int order;
// getter and setter implementation
}
Then I create EventList:
EventList<Car> cars=new BasicEventList<Car>()
for (i=0;i<10;i++) {Car car=new Car(i); cars.add(car);}
Then I create SortedList based on cars to use it for TableModel
SortedList<Car> sortedCars=new SortedList<Car>(cars,carsComparator);
Here is comparator:
Comparator<Car> carsComparator implements Comparator<Car>
{
@Override
public int compare(Car o1, Car o2) {
return o1.getOrder() - o2.getOrder();
}
}
In program there are some events that change car.order property. How to notify Lists about this changes?
A: Q: How to notify Lists about order change ?
Possible case scenario not necessarily the best one.
The class car could implement the Observer design pattern. Then in each setter after, value change you could notify the listeners about it.
In the code where you are creating the list, you could add the listener to car, that check for order property change and reorder the list.
The example event
public class PropertyChangeEvent extends EventObject {
private final String propertyName;
private final Object oldValue;
private final Object newValue;
public PropertyChange(String propertyName, Object oldValue, Object newValue) {
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
}
public String getProperty() {
reutnr this.propertyName;
}
//Rest of getters were omitted.
}
And the listener
public abstract interface PropertyChangeListener extends EventListener {
public abstract void propertyChange(PropertyChangeEvent event);
}
Then you should write a class that will support the property change, is should have methods like addPropertyChangeListener(PropertyChangeListener pcl), firePropertyChange(PropertyChangeEvent pce).
When the manger of property change is done. Only thing what you have to do is.
public class Car {
private PropertyChangeManager manager = new PropertyChangeManager(Car.class);
/* The omitted code*/
public void setOrder(int order) {
int oldValue = this.order;
this.order = order;
manager.firePropertyChange("order", oldValue, this.order);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
this.manager.addPropertyChangeLIstener(pcl);
}
}
And in the class where you use that list.
private SortedList<Car> sortedCars=new SortedList<Car>();
private PropertyChangeListener listReorder = new ProprtyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
if("order".equals(event.getProperty()) {
reoderCars();
}
}
public boolean addCarToOrderList(Car car) {
/* Safety code omitted */
boolean result = false;
if(sortedCars.contains(car) == false) {
result = sortedCars.add(car);
}
if(result) {
car.addPropertyChangeListener(listReorder); //We assume that this is safe
}
return result;
}
public void reoderCars() {
synchronized(this.sortedCar) {
//the code that will sort the list.
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Maven: PL/SQL script with sql-maven-plugin throws error PLS-00103 I'm trying to use the sql-maven-plugin to execute a PL/SQL script on an Oracle 11 database. Although the script is valid PL/SQL (as far as I can tell), the execution gives me a PLS-00103 error:
The SQL script: (drop_all_tables.sql)
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
And my plugin configuration:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>oracle</groupId>
<artifactId>jdbc</artifactId>
<version>11.2.0.2.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>create-schema</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<driver>oracle.jdbc.driver.OracleDriver</driver>
<url>${jdbc.url}</url>
<username>${jdbc.username}</username>
<password>${jdbc.password}</password>
<autocommit>true</autocommit>
<srcFiles>
<srcFile>src/main/resources/sql/drop_all_tables.sql</srcFile>
</srcFiles>
</configuration>
</execution>
</executions>
</plugin>
And this is the output from the Maven execution:
[ERROR] Failed to execute: BEGIN
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE';
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] ORA-06550: line 2, column 43:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
( begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<an identifier> <a double-quoted delimited-identifier>
<a bind variable> << continue close current delete fetch lock
insert open rollback savepoint set sql execute commit forall
merge pipe purge
A: I guess the plugin is splitting the sql script by semicolons and trying to execute each part independently. The first statement would be
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE MY_TABLE';
Which is incomplete as far as oracle is concerned. The plugin does have two configuration parameters to change this behaviour, delimiter and delimiterType. By changing the configuration like below and separating your BEGIN blocks by a / on a line by itself you should be able to execute this script.
<configuration>
<delimiter>/</delimiter>
<delimiterType>row</delimiterType>
</configuration>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Are both getters and setters mandatory in JSF's managed beans? I have a JSF component which is initialized from a managed bean's getter getProperty(). Is it mandatory to also have a setter setProperty() in that managed bean?
A: It depends.
Some property bindings must be read-write. For example, if you bind the value of a component that implements EditableValueHolder. Other properties can be read-only.
If you use the binding attribute for dynamically creating component instances, this must also be read-write as per the contract defined in the specification.
A: No, not mandatory. Unless you want to be able to bind the property in a way that allows its value to be changed.
EG. If you have a list of objects you want to display in a data table then a setter may not be needed. If you bind a string property to an textInput then you will need a setter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: TextArea in Table Cell strange issue I have worked with javame + lwuit.
I encountered an unusual behavior of textarea, when it is inside table cell. Originally textarea ыhifted to right over edge of cell, then I set a fixed size, the problem goes away, but there was another - even though that textarea was stretched to full screen, the text is drawn according to old boundaries.
This looks like:
+++++++++++++++++++++++++++++++
+ This text would +
+ fit, but somehow +
+ transferred to +
+ another line +
+++++++++++++++++++++++++++++++
Please help if you are faced with similar problems or know what it was.
A: Cells in a table take up their preferred width or the cell constraint percentage if one is defined.
Preferred width for a text field/text area is calculated based on the columns value for the text area/text field. E.g. to increase the preferred width of a text area just increase the columns by deriving Table and overriding createCell like this:
protected Component createCell(Object value, int row, int column, boolean editable) {
Component c = super.createCell(value, row, column, editable);
if(c instanceof TextArea) {
((TextArea)c).setColumns(50);
}
return c;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySpace oauthentication login using php I have tried searching the internet for this, but couldn't find. Is there any documentation for authentication procedure from PHP web application for MySpace login. Can anyone give me example URL where from i can download source code to connect with MySpace account?
A: implement the cURL extension in the PHP script, works wonders... Lately Myspace has been running sweeps to clear out accounts that use any form of automation for logging into accounts and automating actions on the site... I wrote a function to grab the input variables for the form to create the post data..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the advantage of having a domain name (spotilocal) that resolves to 127.0.0.1? Not sure if this is best suited to Programmers, Server Fault or Stack Overflow. It's not, however, a question about developing for Facebook.
Facebook recently announced tighter integration with Spotify. Play/pause buttons that control the Spotify desktop software have been added to Facebook, and the most recent version of the Spotify client runs a local web server. Facebook makes calls to, for example:
http://1234.spotilocal.com:4380/remote/status.json
http://1234.spotilocal.com:4380/remote/play.json
http://1234.spotilocal.com:4380/remote/pause.json
...where *.spotilocal.com resolves to 127.0.0.1.
What is the advantage of having a domain name that resolves to localhost? Is it so that Spotify can quickly make a code change on that domain name if something should break, and so don't have to rely on Facebook?
It seems Facebook could just as easily point to:
http://127.0.0.1:4380/remote/status.json
A: the biggest reason for us when designing it was so that it would work with https without a mixed-content warning. Getting a cert for a real domain is a lot easier than getting one for 127.0.0.1.
A: One of the advantages of using a custom domain is that it looks a lot more trustworthy. I've seen a good chunk of Windows malware that sets up a local proxy server; any web requests that go to 127.0.0.1 (and not on a test web server the user knows about) would look pretty suspicious, which I'm sure both Facebook and Spotify would like to avoid.
A: It is both more user-friendly and indeed can resolve to different IPs depending on the settings of your windows 'hosts' file(which I'd imagine they're making use of). The port number is also important, as the service would reserve that port for its own use. Users don't like seeing IPs as much as they like seeing URLs because they're familiar with them, and those that aren't too computer literate may get concerned that something isn't right. They feel safer seeing the 'spotilocal' url.
A: The answer is simple : infinite subdomain and thus bypass the number of concurrent connections allowed by the browser
A: I suppose if they're running a local web server they could also do some routing on the domain name - they could have auth.spotilocal.com, remote.spotilocal.com, images.spotilocal.com etc and have the code dispatch to various things based on the incoming url.
I'm not sure there's any particular merit in that over the URL format you've described but it is another option you don't have if you just go direct to an IP address.
A: When you visit spotify.com, the site requests spotilocal and receives a token (I think it's from the spotifywebhelper process running in the background). So basically it's for tracking you.
Try it, if the spotify app is running (and you logged in), you can login on spotify.com automatically, even in private mode.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Yammer url for post something i want to find out how to post something in yammer group wall via php application.I searched in yammer api and couldn't get clear idea.can someone please help me with the url format to post something to yammer wall
A: They will tell you when you register for an API key:
Request token URL https://www.yammer.com/oauth/request_token
Access token URL https://www.yammer.com/oauth/access_token
Authorize URL https://www.yammer.com/oauth/authorize
We support plain text (recommended) as well as HMAC-SHA1. Only SSL requests are allowed.
Callback URL: None specified
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to fetch ID from other site? Just let me know how one site fetch Logged in ID of other site?
e.g. If i already logged-in in Gmail,then how any other site fetch gmail email ID into their user name textbox?
Thanks
A: This would only be possible if Gmail had an API for it. You can't read an other domain's cookies, for security reasons.
A: Such behavior is obtained via a common loggin system. On Gmail a lot other (like StackOverflow), they use OpenID, some other uses OAuth like Twitter.
But, I don't know if you're allowed to access user's data, like your their Gmail address. I've never used OpenID before.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any alias available in Perl for referencing a module name? I have multiple Perl modules. The package names seems to be big
everytime i access the functions from those modules, i need to provide something like this
&PackageName::Functionname()
is there a shortcut or alias available in Perl which can reference the packages with bigger names
Thanks
Karthik
A: You can call the function without the &:
PackageName::Functionname();
Also there is the exporter mechanism which exports function from a module to your default namespace:
use PackageName 'Functionname';
Functionname();
For further explainations how to use use see http://perldoc.perl.org/functions/use.html
How to export functions when writing your own modules, see http://perldoc.perl.org/Exporter.html
A: With Package::Alias you can alias a long package name such as Foo::Bar::Baz to baz:
use Package::Alias 'baz' => 'Foo::Bar::Baz';
baz::quux; # Invokes Foo::Bar::Baz::quux;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to rotate image and resize with transparent background using PHP GD Following code using for rotate an image and resize the same,
<?php
$src = "41611326.png";
// Get new dimensions
list($width, $height) = getimagesize($src);
$new_width = 192;
$new_height = 192;
$dstimage=imagecreatetruecolor($new_width,$new_height);
$srcimage = imagecreatefrompng($src);
$degrees = -30;
$srcimage = imagerotate($srcimage, $degrees, 0) ;
imagealphablending($dstimage, false);
imagesavealpha($dstimage, true);
imagecopyresampled($dstimage,$srcimage,0,0,0,0, $new_width,$new_height,$width,$height);
header('Content-type: image/png') ;
imagepng($dstimage) ;
?>
But its not getting transparent background for output image. How to keep the transparent background.
Any help please
A: function rotate_transparent_img( $img_resource, $angle ){
$pngTransparency = imagecolorallocatealpha( $img_resource , 0, 0, 0, 127 );
imagefill( $img_resource , 0, 0, $pngTransparency );
$result = imagerotate( $img_resource, $angle, $pngTransparency );
imagealphablending( $result, true );
imagesavealpha( $result, true );
return $result;
}
usage:
$img_resource = imagecreatefrompng('transparent_img.png');
$angle = 30;
$res = rotate_transparent_img( $img_resource, $angle );
header('Content-Type: image/png');
imagepng($res);
A: I think you need to use the imagecolortransparent() function.
Documentation
A: change :
$srcimage = imagerotate($srcimage, $degrees, 0) ;
to :
$srcimage = imagerotate($srcimage, $degrees, -1);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django URLS, how to map root to app? I am pretty new to django but experienced in Python and java web programming with different frameworks.
I have made myself a nice little django app, but I cant seem to make it match www.mysite.com as opposed to www.mysite.com/myapp.
I have defined urls and views in my urls.conf which is currently not decoupled from the app (don't mind that).
urlpatterns = patterns('myapp.views',
(r'^myapp/$', 'index'),
(r'^myapp/(?P<some_id>\d+)/global_stats/$', 'global_stats'),
(r'^myapp/(?P<some_id>\d+)/player/(?P<player_id>\d+)/$', 'player_stats'),
)
All this works like a charm. If someone goes to www.mysite.com/myapp they will hit my index view which causes a http redirect to my "correct" default url.
So, how can I add a pattern that will do the same as (r'^myapp/$', 'index') but without the /myapp--that is, www.mysite.com should suffice?
I would think this would be very basic stuff... I tried adding a line like:
(r'^$', 'index'),
however this throws me in a loop...
Hope you django gurus out there can clarify this for me!
A: This sounds strange.
Your latest attempt should work, but what I normally do - put
urlpatterns = patterns('',
(r'^$', lambda r: HttpResponseRedirect('myapp/')),
...
)
This scales better when you start adding new apps.
A: Just put an empty raw regular expression: r''
I tested here and it worked perfectly.
urlpatterns = patterns('',
url(r'', include('homepage.urls')),
url(r'^homepage/', include('homepage.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Hope it help!
A: I also wanted to have the root of my domain to directly point to a view of a sub app.
At first I created the sub app with this command:
python3 manage.py startapp main offer_finder/main
In your case it would be:
python3 manage.py startapp myApp project/somedirectory/myApp
make sure that the directory exists: mkdir -p project/somedirectory/myApp
This is my project structure: Project structure
In my case I have these directories:
offer_finder_project/offer_finder/main # sub app
offer_finder_project/offer_finder/ # main source directory
in offer_finder_project/offer_finder/urls.py I have this code:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('offer_finder.main.urls')),
]
And in offer_finder_project/offer_finder/main/urls.py I have this code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
]
And the offer_finder_project/offer_finder/main/views.py file simply contains some test code.
from django.http import HttpResponse
def index(request):
return HttpResponse("TEST app index")
This way your requests to your root domain are directed to your sub app.
Hopefully this helps someone.
This code was tested with Django 2.1.4.
A: old question here ... (as much as myself :o)
but still worth of sharing updates for Django 3.x:
In project urls.py just add:
urlpatterns = [
path('', include('myapp.urls')),
path('myapp/', include('myapp.urls')),
#path('admin/', admin.site.urls),
]
Be aware that this solution will monopolize the whole django to your hungry&selfish app :-) !!!
A: As I didn't see any answer for django 2.0 I thought I'll provide one. you have to use '' as the root url. Here is an example from django 2.0 docs
urlpatterns = [
path('', main_views.homepage),
path('help/', include('apps.help.urls')),
path('credit/', include(extra_patterns)),
]
A: I know the answer is late, but i had my fair share of hunting recently. This is what i tried with CBV..
in Project urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('app_name.urls', namespace='app_name')),
]
PS: It is always recommended to use namespace. Gives a good advantage later on.
In App urls.py
urlpatterns = [
url(r'^$', views.IndexPageView.as_view(), name='index'),
]
A: I know that this question was asked 2 years ago, but I've faced the same problem and found a solution:
In the project urls.py:
urlpatterns = patterns('',
url(r'^', include('my_app.urls')), #NOTE: without $
)
In my_app.urls.py:
urlpatterns = patterns('',
url(r'^$', 'my_app.views.home', name='home'),
url(r'^v1/$', 'my_app.views.v1', name='name_1'),
url(r'^v2/$', 'my_app.views.v2', name='name_2'),
url(r'^v3/$', 'my_app.views.v3', name='name_3'),
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
}
|
Q: Delphi OTA interface - AddPluginBitmap function does not display the caption When I use the following code in my package (a Delphi OTA/IDE plugin):
unit uSplashRegister;
interface
implementation
{$R SPLASHREGISTER.RES}
uses
Classes, Windows, Graphics, ToolsAPI,DesignIntf;
ResourceString
strSplashScreenName = 'MyTestCaption';
procedure AddSplashText;
var
bmp: HBITMAP;
begin
bmp := LoadBitmap(FindResourceHInstance(HInstance), 'LOGO');
if assigned(SplashScreenServices) then
begin
SplashScreenServices.AddPluginBitmap(strSplashScreenName,bmp,false,'Registered');
end;
end;
initialization
AddSplashText;
end.
I see the text "MyTestCaption" in Delphi XE and in Delphi 2009. In Delphi 2007 however, the caption is not visible. The word "Registered" is visible, the logo also.
Anyone an idea why I don't see the caption?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: NetBeans 6.9.1 fails to see svn configuration for SSHFS mounted drive I'm using NetBeans 6.9.1 with the Python package on OS X 10.6.8 for a project I've mounted using FUSE for OS X and MacFusion.
Initially, when checking out the project from subversion, I'm able to commit and update as I wish. However - when I restart NetBeans, it fails to see the svn configuration for the project.
The project Subversion context menu is empty.
When I try to commit from Team -> Subversion -> Commit (yes, that option is still there), it yields this error: Cannot determine repositoryRootUrl for selected context:
/Volumes/mounted/project/root/files
I've already tried the Macfusion option "-o workaround=rename" as per the resolved svn issues on http://ubuntuforums.org/showthread.php?t=1065308 .
A: Ok, the work around is quite easy... Make sure the SSHFS drive is mounted before starting NetBeans, if your project is still loaded in NetBeans.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.