text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Need to trigger an event on a video ending Working on switching from Flash to a flash player/html5 video player hybrid solution. Using video.js player. I am looking to hide the player and show a div block with javascript upon video finishing. Would anyone know how to trigger this? I have a SWF container and a video container. Anyone have any suggestions?
www.friedmanllp.com/home3.php
Following code:
<div class="video-js-box">
<!-- Using the Video for Everybody Embed Code http://camendesign.com/code/video_for_everybody -->
<video id="example_video_1" class="video-js" width="545" height="380" controls="controls" preload="auto" poster="http://www.friedmanllp.com/video/video.jpg">
<source src="http://www.friedmanllp.com/video/intro.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
<object id="flash_fallback_1" class="vjs-flash-fallback" width="545" height="380" type="application/x-shockwave-flash"
data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">
<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
<param name="allowfullscreen" value="true" />
<param name="flashvars" value='config={"playlist":["http://www.friedmanllp.com/video/video.jpg", {"url": "http://www.friedmanllp.com/video/intro.mp4","autoPlay":true,"autoBuffering":true}]}' />
<!-- Image Fallback. Typically the same as the poster image. -->
<img src="http://www.friedmanllp.com/video/video.jpg" width="545" height="380" alt="Poster Image"
title="No video playback capabilities." />
</object>
</video>
<!-- Download links provided for devices that can't play video in the browser. -->
</div>
<div style="display:none; width:545px; height:380px; overflow:hidden;">
<div class="practices_link" style="float:left; margin-bottom:1px; width:95px; height:17px; cursor:pointer;"><img class="practices_on" style="margin-bottom:1px; width:95px; height:17px;" src="images/alt/practices_on.jpg" /><img class="practices_off" style="display:none; margin-bottom:1px; width:95px; height:17px;" src="images/alt/practices_off.jpg" /></div><div style="float:left; margin-bottom:1px; width:355px; height:17px;"><img src="images/alt/blank_alt.gif" style="width:355px; height:17px;"></div><div class="services_link" style="float:left; margin-bottom:1px; width:95px; height:17px;"><img class="services_off" style="margin-bottom:1px; width:95px; height:17px; cursor:pointer;" src="images/alt/services_off.jpg" /><img class="services_on" style="display:none; margin-bottom:1px; width:95px; height:17px; cursor:pointer;" src="images/alt/services_on.jpg" /></div>
<div id="slider">
<div id="practices" style="float:left; top:0; left:0; position:relative;">
<a href="http://www.friedmanllp.com/articles.php?pcode=1"><img style="margin-bottom:1px;" src="images/alt/1.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=5"><img style="margin-bottom:1px;" src="images/alt/2.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=13"><img style="margin-bottom:1px;" src="images/alt/3.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=2"><img style="margin-bottom:1px;" src="images/alt/4.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=18"><img style="margin-bottom:1px;" src="images/alt/5.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=28"><img style="margin-bottom:1px;" src="images/alt/6.jpg" /></a>
</div>
<div id="services" style="float:left; top:-360px; left:545px; position:relative;">
<a href="http://www.friedmanllp.com/articles.php?pcode=21"><img style="margin-bottom:1px;" src="images/alt/7.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=7"><img style="margin-bottom:1px;" src="images/alt/8.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=29"><img style="margin-bottom:1px;" src="images/alt/9.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=30"><img style="margin-bottom:1px;" src="images/alt/10.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=14"><img style="margin-bottom:1px;" src="images/alt/11.jpg" /></a>
<a href="http://www.friedmanllp.com/articles.php?pcode=17"><img style="margin-bottom:1px;" src="images/alt/12.jpg" /></a>
</div>
</div>
</div>
A:
I am looking to hide the player and show a div block with javascript upon video finishing.
Look in the docs of your video player whether it has an event for it; if it doesn't, change players.
JPlayer has events, for example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to save a DateField on Blackberry? I create a DateField and add it on screen1 like above image.
User can select "time" from this DateField.
I want to save this "time" and create a new DateField has a same "time" on screen2
How I can do this?
A: Use the DateField.getDate() and DateField.setDate() methods for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HELP: application defined or object defined error when saving a workbook I get the application defined or object defined error when I save an excel file. I get an error at line: "wbk.SaveAs FPath"
Here is my code:
Dim wbk As Workbook, FPath As String
Set wbk = Workbooks.Open("\\network\drive\Template.xlsm", False, ReadOnly:=True, IgnoreReadOnlyRecommended:=True)
FPath = "\\network\drive\Saved_Files\" & _
"File Number - " & ThisWorkbook.Worksheets("Sheet1").Range("A1").Value & ".xlsm"
With Worksheets("Sheet1")
.Range("A2").Value = Test....
End With
***wbk.SaveAs FPath***
wbk.Close True
Set wbk = Nothing
A: I had this problem the other day too, You can not save to a network drive like that. It has to be mapped as a drive letter for it to work.
At least I couldn't find a way around it while tinkering with it. Excel does not seem to like network drives as a path name.
EDITED : Tim is right, my problem I stated above is a problem that just requires a hot fix from Microsoft. Shouldn't be on all machines.
Maybe this link could help though, they are describing the same type of issue. See the first comment, a lot of people seemed to have success with the code inside.
http://www.dailydoseofexcel.com/archives/2006/06/21/unc-path/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to delete columns in a CSV file? I have been able to create a csv with python using the input from several users on this site and I wish to express my gratitude for your posts. I am now stumped and will post my first question.
My input.csv looks like this:
day,month,year,lat,long
01,04,2001,45.00,120.00
02,04,2003,44.00,118.00
I am trying to delete the "year" column and all of its entries. In total there is 40+ entries with a range of years from 1960-2010.
A: import csv
with open("source","rb") as source:
rdr= csv.reader( source )
with open("result","wb") as result:
wtr= csv.writer( result )
for r in rdr:
wtr.writerow( (r[0], r[1], r[3], r[4]) )
BTW, the for loop can be removed, but not really simplified.
in_iter= ( (r[0], r[1], r[3], r[4]) for r in rdr )
wtr.writerows( in_iter )
Also, you can stick in a hyper-literal way to the requirements to delete a column. I find this to be a bad policy in general because it doesn't apply to removing more than one column. When you try to remove the second, you discover that the positions have all shifted and the resulting row isn't obvious. But for one column only, this works.
del r[2]
wtr.writerow( r )
A: Using a dict to grab headings then looping through gets you what you need cleanly.
import csv
ct = 0
cols_i_want = {'cost' : -1, 'date' : -1}
with open("file1.csv","rb") as source:
rdr = csv.reader( source )
with open("result","wb") as result:
wtr = csv.writer( result )
for row in rdr:
if ct == 0:
cc = 0
for col in row:
for ciw in cols_i_want:
if col == ciw:
cols_i_want[ciw] = cc
cc += 1
wtr.writerow( (row[cols_i_want['cost']], row[cols_i_want['date']]) )
ct += 1
A: Use of Pandas module will be much easier.
import pandas as pd
f=pd.read_csv("test.csv")
keep_col = ['day','month','lat','long']
new_f = f[keep_col]
new_f.to_csv("newFile.csv", index=False)
And here is short explanation:
>>>f=pd.read_csv("test.csv")
>>> f
day month year lat long
0 1 4 2001 45 120
1 2 4 2003 44 118
>>> keep_col = ['day','month','lat','long']
>>> f[keep_col]
day month lat long
0 1 4 45 120
1 2 4 44 118
>>>
A: You can directly delete the column with just
del variable_name['year']
A: I would use Pandas with col number
f = pd.read_csv("test.csv", usecols=[0,1,3,4])
f.to_csv("test.csv", index=False)
A: you can use the csv package to iterate over your csv file and output the columns that you want to another csv file.
The example below is not tested and should illustrate a solution:
import csv
file_name = 'C:\Temp\my_file.csv'
output_file = 'C:\Temp\new_file.csv'
csv_file = open(file_name, 'r')
## note that the index of the year column is excluded
column_indices = [0,1,3,4]
with open(output_file, 'w') as fh:
reader = csv.reader(csv_file, delimiter=',')
for row in reader:
tmp_row = []
for col_inx in column_indices:
tmp_row.append(row[col_inx])
fh.write(','.join(tmp_row))
A: Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".
outFile = open( 'newFile', 'w' )
for line in open( 'oldFile' ):
items = line.split( ',' )
outFile.write( ','.join( items[:2] + items[ 3: ] ) )
outFile.close()
A: I will add yet another answer to this question. Since the OP did not say they needed to do it with Python, the fastest way to delete the column (specially when the input file has hundreds of thousands of lines), is by using awk.
This is the type of problem where awk shines:
$ awk -F, 'BEGIN {OFS=","} {print $1,$2,$4,$5}' input.csv
(feel free to append > output.csv to the command above if you need the output to be saved to a file)
Credit goes 100% to @eric-wilson who provided this awesome answer, as a comment on the original question, 10 years ago, almost without any credit.
A: Try:
result= data.drop('year', 1)
result.head(5)
A: It depends on how you store the parsed CSV, but generally you want the del operator.
If you have an array of dicts:
input = [ {'day':01, 'month':04, 'year':2001, ...}, ... ]
for E in input: del E['year']
If you have an array of arrays:
input = [ [01, 04, 2001, ...],
[...],
...
]
for E in input: del E[2]
A: Try python with pandas and exclude the column, you don't want to have:
import pandas as pd
# the ',' is the default separator, but if your file has another one, you have to define it with sep= parameter
df = pd.read_csv("input.csv", sep=',')
exclude_column = "year"
new_df = df.loc[:, df.columns != exclude_column]
# you can even save the result to the same file
new_df.to_csv("input.csv", index=False, sep=',')
A: My take using pandas's drop in python:
import pandas as pd
df = pd.read_csv("old.csv")
new_df = df.drop("year", axis=1)
new_df.to_csv("new.csv", index=False)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: Python sockets question: socket.MSG_DONTWAIT in Windows I have a Python app that uses UDP sendto/recvfrom with the socket.MSG_DONTWAIT flag. In Linux and Mac OS X, this works just fine. However, this flag doesn't exist in the Windows environment.
What is the equivalent flag in Windows? Alternatively, how can I do non-blocking sendto/recvfrom in Windows?
A: socket.setblocking(False) switches your socket into non-blocking mode on any platform. Call this once on socket creation, and you can remove all the MSG_DONTWAIT flags.
If you need to switch between blocking and nonblocking I/O (which is usually not the case), call socket.setblocking every time you want to switch between those two.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Multiple functions in the same Element and Event What exactly happens if I add several functions in one element to the same event?
By example:
jQuery('#searchButton').click(function(){ /* logic 1 */ );
jQuery('#searchButton').click(function(){ /* logic 2 */ );
*
*always the first function added to an event will be the first to be called?
*all browsers support this type of thing?
*functions are called asynchronously?
thanks
A: Just to point out something that other answers haven't yet: jQuery indeed guarantees that the events will be triggered in the order they were added (as is referenced in John Hartsock's answer) by way of binding only one event handler to any given element, and holding an internal array of functions bound (which has the additional advantage of being able to remove anonymous functions, that otherwise you wouldn't have a reference to). That then holds true for all browsers.
However, if you mix this with any other library or use the DOM directly, there are no guarantees. The standard doesn't require implementations to follow any order, so although many implement a FIFO structure internally that isn't guaranteed. Relevant section of the standard.
A: Always the first function bound to an elements event will be the first to be called?
Quote from jQuery Docs
If there are multiple handlers registered, they will always execute in the order in which they were bound.
Reference
http://api.jquery.com/bind/
A: They're executed in the order in which they were bound. Here's an excerpt from a jquery quickstart book:
http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get the selected-row count from a list box in asp.net int countSelected = ListBoxMembers.Items.Cast<ListItem>().Where(i => i.Selected).Count();
string groupName = txt_GroupName.Text;
for (int counter = 0; counter < ListBoxMembers.Items.Count; counter++)
I have 20 items in the list, when I select only 2 ListBoxMembers.Items.Count shouws 20 and Countselected is 0
i tried this int count = ListBoxMembers.GetSelectedIndices().length;
system.web.ui.controls.listbox does not contain a definition for selected items and no extension method selevted items acceptin first argument error
<asp:ListBox ID="ListBoxMembers" runat="server" SelectionMode="Multiple" CssClass="style102"
ToolTip="Press ctrl to select multiple users" DataValueField="FirstName"></asp:ListBox>
A: Just use the functionality built-in to the ListBox ... no Linq required. (For WinForms)
int countSelected = ListBoxMembers.SelectedItems.Count;
Edit: (since the OP added to the question and it appears it is regarding ASP.NET)
int countSelected = 0;
foreach(ListItem li in ListBoxMembers.Items)
if(li.Selected)
countSelected++;
I'm not sure why the Linq statement is not working. It certainly appears that it should be... is there any difference if you explicitly include true? i => i.Selected == true
A: Your code looks correct, but you can try this:
int count = ListBoxMembers.GetSelectedIndices().Length;
A: there should be somehting like listBoxMembers.SelectedItems which returns a list of the selected items. So you could do listBoxMembers.SelectedItems.count. Now this is in VB.Net but there should be something like it for C#
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Is there a PHP Web framework that does NOT use templates? I'm looking for a PHP framework that would allow me to create HTML, not through a templating system like Smarty or Twig (which I really don't like), but directly from my view classes, through methods like:
$this->elementStart('div', array('id' => 'header',
'class' => 'cls'));
...
$this->elementEnd('div');
StatusNet does that, but it's not really a general-purpose framework. Are there any frameworks that work that way?
A: You can check out Yii. There isn't a template's system like Smarty or anything, you just have your view files with HTML and whatever PHP variables you pass over from your controllers.
EDIT: Heres an old example view I found, didn't have a link so I just pasted. The stuff referencing "widget" etc is just components of the framework, not template engine stuff.
<!-- blueprint CSS framework -->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print" />
<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" />
<![endif]-->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.css" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<body>
<div class="container" id="page">
<div id="header">
<div id="logo"><?php echo CHtml::encode(Yii::app()->name); ?></div>
</div><!-- header -->
<div id="mainmenu">
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
)); ?>
</div><!-- mainmenu -->
<?php if(isset($this->breadcrumbs)):?>
<?php $this->widget('zii.widgets.CBreadcrumbs', array(
'links'=>$this->breadcrumbs,
)); ?><!-- breadcrumbs -->
<?php endif?>
<?php echo $content; ?>
<div id="footer">
Copyright © <?php echo date('Y'); ?> by My Company.<br/>
All Rights Reserved.<br/>
<?php echo Yii::powered(); ?>
</div><!-- footer -->
</div><!-- page -->
</body>
</html>
A: At this point there is very fast DooPHP. And you can write your own templating over php. But i dont see a point.
A: yes there is Yii framework.. It allows both. If u dont want to apply any template call use renderPartial() instead of render().
Plz refer to http://www.yiiframework.com/doc/guide/1.1/en/basics.view
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between Debug and Signing key hi i am trying to get sign key MD5 finger prints for my signing certificate.can any one please tell the difference between sign key and debug key. i am able to fingure prints for debug key but for getting sign key finger print i am confused what is the meaning of my_release_key.keystore in keytool -list -alias alias_name -keystore my-release-key.keystore.
i am using the following link for getting signing key fingerprints.
http://code.google.com/android/add-ons/google-apis/mapkey.html#getfingerprint.
A: Tutoral on signing your application:
http://developer.android.com/guide/publishing/app-signing.html
About Signing in Debug Mode:
The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your .apk. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the .apk, so you do not need to sign the package with your own key.
About Sign key:
The Android system requires that all installed applications be digitally signed with a certificate whose private key is held by the application's developer. The Android system uses the certificate as a means of identifying the author of an application and establishing trust relationships between applications. The certificate is not used to control which applications the user can install. The certificate does not need to be signed by a certificate authority: it is perfectly allowable, and typical, for Android applications to use self-signed certificates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to avoid code duplication in a Android Test Application? Suppose I have an application that have similar buttons named button0, button1, etc, up to button9.
How can I do the following without duplicating code?
button0 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button0);
button1 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button1);
...
button9 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button9);
I tried to use reflection but the code looks unclean.
for (int i = 0; i <= 9; i++) {
String btnName = "button" + i;
/* do reflection stuff to link self.buttonX
with a reference to com.sample.SampleApp.R.id.buttonX */
}
A: The following code is untested, but give it a try:
Button[] buttons = new Button[]{button0, button1, button2, button3, button4, button5, button6, button7, button8, button9};
for (int i = 0; i < buttons.length, i++) {
buttons[i] = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}
With ArrayList (again untested - just to give you an idea of what I mean):
ArrayList<Button> buttons = new ArrayList<Button>();
for (int i = 0; i < 10, i++) {
buttons.add(new Button(this));
buttons.get(i) = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jquery mutiple text field update in form i need to create a html form where upon entering value on one input text field should automatically enter calculated value in another input text field using jquery.I found a source http://pastie.org/2607417,where i have input text value which output in a paragraph... Any help would be greatly appreciated
A: $("input[name='textbox1']").blur(function() {
//if u want to perform any calculation
var textbox2val=.....;
//if u want to just paste the textbox1 value
var textbox2val=$(this).val();
$("input[name='textbox2']").val(textbox2val);
});
A: Try
<input type="text" value="" id="text1" />
<p></p>
<div></div>
<script>
$("#text1").keyup(function () {
var value = $(this).val();
value2 = value*2;
value3 = value*3.7;
$("p").text(value2);
$("#text2").val(value3);
});
</script>
<input type="text" value="" id="text2" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: overriding a method in a generic class Im refactoring some unit tests. Basically, i ve found that unit tests of different clients implement a bundle of methods such as: createClientWithNullResponse, createClientWithSuccessResponse, etc.
I was wondering if its possible in Java to implement a generic solution to this, since this methods are repeated over and over in hundreds of unit classes, changing only the method signature.
But, there is a tricky. See a method example:
/**
* configures the client to return a succesful response
* @return a client configured to return a succesful response
*/
private Client1 configureClientWithSuccesfulResponse()
{
client = new Client1()
{
public CommonClientResponse processRequest( CommonsClientRequest commonsClientRequest )
{
CommonClientResponse commonClientResponse = new CommonClientResponse();
commonClientResponse.setResponse( new Client1Response() );
return commonClientResponse;
}
};
return client;
}
So, client2 will have the very same method except that signature have Client2, and the overrided method creates a new Client2Response, and the same with dozens of clients.
Additional information: processRequest is overrided to act as a mock, setting the response i wish for each method.
Client1 extends CommonsWS that extends of AbstractCommons, which is an abstract class but contains the implementation of processRequest method.
All in all, my idea is to create a Base class for all unit tests, with a bundle of generic methods where i can pass the class type, and then rewrite the processRequest for each one. Ive tried :
public class base <T extends AbstractCommonClient>{
private T configureClientWithNullResponse(Class <? extends AbstractCommonClient> clazz, Class< ? extends ClientResponse> clazz1)
{
try
{
return clazz.newInstance()
{
CommonClientResponse processRequest( CommonsClientRequest commonsClientRequest )
{
CommonClientResponse commonClientResponse = new CommonClientResponse();
commonClientResponse.setResponse( clazz1.newInstance() );
return commonClientResponse;
};
};
}
}
}
but it not even compile. Do you have any ideas of how i can begin implementing this?
A: This is a tricky question. I suggest create a Factory class that would return each type of client, and you provide the response and pass it to the factory. Something like:
public class ClientFactory {
public static createResponse(ClientResponse response) {
CommonClientResponse commonClientResponse = new CommonClientResponse();
commonClientResponse.setResponse(response);
return commonClientResponse;
}
public static Client1 createClient1(final ClientResponse response) {
return new Client1() {
public CommonClientResponse processRequest(CommonsClientRequest unused) {
return createResponse(response)
};
}
};
public static Client2 createClient2(final ClientResponse response) {
return new Client2() {
public CommonClientResponse processRequest(CommonsClientRequest unused) {
return createResponse(response)
};
}
};
..... // same for every type of Client
And you call it using:
factory.createClient1(new Client1Response());
There is still some duplication, but it helps. A little.
What do you think?
A: As you are effectively trying to create an anonymous class whose type is unknown at runtime, have you considered invoking the compiler at runtime? I haven't used it much myself, but it may be worth investigating. You can invoke it by using
JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler();
Note that this will only work if the application is run on a system where JDK is install, as JRE (does not include javac).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Usage of "isset" function Although I visit php documentation , I didn't understand usage of "isset" function .
1 - for example in a php tutorial book author wrote a text with this context : when we create a form in a first.html and we want to use from form information in second.php , we must use these 2 pieces of code :
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
$key = $_GET['q'];
if($key == "")
die("The Search key word must be entered !!!");
but I don't understand what is difference between these 2 codes ?
2 - for another example I saw this code for checking that a bottom is clicked or not :
if(isset($_POST['login_btn']))
{
....
}
but I don't understand why does it check that a bottom is clicked or not ?
A: $key="";
isset($key) //This evaluates to true.
The string is empty, but the variable is defined. The isset() function returns true, even for an empty string.
Perhaps you would like to use empty() instead, which has a broader range of conditions that evaluate to false.
A: isset checks to see if a given variable or index exists. If you assume that a variable exists and it doesn't, PHP generates a notice. All you're doing by using isset is suppressing possible notices -- which is good practice.
A: The difference is, in one instance the form was not submitted, in the second instance, the form was submitted, but with a blank value.
You wouldn't want to process a form on your page if the form has not been submitted yet.
There may also be multiple forms on one page, so you might check the button value to find out which form was submitted.
A: This function is quite simple
As on php.net:
Determine if a variable is set and is not NULL.
In your case, the isset function checks of your post variable is empty or not
A: Everyone here has already explained to you what the isset() function checks for (that being if a variable is set or not), but I think what you're really asking about is how $_GET[] and $_POST[] work. You're going to need to look more at the form that feeds this code. Read about what $_GET[] and $_POST[] variables are and I think this code will make a lot more sense to you.
For instance, your second example checks to see if the value named login_btn was sent via post method. If it was, then it runs the ... code block.
A: $key == ""; // Is $key an empty string
isset($key); // Has the $key variable been defined and not null
And just for reference, here are a few others that may be useful
empty($key); // Is $key and empty value (0, false, null, "", array())
$key == false // Is $key a falsey value (0, false, null, "", "0", array())
$key === false // Is $key a false boolean (false)
A: I'm just going to dissect your code a little bit..
isset
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
Would typically be used to see if a variable in a URL is set so something like this:
http://mysite.com/index.php?q=1
Would have $_GET['q'] set and isset($_GET['q']) would come back true
$key==""
$key = $_GET['q'];
if($key == "")
Would check to see if $key is empty. Using my previous example URL, $key would not be empty or blank, it would be 1.
Why check for a button press
The script that processes your form needs to know that it is being accessed after the form that way it does not error out. This is where you would want to make sure that the form submit button was pressed. As this is confusing, here is an example:
Say you want to insert a tag for your blogging system into a database you might have code that looks like this:
AddTag.php
<form name="addtag" method="process.php" action="post">
<input type="text" name="tagname" />
<input type="submit" name="submittag" />
</form>
process.php
<?php
if ($_POST['submittag']) {
//INSERT query
}
?>
As you can see, if process.php is accessed without the AddTag form being accessed first, the script would not try to insert your tag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Sorting by custom score in Solr does not sort consistently I assign a custom "popularity" score for each document in my Solr database. I want search results to be ordered by this custom "score" field rather than the built-in relevancy score that is the default.
First I define my score field:
<fieldType name="sint" class="solr.SortableIntField" sortMissingLast="true" omitNorms="true"/>
<field name="score" type="sint" stored="true" multiValued="false" />
Then I rebuild the index, inserting a score for each document.
To run a query, I use something like this:
(text:hello)+_val_:"score"
Now I would expect the documents to come back sorted by the "score" field, but what I get instead is:
<doc>
<int name="score">566</int>
<str name="text">SF - You lost me at hello...</str>
</doc>
<doc>
<int name="score">41</int>
<str name="text">hello</str>
</doc>
<doc>
<int name="score">77</int>
<str name="text">
CAGE PAGE-SAY HELLO (MIKE GOLDEN's Life Is Bass Remix)-VIM
</str>
</doc>
<doc>
<int name="score">0</int>
<str name="text">Hello Hello Hello</str>
</doc>
Notice that the scores come back out of order: 566, 41, 77, 0. The weird thing is that it only sorts this way with certain queries. I'm not sure what the pattern is, but so far I've only see the bad sorting when scores of "0" come back in the search results.
I've tried IntField instead of SortableIntField, and I've tried putting "sort=score desc" as a query parameter, with no change in behavior.
Am I doing something wrong, or just misunderstanding the meaning of using val:"score" in my query?
EDIT: I tried renaming the "score" field to "popularity" and got the same result.
A: score field is used by Solr internally, so may be its not a good practice to define a field with the same field name.
you can try defining a field with different field name and both the options you mentioned should work fine.
Edit - This is what i have and works fine (Solr 3.3)
Schema -
Field Type -
<fieldType name="sint" class="solr.SortableIntField" sortMissingLast="true" omitNorms="true"/>
Field -
<field name="popularity" type="int" indexed="true" stored="true" />
Data -
<add>
<doc>
<field name="id">1007WFP</field>
<field name="popularity">566</field>
<field name="text">SF - You lost me at hello...</field>
</doc>
<doc>
<field name="id">2007WFP</field>
<field name="popularity">41</field>
<field name="text">hello</field>
</doc>
<doc>
<field name="id">3007WFP</field>
<field name="popularity">77</field>
<field name="text">
CAGE PAGE-SAY HELLO (MIKE GOLDEN's Life Is Bass Remix)-VIM
</field>
</doc>
<doc>
<field name="id">4007WFP</field>
<field name="popularity">0</field>
<field name="text">Hello Hello Hello</field>
</doc>
</add>
Query -
http://localhost:8983/solr/select?q=*:*&sort=popularity%20desc
Results :-
<result name="response" numFound="4" start="0">
<doc>
<str name="id">1007WFP</str>
<int name="popularity">566</int>
</doc>
<doc>
<str name="id">3007WFP</str>
<int name="popularity">77</int>
</doc>
<doc>
<str name="id">2007WFP</str>
<int name="popularity">41</int>
</doc>
<doc>
<str name="id">4007WFP</str>
<int name="popularity">0</int>
</doc>
</result>
A: The _val_ hack actually ADDS the "popularity" field to the normally computed score of solr.
So, if you have popularity=41 on document A and popularity=77 on document B, but document A scores more than 36 points better than B for the keyword "hello", then they'll get sorted with A before B.
Use the "sort" field (as you did) that completely overrides normal sorting by score.
An alternative way could be to use a filter query (parameter fq instead of q), that filters matching document without computing any score, and then use _val_ to define your scoring formula. Since with filter queries all retrieved documents will have a score of zero, _val_ would be unaffected and behave as you originally expected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: User-specific database records This is more of a theoretical questions. Anyways,
Assume that I have a database (50 tables)
And Data in ALL of those tables should be hold specifically to one user.
What I mean is, usually we do foreign keys for each table that is user-specific. and retrieving data using something like:
select Column1,Col2,Col3 from Table where UserId=@UserId
This clutters queries significantly. Is the other way of storing such data?
A: There might be other ways, but I wouldn't say they are better. If every record in every table needs to belong to a specific user then you need a way to define that.
A possible method to reduce the number of UserId columns would be if you have child tables and you simply assumed that the parent table defined ownership and that it was implied that it's child records belonged to that user.
Example:
CarMake:
MakeId
MakeName
UserId
CarModel:
ModelId
MakeId
ModelName
Notice that CarModel does not have a UserId column, but you could assume that it inherits the same UserId of the parent CarMake record. If you cannot assume that children should always inherit the parent UserId then your original method is best.
A: What you're referring to has a name. It's called multi-tenant. The link gives some general information on multi-tenant structures.
This all depends on your RDBMS though. Oracle provides a tool which makes this very easy.
The
WHERE User_ID = @User_ID
becomes a policy which you can apply to tables. You also create a protected stored procedure to update @User_id to ensure that it cannot be changed without authority. Then every query to a table with such a policy adds the where clause in the background. It's automatic and there's no way to avoid it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: tableview delete error with touch interface after tableView:commitEditingStyle:forRowAtIndexPath: has been used I am overriding tableView:commitEditingStyle:forRowAtIndexPath to become a method that resets the textlabels in my uitableviewcells however this seams to be causing errors when the user next touches the uitableview.. it has to be touched once before itll do anything (so it takes two touches to actually get any response.)
Im hoping someone can help who has also been in a similar situation;. My code is below.. I have debuged it down to the tableView:commitEditingStyle:forRowAtIndexPath method as if I comment out tableview:titleForDeleteConfirmationButtonForRowAtIndexPath: method the same thing still happens.. So i think i am doing something wrong by overriding the other method.
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"Clear";
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
//[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
//reset uitableviewcell textlabel with default input "empty"
vehicleSearchObjectString = @"empty";
[self.tableView reloadData]; //reloads the tabels so you can see the value.
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
UPDATE
This is where I set my uitableviewcell textlabel
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"VehicleSearchCell" owner:self options:nil];
cell = vehicleSearchCell;
self.vehicleSearchCell = nil;
}
// Configure the cell...
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if(indexPath.section == 0)
{
if(indexPath.row == 0)
{
UILabel *label1;
label1 = (UILabel *)[cell viewWithTag:1];
label1.text = @"Manufacture";
UILabel *label2;
label2 = (UILabel *)[cell viewWithTag:2];
label2.text = vehicleSearchObjectString;
}
//...
A: If you're in this method, you've enabled editing on the table, I suggesting checking where/when it is disabled, as this could be the cause for a click looking like ignored.
Another lead I would follow is to avoid the reloadData method which fires quite a lot of things and sometimes not controllable by the developer. You've got the indexPath so you can target the single cell for updating by using :
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
on the table view.
Last thing I would investigate is Apple's comment on updating tables :
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/ManageInsertDeleteRow/ManageInsertDeleteRow.html#//apple_ref/doc/uid/TP40007451-CH10-SW1
It says that the commit... method must call the method :
deleteRowsAtIndexPaths:withRowAnimation:
or similar for insert, but it doesn't what happens if not.
A: So I have solved the problem!... I basically deleted the views .h.m.xib started again pretty much copied my code right across to the file and it works perfectly... I have no idea why this happened maybe something I did when I very first set it up.. I'm not sure...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best way to get 51, out of the following string What is the best way to get '51', out of the following string in ruby :
"<https://api.example.com/users/lgs/api?page=2>; rel=\"next\", <https://api.example.com/users/lgs/api?page=51>; rel=\"last\""
Thanks in advance
Luca
A: If you know there're only two numbers in that string then this is enough:
str = '"<https://api.example.com/users/lgs/api?page=2>; rel=\"next\", <https://api.example.com/users/lgs/api?page=51>; rel=\"last\""'
p str.scan(/\d+/).last #=> "51"
If not then provide more detail to make the regex more precise. Also you can add to_i if you need the answer as a number.
A: You can use regexp in this way:
res = str.match /.page=(\d+)./
in this way you are "capturing all the digits between "(" and ")" (in the last token), and you result will be store in
res.captures.first
(or simply in $1 variable)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Returning Multiple Entries With WHERE subseach I'm facing the following problem:
I have a table (new_form) that lists units that should answer a formulary. The information about those units are in another table (units), including the code of city (city_code) where they are. I want to find the information in the first table (new_form) about all the units that are there and are located in an specific city (8383).
SELECT * FROM `new_form`
WHERE `unit_number`=(
SELECT `unit_number`
FROM `units`
WHERE `city_code`=8383
)
The way it is now, I get this error:
#1242 - Subconsulta retorna mais que 1 registro
A: Use IN:
SELECT *
FROM `new_form`
WHERE `unit_number` in (
SELECT `unit_number`
FROM `units`
WHERE `city_code`=8383
)
Alternately, you could use a JOIN:
SELECT f.*
FROM `new_form` f
INNER JOIN `units` u on f.`unit_number` = u.`unit_number`
WHERE u.`city_code`=8383
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: problem writing array results to a csv file I have a csv file I need to cleanup. It contains 13 fields, but I only need 7 (Business, Address, City, St, Zip, Phone, Email)
I need to run through all of the records and create a new output of just the records with email addresses.
In nutshell... I load the original file, run the for loop, explode the results, then look for the records where the $tmp[10] index is not null. I then get the rest of the rest of required fields, and do a foreach loop and fwrite the results to a new csv file.
Depending on how I tweak the code, I get either...
A text file of just email addresses.
or
A text file of just the last record with an email address.
I have been working on this too long and I just need a fresh set of eyes to point out the problem. I am new to php, and want to make this work. Thanks on advance.
<?php
// See if file exists and is readable
$file = 'uploads/AK_Accountants.csv';
$newfile = basename($file,".csv");
$newfile = $newfile.Date("Ymd").".csw";
$fileNew = fopen('uploads/AK_'.Date("Ymd").'.csv','w+');
// Read the file into an array called $sourcefile
$sourcefile = file($file);
// Loop through the array and process each line
for ($i = 0; $i < count($sourcefile); $i++) {
// Separate each element and store in a temp array
$tmp = explode('","', $sourcefile[$i]);
// Assign each element of the temp array to a named array key
if ($tmp[10] != "") {
$sourcefile[$i] = array('Business_Name' => $tmp[1], 'Address' => $tmp[3], 'City' => $tmp[4], 'State' => $tmp[5], 'Zip' => $tmp[6], 'Phone' => $tmp[7], 'Email' => $tmp[10]);
foreach($sourcefile[$i] as $key => $value);
fwrite($fileNew, $value);
}
}
?>
A: From a quick glance:
foreach($sourcefile[$i] as $key => $value);
fwrite($fileNew, $value);
should be
foreach($sourcefile[$i] as $key => $value){
fwrite($fileNew, $value);
}
Also, you have
$newfile = $newfile.Date("Ymd").".csw";
rather than what I assume should be
$newfile = $newfile.Date("Ymd").".csv";
A: Your last foreach statement is terminated by a ';' and has no code block. Once the foreach statement has finished iterating you'll get the last value written to file i.e. just the email address.
You currently have
foreach (... ) ;
fwrite(...);.
but you probably mean
foreach( ... ) {
fwrite(...) ;
}
Been there, done that :)
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery : manipulate width and height of an img tag How do I change the height and width of an image in and unordered list with jQuery
<ul id="files">
<li><img src="1.png" /></li>
<li><img src="2.png" /></li>
<li><img src="3.png" />/li>
</ul>
My css :
ul#files li img
{
width: 100px;
height:100px;
}
I've tried this :
$('ul > li > img').width('300');
$('ul > li > img').height('300');
A: If you pass jQuery a number for a width or height, it assumes the value is in pixels, but if you pass it a string, it demands a valid CSS unit. You can either say
$('ul > li > img').width(300);
or
$('ul > li > img').width('300px');
A: Your code works fine for me.
You probably have to include these functions within $(document).ready, because you're currently running the code before the tags exist.
Example:
<script>
$(document).ready(function(){
$('ul > li > img').width('300');
$('ul > li > img').height('300');
});
</script></head><body>
<ul id="files">
<li><img src="1.png" /></li>
<li><img src="2.png" /></li>
<li><img src="3.png" />/li>
</ul>
A: use the jquery .css method instead
$('ul > li > img').css('width', '300px');
$('ul > li > img').css('height', '300px');
A: $('#files').each(function(a, b){ $(b).height(300); $(b).width(300); })
A: Give the images a class, and select it by class doing this:
<img src="1.png" class="image_class">
Javascript:
$('.image_class').height('300');
$('.image_class').width('300');
A: Apart from the mistake in your markup (last closing li tag missing <) your code will work as expected. You have to make sure your code is run after the document is ready though:
$(document).ready(function() {
$('ul > li > img').width('300');
$('ul > li > img').height('300');
});
Tested with jQuery 1.6.4.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery loading an image while async false I want to give a spinning gif image for the user to know something is happening while I am doing an ajax call with jquery. I have to use async:false because otherwise the code gets confused and we end up with a bad session variable. Here is what I have (that does not show the gif until after the call has frozen the screen.)
$('#status' + itemNum).html("<img width='14px' src='/style/images/spinner.gif'>");
if (foo == "bar") {
$.ajax({
type:"POST",
url: "foobar.html",
async:false,
data: "val1=" + escape(newValue) + "&val2=" + fieldName + "&val3=" + newValue2
})
} else {
$.ajax({
type:"POST",
url: "foobar.html",
data: "val1=" + escape(newValue) + "&val2=" + fieldName + "&val3=" + newValue3
})
document.getElementById('status' + itemNum).innerHTML = "SAVED";
}
$("#status" + itemNum).show();
setTimeout("fade_out('"+itemNum+"')", 1000);
}
In this case I only want the async when foo = bar. Can anyone let me know why the spinner.gif loads after the call. I am thinking that might be because the spinner isn't anywhere else and there is a delay in loading it, but still it doesn't show up when called multiple times (should be in cache by then), so I'm stumped.
Thanks!
A: This is not possible.
Since Javascript runs in the UI thread, async: false will freeze the browserm including all animation.
Do not use async: false!
You need to fix your code to handle asynchronous requests.
A: async: false will lock the browser, resulting in all animations being paused until processing is allowed to continue. You can however get the graphic to at least show up before the ajax calls by placing the ajax calls inside of a setTimeout with a delay of 1ms or greater. It still will not animate though, even though it is an animated gif.
Of course, the above is just a bandaid, the better solution would be to not use async: false.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I compile a 32-bit version of Live555 Streaming Media on OS X? The default compile of Live555 Streaming Media on OSX is x86_64.
How can I configure the build system to create 32-bit versions of the static libraries?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change ChildWindow CloseButton image Silverlight 3 I'm modifying the default 'ChildWindow' style and I'd like to specify a different image than the 'X' that is there by default. I've tried various things, like hooking into the OnApplyTemplate and OnOpened, where I can gain programmatic access to the button, like this:
Button closeButton = this.GetTemplateChild("CloseButton") as Button;
Yet closeButton.Content is always null. I've tried setting this to my Image and it does get set, yet the UI still displays the default 'X'. I've called UpdateLayout() as well to no avail.
Is there a way to do this either programmatically or via XAML? I've copied the default style and have made changes that are affected, yet this is one change that has me stumped. Below is a snippet of the style XAML I've been working with:
<!-- Header with Title-->
<Border x:Name="Chrome" Width="Auto" CornerRadius="5,5,0,0" Background="{StaticResource ChildWindowHeaderBackgroundBrush}">
<Grid Height="Auto" Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<ContentControl Content="{TemplateBinding Title}"
IsTabStop="False"
FontWeight="Bold"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Margin="6,0,6,0"/>
<Button x:Name="CloseButton" Margin="0,5,0,5" Grid.Column="2" IsTabStop="False" HorizontalAlignment="Center" VerticalAlignment="Center" Width="15" Height="14" Style="{StaticResource ButtonStyle}"/>
</Grid>
</Border>
I've added an Image to the Button via XAML and it still doesn't show up.
A: It's all handled via the style, in a ControlTemplate:
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="Padding" Value="0"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Disabled"/>
<VisualState x:Name="Normal"/>
<VisualState x:Name="Pressed"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="mouseOverImage">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<Visibility>Visible</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="normalImage">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<Visibility>Collapsed</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Image x:Name="normalImage" Margin="0" Source="/img/status_unknown.png" Stretch="None" />
<Image x:Name="mouseOverImage" Margin="0" Source="/img/up.png" Stretch="None" Visibility="Collapsed" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple php/mysql not working I have the following in a php script.All I get is a blank page, no errors or nothing.
error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db($database);
if(!$db){
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['id'])){
$userid = mysql_real_escape_string($_POST['id']);
echo($userid);
}
if(isset($_POST['name')){
$username = mysql_real_escape_string(htmlentities($_POST['name']));
echo($username);
}
$query = mysql_query("SELECT * FROM userinfo
WHERE userid ='$userid'")or die(mysql_error());
if(mysql_num_rows($query) > 0){
echo "yeah";
}else{
$query = mysql_query("INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)")or die(mysql_error());
if(mysql_affected_rows($query)== 1){
echo "UPDATED";
}else{
echo "NOPE";
}
}
A: You also have an error in your SQL:
INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)
The values here should be quoted:
INSERT INTO userinfo (username,userid)
VALUES ('$username', '$userid')
A: You should format your code better. Also you where missing a close ] bracket on this line, if (isset($_POST['Name')) {
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db($database);
if(!$db)
{
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['id']))
{
$userid = mysql_real_escape_string($_POST['id']);
echo($userid);
}
if(isset($_POST['name']))
{
$username = mysql_real_escape_string(htmlentities($_POST['name']));
echo($username);
}
$query = mysql_query("SELECT * FROM userinfo WHERE userid ='$userid'")or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
echo "yeah";
}
else
{
$query = mysql_query("INSERT INTO userinfo (username,userid) VALUES ($username,$userid)")or die(mysql_error());
if(mysql_affected_rows($query)== 1)
{
echo "UPDATED";
}
else
{
echo "NOPE";
}
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql query order output I have table called Property and the data is like
pid city state state_abb address1 address2
x1 NewCity NHANy NH xxxx gfg
x2 Gloucester Manchestar MA newAde xxxx
x3 OtherC NewYork NY yyyy
I want a query with search keyword to display order like (state or state_abb), city, address1, adress2
For ex:
If I search keyword with New The result output should
pid city state state_abb address1 address2
x3 OtherC NewYork NY yyyy
x1 NewCity NHANy NH xxxx gfg
x2 Gloucester Manchester MA newAde xxxx
I don't want unmatched rows.I want display only matched rows.
Thanks in advance
A: It think the question is how to order the results, not how to perform the search. Try this as your ORDER BY clause
order by
case when charindex('NEW',state) >0 then 1000 else 0 end desc,
case when charindex('NEW',city) >0 then 100 else 0 end desc,
case when charindex('NEW',address) >0 then 10 else 0 end desc
Where clause to only get matching rows
select * from Property where
city like '%New%' or
state like '%New%' or
address1 like '%New%' or
address2 like '%New%'
A: You could try something like this:
SELECT pid, city, state, stat_abb, address1, address2
from property
where city like '%New%'
OR state like '%New%'
OR address1 like '%New%'
A: This should get you started:
select * from Property where
city like '%New%' or
state like '%New%' or
address1 like '%New%' or
address2 like '%New%'
I assume you don't want to look at the pid column.
A: select *
from Property
order by case
when state like 'New%' then 1
when state_abb like 'New%' then 1
when city like 'New%' then 2
when address1 like 'New%' then 3
when address2 like 'New%' then 4
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL : SubQuery with Group By
Possible Duplicate:
SQL : How can I use sub query in a query with group by section?
Some one help me please . SQL Server cant recognize t1.sen in subquery . Error message : The multi-part identifier "t1.sen" could not be bound.
select
t1.sen,
sum(t1.d_rooz)as d1,
sum(t1.d_shab)as d2,
sum(t1.d_rooz+t1.d_shab) as d_sum,
Round((sum((1000*(t1.d_rooz+t1.d_shab))/(9500-tc.c))),1) as SSS
from
tbl_talafat_dan t1, (
select sum(t2.t_shab+t2.t_rooz) as c
from tbl_talafat_dan t2
where FCode=81 AND DCode=1 AND t2.sen<=t1.sen
) as tc
where
FCode = 81
AND DCode = 1
group by
t1.sen
A: I think you have a syntax issue here after t1:
from
tbl_talafat_dan t1, (
select sum(t2.t_shab+t2.t_rooz) as c
from tbl_talafat_dan t2
where FCode=81 AND DCode=1 AND t2.sen<=t1.sen
) as tc
It's trying to figure out what's the table to select from. You need to use either t1 or tc and join after that appropriately. Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Combining Two Images with OpenCV I'm trying to use OpenCV 2.1 to combine two images into one, with the two images placed adjacent to each other. In Python, I'm doing:
import numpy as np, cv
img1 = cv.LoadImage(fn1, 0)
img2 = cv.LoadImage(fn2, 0)
h1, w1 = img1.height,img1.width
h2, w2 = img2.height,img2.width
# Create an array big enough to hold both images next to each other.
vis = np.zeros((max(h1, h2), w1+w2), np.float32)
mat1 = cv.CreateMat(img1.height,img1.width, cv.CV_32FC1)
cv.Convert( img1, mat1 )
mat2 = cv.CreateMat(img2.height, img2.width, cv.CV_32FC1)
cv.Convert( img2, mat2 )
# Copy both images into the composite image.
vis[:h1, :w1] = mat1
vis[:h2, w1:w1+w2] = mat2
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
cv.ShowImage('test', vis2)
cv.WaitKey()
The two input images are:
https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/box.png?rev=2270
https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/box_in_scene.png?rev=2270
The resulting image is:
It may be hard to distinguish from the rest of the site, but most of the image is white, corresponding to where the individual images should be. The black area is where no image data was written.
Why is all my image data being converted to white?
A: For those who are looking to combine 2 color images into one,
this is a slight mod on Andrey's answer which worked for me :
img1 = cv2.imread(imageFile1)
img2 = cv2.imread(imageFile2)
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty matrix
vis = np.zeros((max(h1, h2), w1+w2,3), np.uint8)
#combine 2 images
vis[:h1, :w1,:3] = img1
vis[:h2, w1:w1+w2,:3] = img2
A: In order to stack horizontally:
imgHor = np.hstack((img, img))
In order to stack vertically:
imgVer = np.vstack((img, img))
In order to display:
cv2.imshow("Horizontal", imgHor) # horizontal stack
cv2.imshow("Vertical", imgVer) # vertical stack
A: import numpy as np, cv2
img1 = cv2.imread(fn1, 0)
img2 = cv2.imread(fn2, 0)
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
vis[:h1, :w1] = img1
vis[:h2, w1:w1+w2] = img2
vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
cv2.imshow("test", vis)
cv2.waitKey()
or if you prefer legacy way:
import numpy as np, cv
img1 = cv.LoadImage(fn1, 0)
img2 = cv.LoadImage(fn2, 0)
h1, w1 = img1.height,img1.width
h2, w2 = img2.height,img2.width
vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
vis[:h1, :w1] = cv.GetMat(img1)
vis[:h2, w1:w1+w2] = cv.GetMat(img2)
vis2 = cv.CreateMat(vis.shape[0], vis.shape[1], cv.CV_8UC3)
cv.CvtColor(cv.fromarray(vis), vis2, cv.CV_GRAY2BGR)
cv.ShowImage("test", vis2)
cv.WaitKey()
A: You can also use OpenCV's inbuilt functions cv2.hconcat and cv2.vconcat which like their names suggest are used to join images horizontally and vertically respectively.
import cv2
img1 = cv2.imread('opencv/lena.jpg')
img2 = cv2.imread('opencv/baboon.jpg')
v_img = cv2.vconcat([img1, img2])
h_img = cv2.hconcat([img1, img2])
cv2.imshow('Horizontal', h_img)
cv2.imshow('Vertical', v_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Horizontal Concatenation
Vertical Concatenation
A: For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.
To stack vertically (img1 over img2):
vis = np.concatenate((img1, img2), axis=0)
To stack horizontally (img1 to the left of img2):
vis = np.concatenate((img1, img2), axis=1)
To verify:
import cv2
import numpy as np
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)
The out.png image will contain img1 on the left and img2 on the right.
A: The three best way to do it using a single line of code
import cv2
import numpy as np
img = cv2.imread('Imgs/Saint_Roch_new/data/Point_4_Face.jpg')
dim = (256, 256)
resizedLena = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)
X, Y = resizedLena, resizedLena
# Methode 1: Using Numpy (hstack, vstack)
Fusion_Horizontal = np.hstack((resizedLena, Y, X))
Fusion_Vertical = np.vstack((newIMG, X))
cv2.imshow('Fusion_Vertical using vstack', Fusion_Vertical)
cv2.waitKey(0)
# Methode 2: Using Numpy (contanate)
Fusion_Vertical = np.concatenate((resizedLena, X, Y), axis=0)
Fusion_Horizontal = np.concatenate((resizedLena, X, Y), axis=1)
cv2.imshow("Fusion_Horizontal usung concatenate", Fusion_Horizontal)
cv2.waitKey(0)
# Methode 3: Using OpenCV (vconcat, hconcat)
Fusion_Vertical = cv2.vconcat([resizedLena, X, Y])
Fusion_Horizontal = cv2.hconcat([resizedLena, X, Y])
cv2.imshow("Fusion_Horizontal Using hconcat", Fusion_Horizontal)
cv2.waitKey(0)
A: in OpenCV 3.0 you can use it easily as follow:
#combine 2 images same as to concatenate images with two different sizes
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty martrix (Mat)
res = np.zeros(shape=(max(h1, h2), w1 + w2, 3), dtype=np.uint8)
# assign BGR values to concatenate images
for i in range(res.shape[2]):
# assign img1 colors
res[:h1, :w1, i] = np.ones([img1.shape[0], img1.shape[1]]) * img1[:, :, i]
# assign img2 colors
res[:h2, w1:w1 + w2, i] = np.ones([img2.shape[0], img2.shape[1]]) * img2[:, :, i]
output_img = res.astype('uint8')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
}
|
Q: Share point 2010 case study project for learning I come from asp.net , SQL server experience of 7 years. I am learning share point 2010 during my free time . At work I don't have the opportunity to work on share point but I would like to expand my skill set with sp2010. Can anyone provide me a good link to develop a share point site with some case study ...?????
Thanks in advance ....
A: Bad news: SharePoint is huge :)
I would recommend a book more than a link: SharePoint 2010 Development with Visual Studio 2010 (Microsoft .NET Development Series). This book assumes you have zero knowledge of SharePoint, but some .NET/ASP.NET experience, which seems to be your case. It explains everything very clear and at slow pace and it also has examples to put in practice the stuff you learn.
You will need a 64 bits system with Windows Server 2008 or Windows 7, at least 4 GB of RAM and VS2010.
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Binding Command inside DataGridTemplateColumn I have View(XAML included) attached to my ViewModel with commands. I need to invoke command when Button on DataGrid's row clicked. I'm using behaviors for this (regular commanding have same issue). When I click button on DataGrid - my command does not get fired.
To illustrate issue - I placed ListBox on a bottom with EXACT same binding stuff - and yes, command works. So, it's something with DataGrid/DataGridTemplateColumn
<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding}">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button Content="Cancel" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction MethodName="Cancel" TargetObject="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
<sdk:DataGrid AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding Data}" Grid.Row="1">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Select">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding ElementName=Control, Path=DataContext.ItemSelectedCommand}" CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTextColumn Binding="{Binding DeviceId}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Device" Width="Auto" FontWeight="Bold" />
<sdk:DataGridTextColumn Binding="{Binding SerialNumber}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Serial Number" Width="Auto" />
<sdk:DataGridTextColumn Binding="{Binding LastActivityOn}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Last Activity" Width="Auto" />
<sdk:DataGridTextColumn Binding="{Binding ClientVersion}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Client Version" Width="Auto" />
<sdk:DataGridTextColumn Binding="{Binding OSVersion}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="OS Version" Width="Auto" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
<ListBox Grid.Row="2" ItemsSource="{Binding Data}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding DeviceId}"></TextBlock>
<Button Content="Select">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding ElementName=Control, Path=DataContext.ItemSelectedCommand}" CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
A: I think the problem is this line
<i:InvokeCommandAction Command="{Binding ElementName=Control, Path=DataContext.ItemSelectedCommand}" CommandParameter="{Binding}" />
cause in your XAML is no element defined with name Control (aka. x:Name="Control").
You should change ElementName=Control to ElementName=LayoutRoot if the command is defined on the DataContext that is bound to LayoutRoot.
I don´t know why this works in the ListBox.
A: I am pretty sure inside a DataGrid, you still need the DataContextProxy to make bindings working. The ElementName binding doesn't work (yes, it is working for ListBox templates, but not DataGrid, this is because DataGridTemplateColumn is not in the visual tree), even in Silverlight 4.
UPDATE
In Silverlight 5, DataContextProxy is not needed in a DataGrid thanks to the support of Ancestor binding.
Example
<Button Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource AncestorType=sdk:DataGrid}}" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Windows Service not trapping error from DLL I have a Windows Service that runs every 10 minutes. Whenever there is an error on the DLL, the service isn't throwing an error. How do I make it so the error propagates back to the Windows Service and have it generate an Event Viewer message, or even start the polling again?
catch (Exception ex)
{
var errorMessage = ex.Message;
if (ex.InnerException != null)
errorMessage += " " + ex.InnerException.Message;
eventLog1.WriteEntry(errorMessage, EventLogEntryType.Error);
new Logging().LogMessageToFile(errorMessage, true);
}
A: Problem solved! Throw it again AFTER catching it.
catch (Exception ex)
{
var errorMessage = ex.Message;
if (ex.InnerException != null)
errorMessage += " " + ex.InnerException.Message;
eventLog1.WriteEntry(errorMessage, EventLogEntryType.Error);
new Logging().LogMessageToFile(errorMessage, true);
throw;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: IllegalArgumentException: No view found for id for fragment when fast switching ActionBar Tabs I am developing an Android app for tablets and not using the compatibility library.
There is just one Activity and it uses the ActionBar with 3 tabs.
In the TabListener I use setContentView to load the layout specific to that tab, and then add the relevant fragments to their frames.
This almost works exactly like I want, except when you switch between the tabs fast enough the app will crash.
I am using a Samsung Galaxy Tab as my debugging device and switching tabs is really fast. At a normal pace I can tap back and forth between them and the pages are loaded instantly. The problem is when I hyper switch between the tabs.
At first I got an
IllegalStateException: Fragment not added
as seen here:
http://code.google.com/p/android/issues/detail?id=17029
Following the suggestion to use try/catch blocks in onTabUnselected, I made the app a little more robust, but that lead to the issue at hand:
IllegalArgumentException: No view found for id 0x... for fragment ...
I have not found any other case on the web of anyone else having the same issue, so I am concerned that I may be doing something that's not supported. Again, what I am trying to do is use 3 different layouts in one Activity - when you click on a tab, the listener will call setContentView to change the layout, and then add the fragments. It works beautifully unless you start aggressively switching between tabs.
I got the idea for this from: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.html
and instead of the TabListener keeping a reference to one fragment, I have an array of them. Also, I am not using attach/detach since those were just added in API 13.
My theory is that either setContentView hasn't finished creating the views, and that's why FragmentTransaction can't add them, OR the fragments are being added for one tab when another tab is selected and setContentView is called, destroying the other set of views.
I tried to hack something in to slow down tab switching but didn't get anywhere.
Here is the code for my TabListener:
private class BTabListener<T extends Fragment> implements ActionBar.TabListener{
private int mLayout;
private Fragment[] mFrags;
private TabData mTabData;
private Activity mAct;
private boolean mNoNewFrags;
public BTabListener(Activity act, int layout, TabData td, boolean frags){
mLayout = layout;
mTabData = td;
mAct = act;
mNoNewFrags = frags;
mFrags = new Fragment[mTabData.fragTags.length];
for(int i=0; i<mFrags.length; i++){
//on an orientation change, this will find the fragments that were recreated by the system
mFrags[i] = mAct.getFragmentManager().findFragmentByTag(mTabData.fragTags[i]);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
//this gets called _after_ unselected
//note: unselected wont have been called after an orientation change!
//we also need to watch out because tab 0 always gets selected when adding the tabs
//set the view for this tab
mAct.setContentView(mLayout);
for(int i=0; i<mFrags.length; i++){
//this will be null when the tab is first selected
if(mFrags[i]==null ){
mFrags[i] = Fragment.instantiate(GUITablet.this, mTabData.classes[i].getName());
}
//if there was an orientation change when we were on this page, the fragment is already added
if(!mNoNewFrags || mDefaultTab!=tab.getPosition()){
ft.add(mTabData.containterIDs[i], mFrags[i], mTabData.fragTags[i]);
}
}
mNoNewFrags = false;
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// this gets called when another tab is selected, before it's onSelected method
for(Fragment f : mFrags){
try{ //extra safety measure
ft.remove(f);
}catch(Exception e){
e.printStackTrace();
System.out.println("unselect couldnt remove");
}
}
}
}
And finally, the stack trace:
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): java.lang.IllegalArgumentException: No view found for id 0x7f0b0078 for fragment Fraggle{40ab2230 #2 id=0x7f0b0078 dummy2}
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:729)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:926)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.app.BackStackRecord.run(BackStackRecord.java:578)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1226)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:374)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.os.Handler.handleCallback(Handler.java:587)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.os.Handler.dispatchMessage(Handler.java:92)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.os.Looper.loop(Looper.java:132)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at android.app.ActivityThread.main(ActivityThread.java:4028)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at java.lang.reflect.Method.invokeNative(Native Method)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at java.lang.reflect.Method.invoke(Method.java:491)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
09-29 01:53:08.200: ERROR/AndroidRuntime(4611): at dalvik.system.NativeStart.main(Native Method)
THANK YOU!!
A: Okay, found a way around this:
Put the references to the fragments in the layout files, and surrounded the setContentView call in onTabSelected in a try/catch block.
The exception handling took care of it!
A: I know it's a slightly old question but I was having the same and find a different work around.
The method itself is described here Avoid recreating same view when perform tab switching
but on the context of this specific crash, doing Show/Hide instead of add/replace avoids multiple fast calls to onCreateView on the fragment.
My final code ended up something like this:
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if (fragments[tab.getPosition()] == null) {
switch(tag.getPosition()){
case 0: fragments[tab.getPosition()] = new // fragment for this position
break;
// repeat for all the tabs, for each `case`
}
fragmentTransaction.add(R.id.container, fragments[tab.getPosition()]);
}else{
fragmentTransaction.show(fragments[tab.getPosition()]);
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if (fragments[tab.getPosition()] != null)
fragmentTransaction.hide(fragments[tab.getPosition()]);
}
A: Seeing a similar case in a Google Play crash report.
java.lang.IllegalStateException:
Fragment not added: MessageDisplayFragment{406e28f0 #2 id=0x7f0b0020}
at android.app.BackStackRecord.hide(BackStackRecord.java:397)
at org.kman.AquaMail.ui.AccountListActivity$UIMediator_API11_TwoPane.
closeMessageDisplay(AccountListActivity.java:2585)
Relevant code:
AbsMessageFragment fragDisplay = (AbsMessageFragment)
mFM.findFragmentById(R.id.fragment_id_message_display);
if (fragDisplay != null) {
FragmentTransaction ft = mFM.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
ft.show(some other fragment);
ft.hide(fragDisplay);
^^ This is where it crashes
The fragment is definitely there (it was returned by findFragmentById), but calling hide() blew up with the "IllegalStateException: Fragment not added"
Not added? How's it not added if findFragmentById was able to find it?
All FragmentManager calls are being made from the UI thread.
The fragment being removed (fragDisplay) was added earlier and I'm sure that its FragmentTransaction was commited.
A: Fixed it by looping through my fragments, removing any of them which have been added and then adding the new one. Also check first that you're not trying to replace it with null or an existing fragment.
Edit: looks like it was just
getChildFragmentManager().executePendingTransactions();
that stopped it from crashing
private void replaceCurrentTabFragment(TabFragment tabFragment){
if (tabFragment == null){ return; }
if (tabFragment == getActiveTabFragment()){ return; }
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
for (TabFragment fragment : mTabButtons.values()){
if (((Fragment)fragment).isAdded()){
ft.remove((Fragment)fragment);
}
}
ft.add(R.id.fragment_frameLayout, (Fragment) tabFragment);
ft.commit();
getChildFragmentManager().executePendingTransactions();
}
private TabFragment getActiveTabFragment(){
return (TabFragment) getChildFragmentManager().findFragmentById(R.id.fragment_frameLayout);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: jQuery Slide Plugin Positional Problem I have been using the Slide plugin to slide a div in to replace another div. Here is my code:
http://jsbin.com/iwemaq/15
I have had to make the position of the second div absolute so that it would stay level with the existing div. If you take this out of the example it will force the first div down and it won't be level with the second as it animates. However the height of the container no longer sticks with the content. How can I achieve this effect?
I want the 2 divs to be able to move back and forth, while level and keeping the container for both divs, any advice would really help! Thanks!
A: If I am understanding your question correctly by container you mean the border around the content. If this is correct, then a simple solution is to set the height of the container div to be the height of the div that is currently displayed when the animation completes:
<script>
jQuery(document).ready(function() {
jQuery("#showInstructionsPanel").live("click", function() {
jQuery('#mainContentContainer').hide('slide', {
direction: 'left'
}, 1000);
jQuery('#instructionsPanel').show('slide', {
direction: 'right'
}, 1000, function () { jQuery('#container').height(jQuery(this).height()); });
});
jQuery("#hideInstructionsPanel").live("click", function() {
jQuery('#mainContentContainer').show('slide', {
direction: 'left'
}, 1000, function () { jQuery('#container').height(jQuery(this).height()); });
jQuery('#instructionsPanel').hide('slide', {
direction: 'right'
}, 1000);
});
});
</script>
Edit: Here is another version that animates the height of the container to avoid the jumping that happens with the version posted above. http://jsbin.com/iqovox
A: I have an alternative, perhaps a bit more elegant solution (see http://jsfiddle.net/MM3D4/):
CSS:
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
#container {
display: block;
width: 100%;
overflow: hidden;
}
#panelWrapper {
display: block;
width: 200%;
}
#instructionsPanel, #mainContentContainer {
display: inline-block;
width: 49.8%;
}
HTML:
<div id="container" style="border:thin black solid">
<div id="panelWrapper">
<div id="mainContentContainer">
<a href="#" style="color:blue;text-decoration:underline" id="showInstructionsPanel">See Help column</a>
<div class="heading2">Main Content</div>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.<br /><br />Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p>
</div>
<div id="instructionsPanel">
<a href="#" style="color:blue;text-decoration:underline" id="hideInstructionsPanel">>- Click here to Go Back</a>
<div class="heading2">Help Panel</div>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. <br /><br />Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p>
</div>
</div>
</div>
Javascript:
jQuery(document).ready(function() {
jQuery("#showInstructionsPanel").live("click", function(e) {
jQuery('#mainContentContainer').animate({'margin-left':'-50%'}, 1000);
e.preventDefault();
});
jQuery("#hideInstructionsPanel").live("click", function(e) {
jQuery('#mainContentContainer').animate({'margin-left':'0'}, 1000);
e.preventDefault();
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails 3 tutorial Ch. 10.6 ex 5 rspec failure In solving exercise 5, I ran into a similar issue as this question. I refactored based on the answer given to that question but am still receiving the failure:
1) UsersController DELETE 'destroy' as an admin user should not self-destruct
Failure/Error: lambda do
count should have been changed by 0, but was changed by -1
# ./spec/controllers/users_controller_spec.rb:354:in `block (4 levels) in <top (required)>'
My spec:
it "should destroy the user" do
lambda do
delete :destroy, :id => @user
end.should change(User, :count).by(-1)
end
it "should redirect to the users page" do
delete :destroy, :id => @user
response.should redirect_to(users_path)
end
it "should not self-destruct" do
lambda do
delete :destroy, :id => @user.id
end.should change(User, :count).by(0)
end
and my controller:
def destroy
@user = User.find(params[:id])
if current_user == @user
flash[:notice] = "You cannot destroy yourself"
else
@user.destroy
flash[:success] = "User destroyed"
end
redirect_to users_path
end
I've checked the behavior in the browser and it works as expected. As always, any help is appreciated. Thanks!
The updated, working code:
describe "as an admin user" do
before(:each) do
@admin = Factory(:user, :email => "admin@example.com", :admin => "true")
test_sign_in(@admin)
end
it "should have links to destroy a user" do
get :index
response.should have_selector("a", :content => "delete" )
end
it "should destroy the user" do
lambda do
delete :destroy, :id => @user
end.should change{ User.count }.by(-1)
end
it "should redirect to the users page" do
delete :destroy, :id => @user
response.should redirect_to(users_path)
end
it "should not be allowed to delete itself" do
lambda do
delete :destroy, :id => @admin
end.should_not change{ User.count }
end
end
A: This bit me for a long time too. Try changing your syntax from:
should change(User, :count).by(-1)
to:
should change{ User.count }.by(-1)
Or try doing:
This is getting a little away from the book but you could try changing your syntax. The RSpec recommendation for this type of expectation is:
it "should destroy the user" do
expect{
delete :destroy, :id => @user
}.to change{ User.count }.by(-1)
end
Which I actually think is much cleaner and more readable anyway. Could you provide a link to the example as it is in the book?
A: I just realised that I read the wrong one of the three tests you posted (it would be clearer if you only posted the failing test :)
However I'm confused, your "it should not self destruct" test is exactly the same as "it should destroy the user":
it "should destroy the user" do
lambda do
delete :destroy, :id => @user
end.should change(User, :count).by(-1)
end
it "should not self-destruct" do
lambda do
delete :destroy, :id => @user.id
end.should change(User, :count).by(0)
end
You're running the same test both times but expecting different outcomes. I would take a look again at the "it should not self destruct" and see what you mean by that (I'm not sure).
I would guess that what needs to change is whatever is in the `change( xxxx ).by(0). What is it that shouldn't be changing through the test?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is drupal a good solution for websites with a very dynamic layout? I'm looking to use Drupal from an upcoming project as I've always been very interested in using it. However the more I get familiar the more I feel that Drupal isn't a good solution for a website that is very dynamic in terms of page-to-page layout alterations and just generally dynamic elements in pages.
For example, the front page of the website is going to have a newsletter signup form with 2 steps, which should be done through Ajax. Just to achieve this I've already had to install like 5 modules to get the right behaviour. And at this point I don't feel it's very user-friendly for end-users who are going to be using the CMS once it's delivered.
My question is simple, am I wrong in assuming that Drupal really isn't the right solution for this type of website? And if I am, what is the conventional approach developers take to the implementation of solutions such as the one I mentioned?
Thanks
A: I used a lot of CMS'es and all are not fine.. dirty code in them etc. and most of them are slow... Drupal is a complex solution for you and it seems ok...
You need to learn how to make modules.. it isn't that hard if you know some php...
You can modify each template .. each page.. it's not so complicated.. just try to learn some..
P.S: You can use the views in order to not write code..you might do something with them...
A: Drupal is highly customizable, but yes takes a lot of work to get set up to do what you'd like. Other CMS' provide much simpler out of the box style 'install this addon through an interface and fuhgeddaboudit' type of solutions for the more layman user. Wordpress and Joomla come to mind. If you want to go a more developer oriented route I would suggest one of the many php frameworks out there. CodeIgniter and Symfony2 are a few popular ones, but there are tons of them out there. Play around with them and see which is better suited to your needs.
A: It's about 20 lines of PHP code in Agile Toolkit. No extra javascript, no extra HTML, no plugins:
Demo: http://codepad.agiletoolkit.org/newsletter
Source: http://codepad.agiletoolkit.org/source/newsletter
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the most elegant way to implement a digest email without reinventing a queueing system? I have my transactional email system setup & by default people get emails as events happen:
class Comment
after_create :email_original_poster
def email_original_poster
UserMailer.delay.notify_author_of_comment self
end
end
However instead of getting the email as-it-happens, a chunk of my users would prefer a daily or weekly digest.
What's the cleanest most elegant way to implement this?
I've already got delayed_job running but this doesn't really feel like a delayed_job job since I'm queueing data that needs to be acted on rather than actions that need to be executed.
...without reinventing a queueing system
I know that the obvious solution is table of queued_emails and of course I could do that. The reason I'm asking the question is that to do so is reinventing a queueing system. Not only are there lots of queuing systems out there but as this well worded post from Percona points out, it's a good idea not to roll your own:
http://www.engineyard.com/blog/2011/5-subtle-ways-youre-using-mysql-as-a-queue-and-why-itll-bite-you/
Have you implemented a digest email, did you use delayed_job & what did you learn?
A: A digest looks like more appropriate to be done as a cron job like. You would still have to control to "who you have sent", to deal with crashes and errors, but the idea is to run, for example, on a daily basis, a custom rake task that craft your mail message including all info in a digest format and them send or queue for sending.
A: Obviously you shouldn't have to create your own queueing system. I haven't used delayed_job, but I have used resque in conjunction with a nice little gem called resque_mailer that should do exactly what you want. What's nice about resque_mailer is that, once it's set up, you don't have to change how you'd normally send mail: MyMailer.some_mailing({vars}).deliver If for some reason you want to not use the queue to send the mail (send it right away), you just need to add ! after deliver and it'll do just that.
Look into resque (with redis) and resque_mailer, I think it'll do what you want.
A: In case anyone wants more details on a great way to do this, there's a good overview here (second answer): Sending emails based on intervals using Ruby on Rails
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Spotlight effect in actionscript-flash Can anyone point me to a good demo or tutorial on creating a hollywood style spotlight effect?
2 soft edged rays pointing down towards a 'floor' and criss crossing each other
A: Hope these links helps you:
http://snipplr.com/view/25032/
http://www.pixeldigest.com/spotlight_effect.html
http://declic-video-fx.com/language/en-US/Tutorials/ID/569/Graffiti-Spotlight-effect.aspx
http://workflowflash.com/615/3d-moving-spotlight-and-shadow-effect-in-as3-and-flash.php
http://www.republicofcode.com/tutorials/flash/mask_as_bc/
http://abduzeedo.com/awesome-background-light-effects-flash-3-flasheff-component-giveaway
http://www.3dnewmedia.com/v1.0/index.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's a good way for a class (that manages a list) to disseminate notifications? I'm working on an iPad app has many pages for users to browse through. I'm implementing the functionality for users to 'favorite' a page so they can revisit it later.
I'm writing a Favorites class that will manage a list of the user's favorite pages. When a user presses the 'favorite' button, it will call either the addFavorite: or removeFavorite: method on the Favorites class. The input seems simple enough.
My question is: what's the best way to propagate that state-change event out to all my views? I have many redundant 'favorite' indicators scattered throughout the app, and they all need to be kept in sync. For instance, if the user favorites Pink Floyd in one view (changing the star from gray to yellow), all the other views that link to Pink Floyd need to display yellow stars next to the link instead of gray ones.
It's my understanding that there are lots of ways to do this using Objective-C notifications. I'm just looking for a clean and maintainable one. What has worked for you in the past? Thanks for your time.
A: Check up on NSNotificationCenter and NSNotification. I use notifications quite regularly especially if there is more than one party interested in the shared information making the delegate pattern difficult. The main issue with notifications I've run into is when subscribing UITableViewCell's to a notification: avoiding that dequeued cells respond to the notification.
A: Here's the code I ended up writing using NSNotificationCenter and a UITableView for bonus points. Maybe it will serve to help someone else.
In the Favorites class:
+ (void)toggleFavorite:(NSString *)artistName {
if([favorites member:artistName]) {
[favorites removeObject:artistName];
[[NSNotificationCenter defaultCenter] postNotificationName:@"favoriteRemoved"
object:artistName];
} else {
[favorites addObject:artistName];
[[NSNotificationCenter defaultCenter] postNotificationName:@"favoriteAdded"
object:artistName];
}
[[UserLibrary current] verifyLibrary];
}
One of the 3 views that interacts with the favorites: a table view, where each cell has a star:
// register for notifications
- (void)awakeFromNib {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(favoriteAdded:)
name:@"favoriteAdded"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(favoriteRemoved:)
name:@"favoriteRemoved"
object:nil];
}
// search through visible cells for the one that needs to be starred
- (void)favoriteAdded:(NSNotification *)notification {
NSString *artistName = notification.object;
for(ArtistTableViewCell *cell in [(UITableView*)self.view visibleCells]) {
if([artistName isEqualToString:cell.artistLabel.text]) {
cell.starred = YES;
}
}
}
// search through visible cells for the one that needs to be de-starred
- (void)favoriteRemoved:(NSNotification *)notification {
NSString *artistName = notification.object;
for(ArtistTableViewCell *cell in [(UITableView*)self.view visibleCells]) {
if([artistName isEqualToString:cell.artistLabel.text]) {
cell.starred = NO;
}
}
}
// when cells are created or reused, make sure the star is set properly
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ArtistTableViewCell *cell = ...
NSString *name = ...
cell.starred = [Favorites isFavorite:name];
return cell;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
The table's cell. Notice how the cells receive events from the TableView so they don't have to register for notifications (and risk being notified after being dequeued).
- (IBAction)starPressed:(id)sender {
NSString *name = artistLabel.text;
[Favorites toggleFavorite:name];
}
- (void)setStarred:(bool)isFavorite {
UIImage *img;
if(isFavorite) {
img = [UIImage imageNamed:@"filledstar30px"];
} else {
img = [UIImage imageNamed:@"emptystar30px"];
}
[favoriteButton setImage:img forState:UIControlStateNormal];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change this Hibernate property to not require a SQL statement I am using Hibernate dynamic-map to load DataEntry objects in my application. When I load any given DataEntry object, I want to retrieve the descriptive value of its InformationTypeId column. The DataEntry table's InformationTypeId is actually a code into the InformationType table. What I want Hibernate to do in the mapping file is to look-up the InformationType row for the DataEntry object and return the value of its InformationDesc column.
Here are the tables and columns:
create table DataEntry (DataEntryID, InformationTypeId)
create table InformationType (InformationTypeId, InformationTypeDesc)
The following hbm.xml file does what I would like for loading. In the informationType property, I specified the column using the read attribute. This invokes that specific SQL query.
<class entity-name="DataEntry" table="DataEntry">
<id name="dataEntryId" type="string">
<column name="DataEntryID" length="36" />
<generator class="assigned" />
</id>
<property name="informationType" type="string">
<column name="InformationTypeId"
read="(SELECT TOP 1 InformationType.InformationDesc FROM InformationType WHERE InformationType.InformationTypeId = InformationTypeId)"/>
</property>
</class>
The approach above does work for loading. It has two problems though:
*
*Updates don't work
*It requires manual SQL (MS SQL Server).
Is there a way I can customize this behavior without the SQL statement?
This seems like something that would be fairly common, but I've not seen any examples of it. I have tried the following using a join, but it does not work. I believe that this join does not work because the join is trying to join using DataEntry's private key. I need it to join using DataEntry's InformationTypeId.
<join table="informationType" optional="true" fetch="select">
<key column="InformationTypeId"/>
<property name="informationType" type="string">
<column name="InformationDesc"/>
</property>
</join>
A: Just map the InformationType table to an InformationType entity, and have an eagerly fetched many-to-one association between DataEntry and InformationType.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why compiler doesn't automatically inline freely defined function ? Instead results in linker error Example:
// header.h
void foo () // function definition in the file
{
}
// file1.cpp
#include"header.h"
...
// file2.cpp
#include"header.h"
...
Above code will result in linker error. Suppose if the compiler makes inline foo() automatically then there will not be any linker error.
My question is on language perspective. Why the compiler doesn't make it inline automatically ? Will it make any difference ?
Question in other words: "What wrong can possibly happens if compiler assumes inline in front of every free function defined ?"
A: Headers are just treated as copy-paste of the header's text. The compiler has no idea your code is in a header rather than a source file so it has to treat both the same, allowing for the error. The language specifies this.
A: Well, the answer is, basically, the C++ standard requires it to behave this way, so it does. This is part of the One Definition Rule.
Practically, the compiler must generate the linker-visible function in case you actually use it elsewhere. E.g., the following file3.cpp must work:
void foo();
void call_foo() {
foo();
}
and in order for that to work, the generated code for foo() must be available to the linker. The compiler only looks at one translation unit (the .cpp file, plus everything included in it) at once, so it can't know that its actually generating it twice. So it does. Then the linker catches it.
A: That doesn't result in a linker error. It may result in a linker error but a compiler is not required to catch that error.
Cross-module consistency is entirely a responsibility of the programmer. The C++ compiler is not required to be able to see for example that you are using the same class name in two unrelated files with different class definitions. Whatever happens it's your fault.
In general many apparently strange weaknesses of the C++ compiling model are related to the fact that it must be possible to compile a C++ program by looking only at one module (compilation unit) at a time. Is is needed to ensure that compile time and space is not going to explode for large projects.
A: It can inline it (but if it's not static it still has to have the function separately), but you are missing the point.
The compiler sees that you defined the function with the same signature twice. They could potentially differ. So at the linking phase it will generate an error to let you know that something bad is going on.
Put the declaration in the header void foo ();, and implement the function in one of the cpp files.
A: Problem with automatically inlining at link time, given how C is defined, is if two different functions with the same name exist. The underlying binary interfaces don't maintain necessary meta-data to resolve such collisions. Throw in a third source file that uses (but does not define itself) a function with such a name, and it will have no idea which one is supposed to be used.
I suspect there may be some experimental C (or more likely C-like) compilers out there that do this, but they are pretty much guaranteed to break compatibility in some way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I concatenate two AFP files together I have two AFP files and I want to concatenate them together, how can I accomplish this. I have written java code to concatenate them, using BufferedInputStream and BufferedOutputStream and the result AFP is not correctly format. I even try to use linux cat but yield the same incorrect result. Please help. I dont think the problem is my java code, but I post the code below just in case.
NOTE: One strange thing is that if I switch the order of the concatenation then it yield the right format output. For example if I concatenate A.afp then B.afp, then the output is messed up, but if I concatenate B.afp, then A.afp then it yield correct format result. But I need A.afp to appear before B.afp
public static void main(String[] args) {
String filePath1 = "C:\\dev\\harry\\ETCC_data\\3199_FI_20_20110901143009.afp";
String filePath2 = "C:\\dev\\harry\\ETCC_data\\3643_FI_49_20110901143006.afp";
ConcatenateMain cm = new ConcatenateMain();
cm.concate(filePath1, filePath2);
}
private void concate(String filePath1, String filePath2){
BufferedInputStream bis1 = null;
BufferedInputStream bis2 = null;
FileInputStream inputStream1 = null;
FileInputStream inputStream2 = null;
FileOutputStream outputStream = null;
BufferedOutputStream output = null;
try{
inputStream1 = new FileInputStream(filePath1);
inputStream2 = new FileInputStream(filePath2);
bis1 = new BufferedInputStream(inputStream1);
bis2 = new BufferedInputStream(inputStream2);
List<BufferedInputStream> inputStreams = new ArrayList<BufferedInputStream>();
inputStreams.add(bis1);
inputStreams.add(bis2);
outputStream = new FileOutputStream("C:\\dev\\harry\\ETCC_data\\output.afp");
output = new BufferedOutputStream(outputStream);
byte [] buffer = new byte[BUFFER_SIZE];
for(BufferedInputStream input : inputStreams){
try{
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) != -1)
{
output.write(buffer, 0, bytesRead);
}
}finally{
input.close();
}
}
}catch(IOException e){
}finally{
try {
output.close();
} catch (IOException e) {
}
}
}
A: AFP generated by Xenos D2e software by default contain inline resources at the top of the pages, like this
AFP file 1 resources AND AFP file 2 resources
AFP file 1 content AFP file 2 content
However when I try to concatenate these two file together, some resources will be at the middle of the concatenated file, hence mess up the result
AFP file 1 resources
AFP file 1 content
AFP file 2 resources ------> resources should not be in the middle page
AFP file 2 content
so the solution is to export all resources to an external file, then you can concatenated as follow
AFP file resources
AFP file 1 content
AFP file 2 content
This will fix the problem.
A: From example depot, here's a quick function to get the bytes from a file:
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
Then just load them both and write it out to a file
try {
FileOutputStream fos = new FileOutputStream("C:\\dev\\harry\\ETCC_data\\output.afp");
byte[] bytes1 = getBytesFromFile(new File(filePath1));
byte[] bytes2 = getBytesFromFile(new File(filePath2));
fos.write(bytes1);
fos.write(bytes2);
fos.flush();
fos.close();
}
catch(FileNotFoundException ex) { System.out.println("FileNotFoundException : " + ex); }
catch(IOException ioe) { System.out.println("IOException : " + ioe); }
A: To piggyback off the answer above about re-ordering the contents of the files, here is a suggested tool I made back when I worked at DST Output (a very large print & mail company).
I made a utility called "afp_dd", which worked like the unix "dd" command, allowing me to specify record skip and count values on the command line to extract sub-files which broke on record boundaries (the standard dd program expects fixed size records, rather than variable size with a length indicator near the beginning of each record). I could pipe the sub-files through our AFP dump program to check them, then use the output subfiles as input to create altered files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Patterns and Practices for Enforcing Object Association Cardinality I've been thinking about object-oriented principals / practices / paradigms such as SOLID, Law of Demeter, and DDD a lot lately and a theme that continues to surface is enforcing object cardinality.
Object association cardinality is derived from business rules that mandate certain entities can only be associated with a certain number of other entity objects. For example, if you're designing a system to manage warehouses, a business rule could be that a single item can only be stored in one warehouse. Obviously, enforcing these rules within the software design is a matter of implementation.
What I'm wondering is this: in the event that a rigid cardinality model is required by the business domain, what is the best way to enforce it? The techniques I can think of off hand include the following:
*
*Bi-directional references - Bi-directional associations between associated objects (object A references object B and object B references object A)
class Warehouse {
private List<Item> items;
public void RegisterItem(Item obj) {
if(obj.Warehouse != null)
throw new ArgumentException("Can only register un-owned item")
items.Add(obj);
obj.Warehouse = this;
}
}
*Encapsulate the owned entity - let the owner control its creation and deletion and provide access through a set of APIs that abstract the actual entity implementation (object A clones a passed in entity B or creates an entity B based on a passed schematic)
class Warehouse {
private List<Item> items;
public void RegisterItem(Item obj) {
items.Add((Item)obj.Clone());
}
public void RegisterItem(ItemDescriptor item) {
items.Add(new Item(item));
}
}
*Third party monitor - Have some third party that understands cardinality constraints create and hookup object associations appropriately (object C knows about the relationship between A and B and is responsible for creating and maintaining it - this method is only available to C and not available to clients)
class Warehouse {
private List<Item> items;
internal void RegisterItem(Item obj) {
items.Add(obj);
}
}
class WarehouseItemRegistrationService {
private List<Item> registeredItems;
public void RegisterItem(Warehouse warehouse, Item item) {
if(registeredItems.Contains(item))
throw new ArgumentException("Can only register un-owned items");
warehouse.RegisterItem(item);
}
}
I think each technique has its strengths and weaknesses. Bi-directional associations can add complexity to the object graph and require private APIs for updating references yet it is very simple to implement and embeds the business constraints in the business entity classes. Encapsulating the owned entity can complicate the domain model by forcing entities to have a value based description, yet it is very clean. The third party monitor technique isolates explicit cardinality enforcements to a separate class, but it also complicates the domain model.
Does anyone have any other thoughts, ideas, or better approaches?
A: Establishing associations is not a responsibility of either class. Leave it to a mediator to create the link.
Create an association class WarehouseItem to represent the association and an WarehouseItemFactory class to establish the associations by creating instances of WarehouseItem. WarehouseItemFactory will be responsible for enforcing the cardinality rules.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why are my custom framework classes not automatically available? So, I created a custom static library (framework). Then, in another project, I went to my targets 'Build Phases' tab and added my custom framework under 'Link Binary With Libraries'. It worked fine and my framework shows up just like any other (.framework, yellow toolbox, etc). However, when I attempt to use some of the classes and methods in that framework, they do not automatically show up as suggestions when I begin typing. If I type them in completely, then run the project everything works fine. Its just that they don't come up as automatic suggestions.
I've done something similar to this before and I didn't have this problem. I'm not sure what I'm missing...
A: Have you imported the correct header files for the framework?
Xcode (at least since version 4, as far as I can remember) won't provide suggestions for classes unless you import their header files, even if they're included as part of your project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python : Accessing Column Values in multi dimension array Example:
a = [[1,2,3],[4,5,6],[7,8,9]]
By doing something like a[:][0], I expect it to give me 1st elements in each row [1,4,7]
However, I get [1,2,3]. I can always make a function to do it.
def column(array,index):
result = []
for row in array:
result.append(row[index])
return result
But I was wondering: is there a smarter way of doing it?
A: The de facto standard way of manipulating arrays in such a way is to use the dedicated NumPy package.
Things work the way you want, with NumPy:
>>> import numpy
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a[:,0]
array([1, 4, 7])
In fact, the purpose of NumPy is to provide powerful array manipulations.
A: a[:][0] doesn't work because a[:] gives a copy of a. [0] then gets the first value from that copy, which is [1,2,3]
Instead use a list comprehension:
a = [[1,2,3],[4,5,6],[7,8,9]]
col = [row[0] for row in a] # => [1,4,7]
A: You can also use a one line for loop, but it is the same as what you already do:
a = [[1,2,3],[4,5,6],[7,8,9]]
result = [item[0] for item in a]
A: Use zip():
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> zip(*a)[0]
(1, 4, 7)
But note that zip builds tuples, which may require you to convert back to lists depending on your application.
A: A bit of list comprehension will do the job:
a = [[1,2,3],[4,5,6],[7,8,9]]
col = [c[0] for c in a]
No idea of speed implications.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Urban Airship. Get Android APIDs using /api/apids/ method I have been trying to use the server side api provided by Urban Airship to integrate with my Android app. I am trying to get all the APIDs registered in Urban Airship server from my Android app. I am getting a Null value always although I have registered 3 devices(emulator registration) and I can view them in https://go.urbanairship.com/api/apids/ after logging in using my app key and secret as username and password respectively.
Urban Airship has provided methods(jave code) to use the server side REST api exposed. Developers have to write their own method for functionalities that are not provided by Urban Airship. there was no method for getting APIDs , hence I wrote this method in line with the other methods.
public DeviceTokensResponse getApids() throws URISyntaxException
{
return get(DeviceTokensResponse.class, "/api/apids/");
}
I used the same server side api to successfully fetch the iPhone device tokens stored in the Urban Airship server using the api /api/device_tokens/ .
FInd below the code for fetching iPhone device tokens. This is giving the expected results.
public DeviceTokensResponse getDeviceTokens() throws URISyntaxException
{
return get(DeviceTokensResponse.class, "/api/device_tokens/");
}
I'm sorry for asking a question about a specific product like Urban Airship. I have seen the founders of Urban Airship active in this forum, hence I did not hesitate to post this question. Kindly help me with this.
A: I solved it creating a custom class called ApidList.java (which has List property)and Apid.java (which has properties corresponding to json tag key names). Once there is a one-to-one mapping of json key names and class properties , response object is populated correctly. In case the mapping fails, a null object is returned ( that is what happened to me previously)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Grails + spring-security-core: How to assign a role after user has logged in? I have a grails application that uses spring-security-core and spring-security-ldap, with authentication against Active Directory. I have a custom UserDetails and UserDetailsContextMapper.
I have a use case where a user can temporarily take on additional responsibilities for a single session. I would like to be able to assign a role to the user after they have already logged in (i.e. mid-session), and then remove that role when the session expires.
I have a user_role database table that stores relationships between users and roles. In this case, it does not matter whether the relationship is added to the database and then removed when the session expires, or simply exists in memory only. Either way, I am looking for a way to assign the role (and have it immediately apply) at a point after the user has logged in. Is this possible?
A: The UserDetails.getAuthorities() holds all roles of currently logged in user. As You already have a custom UserDetails You only need to add the additional role to the values returned by getAuthorities() on the mid-session start, and then remove it on the mid-session end. (see edit below)
ie:
public class MyUserDetails implements UserDetails {
// holds the authorities granted to the user in DB
private List<GrantedAuthority> authorities;
// holds the temporarily added authorities for the mid-session
private List<GrantedAuthority> extraAuthorities;
public GrantedAuthority[] getAuthorities() {
List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
auths.addAll(this.authorities);
auths.addAll(this.extraAuthorities);
return auths;
}
public void addExtraAuthorities(GrantedAuthority...auths) {
for (GrantedAuthority a : auths) {
this.extraAuthorities.add(a);
}
}
public void clearExtraAuthorities() {
this.extraAuthorities.clear();
}
}
Or You could create a wrapper around the original UserDetails that will hold the extra authorities and wrap it and set to the current Authentication object on the mid-session start and unwrap on the mid-session end.
Edit:
As Ben pointed out in the comment the UserDetails.getAuthorities() does get called only once, at the login, when the Authentication object is created - I forgot about that. But that brings us to the right answer, and this time I'm sure it's gonna work, cause I did it myself this way. The Authentication.getAuthorities() is the method to attend to, not the UserDetails.getAuthorities(). And I really recommend a wrapper for that, not the custom implementaion of Authentication interace, as it'll be more flexible and allow to transparentlysupport diffrent authentication mechanisms underneath.
ie:
public class MidSessionAuthenticationWrapper implements Authentication {
private Authentication wrapped;
private List<GrantedAuthority> authorities;
public MidSessionAuthenticationWrapper(
Authentication wrapped, Collection<GrantedAuthority> extraAuths) {
this.wrapped = wrapped;
this.authorities = new ArrayList<GrantedAuthority>(wrapped.getAuthorities());
this.authorities.addAll(extraAuths);
}
public Authentication getWrapped() {
return this.wrapped;
}
@Override
public Collection<GrantedAuthority> getAuthorities() {
return this.authorities;
}
// delegate all the other methods of Authentication interace to this.wrapped
}
Then all You need to do is on the mid-session start:
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
Collection<GrantedAuthority> extraAuths =
null; // calculate the extra authorities
MidSessionAuthenticationWrapper midSessionAuthentication =
new MidSessionAuthenticationWrapper(authentication, extraAuths);
SecurityContextHolder.getContext().setAuthentication(midSessionAuthentication);
And on the mid-session end:
MidSessionAuthenticationWrapper midSessionAuthentication =
(MidSessionAuthenticationWrapper) SecurityContextHolder.getContext().getAuthentication();
Authentication authentication = midSessionAuthentication.getWrapped();
SecurityContextHolder.getContext().setAuthentication(authentication);
A: I just had the same problem and found a shorter solution. I use a "before"-Filter to check if the LDAP user has a local (db) user, findOrCreate it if necessary, add roles to the user and then reauthenticate the user via:
springSecurityService.reauthenticate(user.username)
The user will then have a current list of authorities.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to apply effect with QGraphicsPixmapItem? void MainWindow::save()
{
QGraphicsPixmapItem *gpx = new QGraphicsPixmapItem(QPixmap::fromImage(_im));
QGraphicsBlurEffect *effect = new QGraphicsBlurEffect;
effect->setBlurHints(QGraphicsBlurEffect::QualityHint);
effect->setBlurRadius(20);
gpx->setGraphicsEffect(effect);
_gpx = gpx;
_image_label->setPixmap(gpx->pixmap());
_image_label->adjustSize();
MainWindow::repaint();
}
Do not mind the function name, it's just a test button. When I press it, I saw the image in the image label as is, with nothing applied to it. I have low expirience in Qt, so I can't understand what is my problem here and how can I debug it myself.
A: From what I can gather of the code you've written, you have a member variable _gpx which is a QGraphicsPixmapItem that you've already added to your scene. Every time this function is called you're replacing (and likely leaking memeory) that member variable with a whole new QGraphicsItem which you are not adding to the scene.
If your intention is to replace this item then you need to do something like this:
scene->removeItem( _gpx );
... // (contents of your save() function )
scene->addItem( _gpx );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: call javascript function from controller I need to call a JavaScript function in a Controller function.
My code looks like the following:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(DeviceLocation locationToEdit)
{
var originalLocation = (from m in _db.DeviceLocations
where m.Id == locationToEdit.Id
select m).First();
if (!ModelState.IsValid)
return View(originalLocation);
_db.ApplyCurrentValues(originalLocation.EntityKey.EntitySetName, locationToEdit);
_db.SaveChanges();
Utility.mostRecentLocationUpdate = locationToEdit;
/******************************************
need to call updateMap() JavaScript function
*******************************************/
return RedirectToAction("Locations");
}
Thanks!
A:
I need to update a map when a database changes. Ideally, the updateMap() should be a callback function that gets executed automatically when a row in the Location table changes
You need to poll the server with Ajax, use sockets (very limited support), or comet to ask the server for new data. The server can not just send down the data at will.
A: I would recommend looking into SignalR. It allows the sort of functionality you want, but it unfortunately doesn't have very good documentation, and Google is always trying to correct your searches to "signal" which is annoying when trying to find information on it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MochaUI won't load script src in window I'm trying to load a page into a modal window. I'd prefer to load with it the necessary js files rather than call them in the head where they will be loaded for every page including the ones they aren't needed on.
The problem is I can't get the scripts to load. It seems like something is preventing them from working. I've set evalScripts to false and changed the loadMethod to xhr as the docs say the evalScripts option is an option of xhr. Note: it didn't work before I changed to xhr and evalScripts: false.
Here is the call:
MUI.newthingWindow = function() {
new MUI.Modal({
id: 'newthing',
title: 'New Thing',
contentURL: '/things/newThing/1',
type: 'modal',
loadMethod: 'xhr',
evalScripts: false,
width: 600,
height: 600,
padding: { top: 43, right: 12, bottom: 10, left: 12 },
scrollbars: false
});
};
if ($('newThingLink')) {
$('newThingLink').addEvent('click', function(e){
new Event(e).stop();
MUI.newthingWindow();
});
}
Any clues?
Tanks
A: evalScripts: false,
needs to be
evalScripts: true,
to allow scripts on the page to work, but still no dice on loading external scripts via script src. Though, this will allow for a js loader (using jQuery btw "jq").
<script type="text/javascript" charset="utf-8">
jq.getScript('/assets/js/things/new_thing.js', function(data, textStatus){
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed.');
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ImageButton update source in AppWidget I'm trying to replicate the functionality of a ToggleButton in terms of RemoteViews, so I can have on in my App Widget. I have an ImageButton, and I've got it detecting clicks, but I'm having trouble changing the image that it displays when clicked. I'm under the impression I need to force the widget to update after it's been clicked to show the changes. Any idea what's the best way to go about it?
public class WifiWidget extends AppWidgetProvider {
boolean toggleState = false;
public static String ACTION_WIDGET_RECEIVER = "com.nickavv.cleanwidgets.WIFICLICK";
Context myContext;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetIds[]) {
final int N = appWidgetIds.length;
myContext = context;
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews views = new RemoteViews("com.nickavv.cleanwidgets", R.layout.wifi_toggle_layout);
Intent intent = new Intent(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.wifiToggleButton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
switchToggle();
}
}
void switchToggle() {
RemoteViews views = new RemoteViews("com.nickavv.cleanwidgets", R.layout.wifi_toggle_layout);
Log.d("toggleState",""+toggleState);
if(toggleState == false) {
views.setImageViewResource(R.id.wifiToggleButton, R.drawable.wifi_toggle_on);
} else {
views.setImageViewResource(R.id.wifiToggleButton, R.drawable.wifi_toggle_off);
}
toggleState = !toggleState;
Log.d("toggleState",""+toggleState);
}
EDIT: Added this to the bottom of switchToggle:
AppWidgetManager myAWM = AppWidgetManager.getInstance(myContext);
ComponentName cn = new ComponentName(myContext, WifiWidget.class);
onUpdate(myContext, myAWM, myAWM.getAppWidgetIds(cn));
A: Yes you have to update the widget. From the looks of this you can just call onUpdate() directly and read the button state in there to update your RemoteViews accordingly. Just use RemoteViews.setImageViewResource() to set the image that corresponds to the current button state.
All you need to call onUpdate() is the arguments, which you can get via a Context:
*
*Context: You can pass this from the receiver to switchToggle() and on to onUpdate()
*AppWidgetManager instance: get that via AppWidgetManager.getInstance(context)
*App widget ids array: use AppWidgetManager.getAppWidgetIds()
getAppWidgetIds() takes a ComponentName as an argument.
You can create one like below:
ComponentName cn = new ComponentName(context, WifiWidget.class);
You can also use this whole construct to update your app widgets from any given point, you are not bound to onUpdate(). Just use an addtional AppWidgetManager.updateAppWidget() call after you constructed your RemoteViews to publish them (which shows your UI changes).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to determine if an incredibly large number is prime? The numbers I'm trying to figure out are in this form (some examples):
2 ^ 7 - 1, 2 ^ 31 - 1, 2 ^ 127 - 1, et cetera.
This is not a homework question I was just researching primes and a lot of the information is going a bit over my head (Fourier transformations). Originally I was just using a function like this:
public static bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
{
return candidate == 2;
}
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
But that stopped working once the numbers got too big. I also looked in to the Sieve of Eratosthenes but apparently that only works for numbers of much smaller size.
To clarify, I'm not looking to write a program to find prime numbers, but rather, to determine if a given number is prime. I was looking in to the BigInteger structure in the .NET Framework and it looks promising if I could just write an efficient enough algorithm (I'd settle for something that finished in days).
I'm not sure if a mathematical proof would be better in this circumstance but I do not have much knowledge in that area as opposed to programming but if there was a proof that specialized in these kinds of numbers, that'd definitely be worth looking in to.
Thanks.
A: Factoring numbers is a big deal. The fact that it's difficult is the basis of modern cryptography.
Depending on how large your number is... You could get a list of all prime numbers up to the square root of the number you're looking for. This will be significantly less than just going up by 2 every time. The problem would be finding a list that large. If you have a number that's 10^100, then you'd need all primes of 10^50 and less, which is still a huge amount of numbers.
A: The numbers that you list: 2 ^ 7 - 1, 2 ^ 31 - 1, 2 ^ 127 - 1 are called Mersenne Numbers. There's already an entire distributed computing project to find those. It's called GIMPS.
So the answer to your question is not trivial. All the currently existing known primes of that form are listed here:
http://en.wikipedia.org/wiki/Mersenne_prime#List_of_known_Mersenne_primes
A: Do you have some upper limit on your numbers ? You mention that you'd settle for days.
If so, unless your numbers are really large, your current algo will work.
You can also look at Miller–Rabin primality test
A: Java comes with an implementation of one of the probabilistic primality tests - see java.math.BigInteger.isProbablePrime(). I thought this would mean that C# had a look-alike in the language. I didn't find one, but looking for one I found some code on the web at http://www.codeproject.com/KB/cs/biginteger.aspx.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Regular expression that optionally matches the beginning of a string I have a text containing expressions that may be generated by the regular expression "[1-9]?[0-9].[1-9]?[0-9].[1-9]?[0-9]".
No I want to perform a regular replacement that puts a "0" in front of each part when there is no first digit. So for example the string "1.10.3" would turn into "01.10.03".
My problem is that I don't know how to capture the first digit if and only if there there is no second digit in the first part. Using something like ".?([0-9])[^0-9]" would capture the first digit even if there is another one. So "12.3.4" would be turned into "02.03.04" or "102.03.04".
Do you have any idea if there is any regular expression that matches this case?
[Edit:]
I am using the VBScript Regexp Object v5.5 which supports lookaheads.
I tried to use the Regular Expression provided by the the answer of Mark Byers:
Set re = New RegExp
re.Global = True
re.Pattern = "(?:^|[^0-9])([0-9])(?![0-9])"
Dim x As String
x = "1.3.4 string"
x = re.replace(x, "0$1")
MsgBox (x)
unfortunately the result of this code is "010304 string" - the dots are stripped away. I tried to modify the pattern to match the dots and whitespaces like "(?:^|[^0-9])([0-9])([. ])" and then to replace with "0$1$2" but the result is the same.
Do you have any idea what the problem might be?
A: Using lookarounds you can find digits that are not next to another digit:
(?<![0-9])[0-9](?![0-9])
And without a lookbehind (as it is not supported by some popular regular expression engines):
(^|[^0-9])([0-9])(?![0-9])
See the second version online: Rubular
Update
Try this:
re.Pattern = "(^|[^0-9])([0-9])(?![0-9])"
Dim x As String
x = "1.3.4 string"
x = re.replace(x, "$1X$2")
A: With GNU sed you can try:
sed 's/^\(\d\.\)/0\1/;s/\.\(\d\)\./.0\1./g;\.\(\d\)$/.0\1/' INPUTFILE
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Listview onclick display options? I currently have a listview which displays summarised data, i have an onlcick listener which works fine, but I was wondering what the best option would be to display all the data of the selected item?
I don't want to use toast, too small. Need a back button to return to the listview.
A: I don't know the size of data, but here is a suggestion for you. Create a new Activity and set android:theme="@android:style/Theme.Dialog" attribute of Activity in Manifest file. So the Activity will have a Dialog appereance like this.
A: Your question is a bit vague, but I think I know what you're asking. Have you tried an AlertDialog or perhaps a custom class/Activity with the dialog theme?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I'm about to use a goto statement Save me from raptor death - is there any better way to handle this kind of structure?
while(condition) {
$this->phase1();
$this->phase2();
$this->phase3();
$this->phase4();
}
Throughout either one of those methods, the condition could be met. IMMEDIATELY after the condition is met, the loop MUST exit. If I could call break; inside of phase2(); for example, I wouldn't need a goto statement (but of course, that would throw an error).
A: Or you could use the State pattern!
In summary, instead of having a goto statement, change the internal state of $this such that methods phase1, phase2, phase3 and phase4 have no effect and are empty functions. Since they will be empty functions, you'll fly right through 'em and exit the loop!
You'll probably also need a pinch of events or the Observer pattern, to know when to change state.
A: Return a boolean from the different phases. I would return false if it didn't succeed, then check for that and break.
A: Throw an exception... sounds exceptional...
try {
while(condition) {
$this->phase1();
$this->phase2();
$this->phase3();
$this->phase4();
}
} catch (Exception $e) { }
A: Return a boolean to execute each stage until successful.
while (condition) {
if ($this->phase1() || $this->phase2() || $this->phase3() || $this->phase4()) {
// Success!
}
}
A: How about wrapping each of the phases in an if:
while(condition)
{
if(condition)
{
$this->phase1();
}
if(condition)
{
$this->phase2();
}
if(condition)
{
$this->phase3();
}
if(condition)
{
$this->phase4();
}
}
Of course, this could probably be made more compact with a bit of planning and a loop.
A: One way might be to use if() statements to check for a return value from each phase*() and break the while loop.
Something like this:
while (condition) {
if ($this->phase1()) { break; }
}
A: Please don't use a goto statement, think to the coder who will herit your code base
if your condition it's not too much of overhead, you could
while(*condition*){
$this->phase1();
if (*condition*){
$this->phase2();
}
...
}
A: $phases=array('phase1','phase2','phase3','phase4');
foreach($phases as $phase){
$this->$phase();
if(condition)break;
}
Also , you can use exceptions if you want to break out from inside of the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: unable to increase height of form in visual studio .net 3.5 I am unable to increase height of a form in Visual Studio 2008. It goes up to 812 pixels but not beyond that!
If I set it to 813 it goes back to 812.
A: You cannot make the form larger than your screen. 812 sounds about right for a something x 800 screen resolution + borders, a pretty common resolution on LCD panels with Aero fat borders enabled. This is Winforms trying to make you do the right thing by not creating a window that's hostile to the user. Who has very few options to move the window so that the bottom part is visible. Dragging the caption won't work, she can't drag it beyond the top desktop edge. Only the system menu can make it visible, very unlikely that your user will stumble on that solution.
Make it usable by setting the form's AutoScroll property to True.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does the WPF listbox change selection on mouse button down rather than button up? I had never noticed this before, but the WPF ListBox seems to change its SelectedItem when the Mouse is down, but has not yet been released. As a quick example, just create a simple ListBox with several ListBoxItems, like so:
<ListBox>
<ListBoxItem>Hello</ListBoxItem>
<ListBoxItem>World</ListBoxItem>
<ListBoxItem>ListBox</ListBoxItem>
<ListBoxItem>Test</ListBoxItem>
</ListBox>
fire up your application, press the mouse button (don't release it!) and move the mouse around. The SelectedItem will change as the mouse moves. This illustrates the larger problem (for me, at least), that a ListBox's SelectedItem will be set as soon as you mouse down, not when mouse up occurs. Usually that isn't a problem, but in my case I'd like to enable drag & drop on the items in my ListBox, without the items explicitly becoming selected.
I imagine my only recourse is to build a custom ItemsControl or Selector with selection-style semantics similar to ListBox, so really my question is more, why does ListBox work this way? Does anyone have any insight into this?
A: It might be a bit off topic but i just came up to similar problem. I do not want to do drag and drop but i want to select items on ListBox on MouseUp and not MouseDown. Although Sheena pseudo code might give some hint it still took me a while before i found out right solution. So this is my solution for my problem.
public class ListBoxSelectionItemChangedOnMouseUp : ListBox
{
protected override void OnMouseUp(MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
DependencyObject obj = this.ContainerFromElement((Visual)e.OriginalSource);
if (obj != null)
{
FrameworkElement element = obj as FrameworkElement;
if (element != null)
{
ListBoxItem item = element as ListBoxItem;
if (item != null && this.Items.Contains(item))
{
this.SelectedItem = item;
}
}
}
}
}
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
e.Handled = true;
}
}
I also wanted to select only on left mouse button. In case of drag and drop its necessary to save selected item in mouse down event and then use it in mouse up event. I hope this will help someone.
A: I personally prefer MVVM and attached properties to tweak the behavior of elements.
Furthermore the solution proposed by Tomas Kosar doesn't seem to work when the ItemsSource property is bound.
Here's what I currently use (C# 7 syntax)
public static class SelectorBehavior
{
#region bool ShouldSelectItemOnMouseUp
public static readonly DependencyProperty ShouldSelectItemOnMouseUpProperty =
DependencyProperty.RegisterAttached(
"ShouldSelectItemOnMouseUp", typeof(bool), typeof(SelectorBehavior),
new PropertyMetadata(default(bool), HandleShouldSelectItemOnMouseUpChange));
public static void SetShouldSelectItemOnMouseUp(DependencyObject element, bool value)
{
element.SetValue(ShouldSelectItemOnMouseUpProperty, value);
}
public static bool GetShouldSelectItemOnMouseUp(DependencyObject element)
{
return (bool)element.GetValue(ShouldSelectItemOnMouseUpProperty);
}
private static void HandleShouldSelectItemOnMouseUpChange(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is Selector selector)
{
selector.PreviewMouseDown -= HandleSelectPreviewMouseDown;
selector.MouseUp -= HandleSelectMouseUp;
if (Equals(e.NewValue, true))
{
selector.PreviewMouseDown += HandleSelectPreviewMouseDown;
selector.MouseUp += HandleSelectMouseUp;
}
}
}
private static void HandleSelectMouseUp(object sender, MouseButtonEventArgs e)
{
var selector = (Selector)sender;
if (e.ChangedButton == MouseButton.Left && e.OriginalSource is Visual source)
{
var container = selector.ContainerFromElement(source);
if (container != null)
{
var index = selector.ItemContainerGenerator.IndexFromContainer(container);
if (index >= 0)
{
selector.SelectedIndex = index;
}
}
}
}
private static void HandleSelectPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
e.Handled = e.ChangedButton == MouseButton.Left;
}
#endregion
}
Now you can apply this to any ListBox (or Selector-derived class), e.g.
<ListBox ItemsSource="{Binding ViewModelItems}"
SelectedItem="{Binding SelectedViewModelItem}"
ui:SelectorBehavior.ShouldSelectItemOnMouseUp="True" />
A: I'm assuming you already tried to make a new mouse-down event that does what you want, and override the standard behavior that way... here's some pseudo-code that should do the trick:
ListBoxItem selected;
on_any_event_that_should_change_whats_selected()
{
selected=whatever_you_want_selected;
}
on_selection_changed()
{
theListBox.selectedItem=selected;
}
My wpf skillz are a little rusty but I think you'll need to store the item and then generate a container, so this pseudocode is a vast oversimplification but the algorithm should do the trick.
A: An alternative approach that seems to be working for me:
private class SelectOnMouseUpListViewItem: ListViewItem
{
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (IsSelected)
e.Handled = true;
base.OnMouseLeftButtonDown(e);
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (!IsSelected)
base.OnMouseLeftButtonDown(e);
base.OnMouseLeftButtonUp(e);
}
}
protected override DependencyObject GetContainerForItemOverride() // in ListView
{
return new SelectOnMouseUpListViewItem();
}
A: I've found similar problem with ListView. I wasn't able to start drag-drop of some item, without loosing selection of another.
I solved it by deriving from ListView, and handling PreviewMouseDown event. Instead of this, I selected item on MouseUp.
Rest of drag logic is implemented using Reactive Extensions.
ListBox is similar to ListView, so you might be able to just derive from ListBox and it'll work.
Code:
public class DragDroppableListView : ListView
{
private IDisposable _subscription;
public DragDroppableListView()
{
Loaded += OnControlLoaded;
Unloaded += OnControlUnloaded;
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
if (e.ChangedButton != MouseButton.Left) return;
var obj = ContainerFromElement((Visual)e.OriginalSource);
if (obj == null) return;
var element = obj as FrameworkElement;
if (element == null) return;
var item = element as ListBoxItem;
if (item == null) return;
// select item
item.IsSelected = true;
}
private void OnControlUnloaded(object sender, RoutedEventArgs e)
{
if (_subscription != null)
_subscription.Dispose();
}
private void OnControlLoaded(object sender, RoutedEventArgs e)
{
var mouseDown = Observable.FromEventPattern<MouseButtonEventArgs>(this, "PreviewMouseDown");
var mouseUp = Observable.FromEventPattern<MouseEventArgs>(this, "MouseUp");
var mouseMove = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove");
_subscription = mouseDown
.Where(a => a.EventArgs.LeftButton == MouseButtonState.Pressed)
.Where(o => !IsScrollBar(o.EventArgs))
.Do(o => o.EventArgs.Handled = true) // not allow listview select on mouse down
.Select(ep => ep.EventArgs.GetPosition(this))
.SelectMany(md => mouseMove
.TakeWhile(ep => ep.EventArgs.LeftButton == MouseButtonState.Pressed)
.Where(ep => IsMinimumDragSeed(md, ep.EventArgs.GetPosition(this)))
.TakeUntil(mouseUp))
.ObserveOnDispatcher()
.Subscribe(_ => OnDrag());
}
private void OnDrag()
{
var item = GetItemUnderMouse();
if (item == null) return;
DragDrop.DoDragDrop(
this,
new DataObject(typeof(object), item),
DragDropEffects.Copy | DragDropEffects.Move);
}
private ListViewItem GetItemUnderMouse()
{
return Items.Cast<object>()
.Select(item => ItemContainerGenerator.ContainerFromItem(item))
.OfType<ListViewItem>()
.FirstOrDefault(lvi => lvi.IsMouseOver);
}
private static bool IsMinimumDragSeed(Point start, Point end)
{
return Math.Abs(end.X - start.X) >= SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(end.Y - start.Y) >= SystemParameters.MinimumVerticalDragDistance;
}
private bool IsScrollBar(MouseEventArgs args)
{
var res = VisualTreeHelper.HitTest(this, args.GetPosition(this));
if (res == null) return false;
var depObj = res.VisualHit;
while (depObj != null)
{
if (depObj is ScrollBar) return true;
// VisualTreeHelper works with objects of type Visual or Visual3D.
// If the current object is not derived from Visual or Visual3D,
// then use the LogicalTreeHelper to find the parent element.
if (depObj is Visual || depObj is System.Windows.Media.Media3D.Visual3D)
depObj = VisualTreeHelper.GetParent(depObj);
else
depObj = LogicalTreeHelper.GetParent(depObj);
}
return false;
}
}
A: Using reflection is never ideal, but here is some code that works for me.
public class SelectOnMouseUpListBoxItem : ListBoxItem
{
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
var received = _receivedMouseDown;
_receivedMouseDown = null;
// validate that the mouse left button down event was called on this list box item
if (received != this)
return;
var parent = WpfUtility.FindVisualParent<SelectOnMouseUpListBox>(this);
parent.NotifyListItemClickedImp(this, e.ChangedButton);
base.OnMouseLeftButtonUp(e);
}
private SelectOnMouseUpListBoxItem _receivedMouseDown;
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
_receivedMouseDown = this;
e.Handled = true;
base.OnMouseLeftButtonDown(e);
}
}
public class SelectOnMouseUpListBox : ListBox
{
static SelectOnMouseUpListBox()
{
_notifyListItemClickedMethodInfo = typeof(ListBox).GetMethod("NotifyListItemClicked", BindingFlags.Instance | BindingFlags.NonPublic);
if (_notifyListItemClickedMethodInfo == null)
throw new NotSupportedException("Failed to get NotifyListItemClicked method info by reflection");
}
private static readonly MethodInfo _notifyListItemClickedMethodInfo;
protected override DependencyObject GetContainerForItemOverride()
{
return new SelectOnMouseUpListBoxItem();
}
public void NotifyListItemClickedImp(ListBoxItem item, MouseButton button)
{
_notifyListItemClickedMethodInfo.Invoke(this, new object[] {item, button});
}
}
This retains the usual selection behaviour depending on the SelectionMode (Single, Multiple, Extended) of the ListBox.
A: Tomas' answer is good, but may need to be tweaked in order for it to work. I had to do some casts and its not necessarily pretty, but it gets the job done.
This should be fairly straight forward to update to your needs.
private void MembersList_MouseUp(object sender, MouseButtonEventArgs e) {
if (e.ChangedButton == MouseButton.Left) {
DependencyObject obj = myListBox.ContainerFromElement((Visual)e.OriginalSource);
if (obj != null) {
FrameworkElement element = obj as FrameworkElement;
if (element != null) {
ListBoxItem item = element as ListBoxItem;
if (item != null && ((MyViewModel)myListBox.DataContext).myListObject.Contains((MyListItem)item.DataContext)) {
myListBox.SelectedItem = item.DataContext;
}
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: .NET SQL new table doesn't exist NOTE: This issue has been resolved, but lead to a new question.
I'm getting this error:
System.Data.SqlClient.SqlException "Invalid object name [tablename]"
I'm working on a DB update to ship with an update to a deployed product. The first time the newly updated application runs, the database update runs, and it has two primary stages.
*
*Run script update.sql to add new tables to the database
*Call some methods to copy some data from existing tables to popuplate the new tables, and do some math/make some adjustments.
Step one works flawlessly. Step two throws the exception above whenever it references any of the new tables. The code called where the exception pops up is used several times throughout the (new version of the)application, and is generally fine. One would expect that this problem would happen if this code ran with the old version of the database (since the tables it uses don't exist), but in this case, the tables have just been added.
Update code:
internal void Update()
{
RunScript(); //runs the SQL script, adds tables to the db
OtherClass oc = new OtherClass();
oc.PrepData(); //no error, just makes some minor tweaks to existing table
oc.CopyData(); //throws exception, none of the new tables appear to exist
oc.AdjustData(); //manipulates the data in the new table, probably throws exception but currently unreachable
}
public class OtherClass
{
private AppEntities db;
public OtherClass()
{
db = new AppEntities();
//other constructor activity
}
internal void CopyData()
{
foreach(DataItem di in db.DataItems) //This throws the exception (with any of the new tables)
{
}
}
}
As shown above, the exception is thrown by an entity set that is initialized after the tables are added to the database, yet it still does not acknowledge that any of them exist.
Has anyone encountered anything like this? Is there a way around it?
UPDATE:
I've discovered something, which I thought must be the problem. The declaration of AppEntities db in OtherClass had been changed to private AppEntities db = new AppEntities();, and it was no longer initialized in the constructor, resulting in it being created before the script is run. Unfortunately, fixing this still yields the same issue.
UPDATE:
In order to assure the data context knows about the new table, I've altered the way I run the script.
Previously (properly executed script against database, application can't find new tables):
StreamReader sr = new StreamReader(File.Open(String.Format("{0}/Scripts/CURRENTVERSION.sql", AppDomain.CurrentDomain.BaseDirectory), FileMode.Open));
string UpdateScript = sr.ReadToEnd();
sr.Close();
//Here connectionstring was the database's connection taken from the .edmx file and trimmed of arguments that caused exceptions as invalid
SqlConnection connection = new SqlConnection(connectionstring);
SqlCommand command = new SqlCommand(UpdateScript);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Currently:
StreamReader sr = new StreamReader(File.Open(String.Format("{0}/Scripts/CURRENTVERSION.sql", AppDomain.CurrentDomain.BaseDirectory), FileMode.Open));
string UpdateScript = sr.ReadToEnd();
sr.Close();
System.Data.Common.DbCommand command = db.Connection.CreateCommand();
command.CommandText = UpdatScript;
//command.CommandText = @UpdateScript;
db.Connection.Open();
command.ExecuteNonQuery();
I've tried both the commented and un-commented lines (with/without the @), but it claims a syntax error on every line in the script (which is the same script the first method executes flawlessly).
db.Connection.Close();
UPDATE:
Using this question and answer, I was able to successfully execute the SQL script using the AppEntities connection, and the tables did appear in the database. However, AppEntities (an object of the class initialized after the script has run) still throws the exception of invalid object name.
Is there a way to force the data context to update itself from the database at runtime?
UPDATE (with solution):
Digging into AppEntities (as per Chris Lively's suggestion) was a huge headache, but it did lead me to digging into some of the config files as well. It was there I found that the new tables were being mapped to with a singular name, rather than plural (TableForEntity rather than TableForEntities), where previously they had been plural (when it worked). The old tables were all plural as well. Changing the new tables to plural here caused all sorts of errors, so I ended up just changing the SQL script to name them in the singular. Surprisingly, this worked.
Considering the SQL script which named them in the plural was autogenerated based on a database that actually worked (where they were named plurally), why should changing the naming work? If anything, that should cause the problem it fixed.
A: I'm not sure what AppEntities is but I'm pretty confident that it does not reflect the structure of your new database.
I'm going to take a guess that it is some form of generated code that is based purely on the initial version of the database and has not been recodegen'd (sp?) to hold information about the new tables. Hence, the error.
This would also explain why the application still fails at that same location when you have created the tables before it even runs.
To sum up, investigate AppEntities and figure out exactly how that thing works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Need Help With Javascript Scope I need some help understanding scope in Javascript. I posted a similar question earlier and prematurely marked it as accepted. (The solution didn't work in my case).
I've got javascript (a) and jQuery script (b). I need to access some values from (a) in (b).
In (a) I've got:
function map_maker_js( args ) {
var map = new google.maps.Map(document.getElementById( args['id'] ), myOptions);
//rest of the code for building the map goes here
google.maps.event.addListener(map, 'tilesloaded', viewport_bounds);
function viewport_bounds() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var maxLat = ne.lat();
var maxLong = ne.lng();
var minLat = sw.lat();
var minLong = sw.lng();
var the_maps_bounds = [maxLat, maxLong, minLat, minLong];
//return(the_maps_bounds);
}
}
In jQuery script (b), I need the_maps_bounds, which is calculated by viewport_bounds(). I can't simply move google.maps.event.addListener(map, 'tilesloaded', viewport_bounds); into (b), because 'map' is out of scope. This won't work in (b):
google.maps.event.addListener(map, 'tilesloaded', function() {
// This code will only execute after event `tilesloaded` happens
var the_maps_bounds = viewport_bounds()
// now do something with the bounds
// ...
});
If I move the viewport_bounds() function outside of map_maker_js, then I'll have to add map as an argument, which won't work in (b), either.
The code that I'm working on is in a WordPress plugin. I don't think that that will affect the answer, though.
I'm learning still learning javascript. What's the best way to solve this?
Thank you
Update:
Thank you Rob W for your suggestion. This is what I've got now:
var the_maps_bounds;
function map_maker_js( args ) {
var map = new google.maps.Map(document.getElementById( args['id'] ), myOptions);
//rest of the code for building the map goes here
google.maps.event.addListener(map, 'tilesloaded', viewport_bounds);
function viewport_bounds() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var maxLat = ne.lat();
var maxLong = ne.lng();
var minLat = sw.lat();
var minLong = sw.lng();
the_maps_bounds = [maxLat, maxLong, minLat, minLong];
alert(the_maps_bounds); //is the the_map_bounds working
return(the_maps_bounds);
}
}
In script (b), I've got:
jQuery.noConflict();
jQuery(document).ready(function($) { //how jQuery scripts are written in WordPress
alert(window.the_maps_bounds);
//rest of my functions
});
When I view the page, I get "undefined" in the alert box and then, an alert box with the lat longs. I also tried the alert without 'window'. And on the ready event:
$('#map').ready(function() {
alert(the_maps_bounds);
});
I guess that the_maps_bounds in script (b) doesn't have a value for soem reason. Is the alert firing before its value is set in script (a)? Is something else going on? Any ideas? Thank you.
A: Remove var before your the_maps_bound declarations, and use this code:
var the_maps_bound;
function map_maker_js( args ) {
var map = new google.maps.Map(document.getElementById( args['id'] ), myOptions);
//rest of the code for building the map goes
....
This way, you define the_maps_bound outside the scope of these functions. If your functions are defined in the global scope (window), the the_maps_bound variable will also be accessible through window.the_maps_bound. Note: the var declaration has to be in the closest shared parent scope in order to get the code work (see below for a more detailled explanation).
It's a good practice to use var, to prevent leaking to the global scope. When you've already defined a variable in a parent scope, omitting var inside the local scope will not leak to the global scope. Instead, the closest variable (ie the closest scope where the variable is defined) will be used. If there's not such a variable, the global scope will be used to store the variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Position absolute and relative IE7 issue I have two divs. First has position:absolute and another one has position:relative.
<div class="first-div">
abc
</div>
<div class="second-div">
xyz
</div>
The problem is in IE7 when hover the first div, the first div is under the second div. In CSS z-index:100; for first div and z-index:0; for the second div but it does not work. Any help to solve this issue?
For other browsers it's working well, only in IE7 is this problem.
A: Apparently there is a z-index bug in IE 7. Setting the parent z-index to a higher value can fix the problem.
<div class="parent" style="position: relative; z-index:200;">
<div class="first" style="position: absolute; z-index:100;"></div>
</div>
<div class="second"></div>
Something like that I suppose - without seeing some of your code it's hard to tell.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Interface, Abstract, or just virtual methods? I have a bunch of systems, lets call them A, B, C, D, E, F, G, H, I, J.
They all have similar methods and properties. Some contain the exact same method and properties, some may vary slightly and some may vary a lot. Right now, I have a lot of duplicated code for each system. For example, I have a method called GetPropertyInformation() that is defined for each system. I am trying to figure out which method would be the best approach to reduce duplicate code or maybe one of the methods below is not the way to go:
Interface
public Interface ISystem
{
public void GetPropertyInformation();
//Other methods to implement
}
public class A : ISystem
{
public void GetPropertyInformation()
{
//Code here
}
}
Abstract
public abstract class System
{
public virtual void GetPropertyInformation()
{
//Standard Code here
}
}
public class B : System
{
public override void GetPropertyInformation()
{
//B specific code here
}
}
Virtual Methods in a Super Base class
public class System
{
public virtual void GetPropertyInformation()
{
//System Code
}
}
public class C : System
{
public override void GetPropertyInformation()
{
//C Code
}
}
One question, although it may be stupid, is let's assume I went with the abstract approach and I wanted to override the GetPropertyInformation, but I needed to pass it an extra parameter, is this possible or would I have to create another method in the abstract class? For example, GetPropertyInformation(x)
A: Your abstract and 'super base class' approaches are not too different. You should always make the base class abstract, and you can provide a default implementation (virtual methods) or not (abstract methods). The deciding factor is whether you ever want to have instances of the base class, I think not.
So it's between base class and interface. If there is a strong coupling between your A, B C classes then you can use a base class and probably a common implementation.
If the A, B, C classes do not naturally belong to a single 'family' then use an interface.
And System is not such a good name.
And you cannot change the parameterlist when overriding. Maybe default parameters can help, otherwise you just need 2 overloads for GetPropertyInformation().
A: Generally you choose object inheritance when you want to share implementation and reduce what would otherwise be duplication. Otherwise interfaces win because they are more flexible since there is no need for a common base class.
As for overriding a method and modifying the parameter list that's just not possible. Imagine how you would call that method on a base class or an interface reference?
A: I'd go with something like what I've added below. You still get the benefit of the interface contract and shared implementation.
public Interface ISystem
{
public void GetPropertyInformation();
//Other methods to implement
}
public abstract class System : ISystem
{
public virtual void GetPropertyInformation()
{
//Standard Code here
}
}
public class B : System
{
public string ExtendedSystemProp {get;set;}
public override void GetPropertyInformation()
{
base.GetPropertyInformation();
var prop = "some extra calculating";
GetExtraPropertyInformation(prop);
}
public void GetExtraPropertyInformation(string prop)
{
ExtendedSystemProp = prop;
}
}
ISystem genericSystem = new B();
genericSystem.GetPropertyInformation();
(genericSystem as B).ExtendedSystemProp = "value";
A: You cannot pass the extra parameter in the override. When you are overriding, you are overriding the method with the exact signature. I would suggest you pass in an interface parameter like IPropertyInformation that can change per implementation.
The decision to go with a base class or an interface for your implementation really depends upon your use. Do A-I have enough in common with each other that they should really all derive from the same base class? If so, then use a base class. Is it really that just GetPropertyInformation is shared and otherwise the systems are totally functionally different? Then you really just want them to share an interface.
A: Others have covered what was originally in my answer, but about the "adding a parameter" point: Don't forget that the latest C# also lets you have optional parameters in methods.
A: Unless you have a compelling reason otherwise, I'd go with the interface. Public virtual methods, though done a lot, is not ideal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: VBA Open Workbook from Macro fails "(path & filename) could not be found. Check the spelling..." I have the following code, which should simply open a workbook from a master workbook to allow me to paste some information which I will later retrieve from a database. I receive the error in the title every time I try to open a workbook. I have used similar code before with no problem at all. The files are kept on a server away from my desktop, but the path has been correct each time. I've checked over and over again. What could be the culprit?
Sub copyDealerDataToWorkbook(ByVal targetID As Integer)
Dim mainWB As Workbook
Dim directory As String
Dim fn As String
Dim aFile As Excel.Application
Set aFile = CreateObject("Excel.Application")
Set mainWB = ActiveWorkbook
directory = ActiveWorkbook.Path
'append a "\"
If InStrRev(directory, "\") < Len(directory) Then
directory = directory & "\"
End If
fn = targetID & ".xls"
aFile.Application.Visible = True
aFile.Workbooks.Open directory & fn 'ERROR ON THIS LINE
aFile.Parent.Windows(1).Visible = True
End Sub
I have also tried the following code...
Sub copyDealerDataToWorkbook(ByVal targetID As Integer)
Dim foreignWB As Workbook
Dim mainWB As Workbook
Dim directory As String
Dim fn As String
Set mainWB = ActiveWorkbook
directory = ActiveWorkbook.Path
'append a "\"
If InStrRev(directory, "\") < Len(directory) Then
directory = directory & "\"
End If
fn = targetID & ".xls"
Set foreignWB = Workbooks.Open(fileName:=directory & fn) 'ERROR ON THIS LINE
End Sub
A: First use hard code with name of file and test if is open.
For sample
Workbooks.open "\\Oesdfiles\Users\FName LName\Reports\test_data\monthly EDS reports\Number by dealer Per importer\test_2011\2011-01January\YourFileHere.xls"
If Yes, your directory or fn var is wrong.
If No, try use office diagnostic in office button/ excel options/Resources/Diagnostic
And try again.
If not work's , your excel need's reinstall.
[]'s
A: If Dir(directory & fn) <> "" Then
'do the magic
Else
MsgBox "Directory and file not found:" & vbCrLf & directory & fn, vbCritical, "Invalid Directory"
End If
A: targetID As Integer
This only works if your Excel workbook has a numeric file name without leading zeroes. Also, In this context there's no need to make targetID an Integer since you aren't iterating or performing calculations on the value, I would make it instead:
targetID As String
Edit: I just realized this was posted 2 years ago. :P
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use DependentTransaction with EF 4.1 DbContext How can we use DependentTransaction with EntityFramework 4.1? If you see the article "http://stackoverflow.com/questions/2858750/what-is-the-reason-of-transaction-context-in-use-by-another-session" to bring transaction into another thread we have to open the connection first but EF 4.1 gives error if connection is opened. Any idea how to do that ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flex: Get a Popup to scroll with the rest of application
Possible Duplicate:
Positioning / Scrolling problem with Flex popup
I am trying to get the main control bar on my application to control the location of a popup that has been opened using PopUpManager.createPopUp(this,JakePanel,false);.
Initially the page looks like this:
After I scroll the page it looks like this:
What I would like is for the Popup to scroll with everything else. Is there a way to do this?
Here is my code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
verticalScrollPolicy="on"
horizontalScrollPolicy="on"
layout="absolute">
<fx:Script>
<![CDATA[
import mx.containers.Panel;
import mx.managers.PopUpManager;
public function buttonClick():void {
PopUpManager.createPopUp(this,JakePanel,false);
}
]]>
</fx:Script>
<mx:VBox>
<mx:Image width="2000"
source="@Embed(source='assets/image.jpg')"/>
<mx:Button click="{buttonClick()}" label="Launch"/>
</mx:VBox>
</mx:Application>
And the popup code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
layout="vertical"
width="400" height="300"
title="Popup"
initialize="{init()}"
>
<fx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function init():void {
}
public function close():void {
PopUpManager.removePopUp(this);
}
]]>
</fx:Script>
<s:TextArea text="Enter more text here: " width="100%" height="200"/>
<s:Button label="OK" click="{close()}" width="100%" height="30" />
</mx:Panel>
A: PopUpManager adds the popped up content to a different parent. It's actually outside of the main stage.
To have the position update with scrolling you would need to add event listeners to the component that is doing the scrolling and manually update the panel's position. In your case add the handler to the .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Boost - Formatting sub second precision time with a time stamp I need to get a nicely formatted timestamp (slightly modified ISO 8601) with millisecond precision.
And example date would look like this: 2011-09-28 13:11:15.237-08:00
The formatting should be able to be overwridden as well.
I've been playing around with boost::posix_time::microsec_clock::local_time() and boost::posix_time::time_facet which works just fine except when it comes to timestamps.
Since posix time doesn't contain time zone information this is just not possible (I'm guessing)
So, is there anything else I could use that has millisecond precision that contains timezone information or can I make the time_facet work with timezones?
Maybe I should always use UTC?
Thanks
A: Have a look at the boost::local_time::local_date_time class. You can specify a time zone and use the local microsecond clock to initialize it like
boost::local_time::local_date_time my_ldt(boost::local_time::local_microsec_clock::local_time(new boost::local_time::posix_time_zone("EST-5EDT,M4.1.0,M10.5.0")));
You should then be able to use the facets to format to a string.
Edit: Full example:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <boost/date_time/local_time/local_time.hpp>
int main(void)
{
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
boost::posix_time::ptime utc = boost::posix_time::second_clock::universal_time();
boost::posix_time::time_duration tz_offset = (now - utc);
std::stringstream ss;
boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
ss.imbue(std::locale(std::locale::classic(), output_facet));
output_facet->format("%H:%M:%S");
ss.str("");
ss << tz_offset;
boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone(ss.str().c_str()));
boost::local_time::local_date_time ldt = boost::local_time::local_microsec_clock::local_time(zone);
boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
ss.imbue(std::locale(std::locale::classic(), output_facet));
output_facet->format("%Y-%m-%d %H:%M:%S%f%Q");
ss.str("");
ss << ldt;
std::cout << ss.str() << std::endl; // "2004-02-29 12:34:56.000789-05:00"
std::cout << "Press return to exit" << std::endl;
std::string wait_for_line;
std::getline(std::cin, wait_for_line);
return (0);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: progressdialog shows up to late (async task) I update dynamically my UI thanks to an asynctask.
On the onpreexecute method I show the progressdialog, but it shows up to late.
I mean, I click on a button to change of activity, then the UI is frozen, and ater I see briefly the progressdialog and finally my UI updated.
What is wrong in my code please ?
private ProgressDialog pd ;
@Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
new taskDoSomething().execute();
}
private class taskDoSomething extends AsyncTask<Long, Integer, Integer>
{
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(SQLView.this, "Working..", "Calculating", true,true);
}
protected Integer doInBackground(Long... params) {
UpdateIHM();
return 0;
}
protected void onPostExecute(Integer result) {
Toast.makeText(SQLView.this,"onPostExecute", Toast.LENGTH_LONG).show();
}
}
public void UpdateIHM()
{
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout my_layout = (LinearLayout) findViewById(R.id.lil_content);
HotorNot info = new HotorNot(SQLView.this);
my_table data = new my_table();
Log.i("Test","ok 0");
info.open();
Log.i("Test","ok 0.1");
for(int i =0; i<3; i++){
data = info.getData();
for (int j=0; j<50; j++){
LinearLayout lil_temp = new LinearLayout(SQLView.this);
lil_temp.setOrientation(LinearLayout.HORIZONTAL);
lil_temp.addView(buildText(data.row), getParams(WRAP, WRAP));
lil_temp.addView(buildText(data.name), getParams(WRAP, WRAP));
lil_temp.addView(buildText(data.hotness), getParams(WRAP, WRAP));
my_layout.addView(lil_temp);
}
}
info.close();
handler.sendEmptyMessage(102);
}
});
}
A: Try showing your ProgressDialog just before executing the AsyncTask. That'll usually help.
A: I am doing the same thing except that I call ProgressDialog.dismiss() at the beginning of onPostExecute().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to join multiple tables related by other tables I'm developing a site where people can publicate their houses for rent. I'm using php 5.2.0 and MySQL 5+
the publications are stored in a table like this
ta_publications
+---+-------------+------+
|id | name | date |
+---+-------------+------+
| 1 | name_001 | ... |
| 2 | name_002 | ... |
| 3 | name_003 | ... |
+---+-------------+------+
I have diferent publications, which have "features" such as "internet", "made service", "satellite tv", etc.
These features might change in the future, and I want to be able to add/remove/modify them, so I store them in the database in a table.
ta_features
+---+-------------+
|id | name |
+---+-------------+
| 1 | Internet |
| 2 | Wi-Fi |
| 3 | satelital tv|
+---+-------------+
which are related to the publications using the following table
ta_publication_features
+---+-------------+----------------+
|id | type_id | publication_id |
+---+-------------+----------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 1 |
+---+-------------+----------------+
I think it's pretty easy to understand; There is a publication called name_001 which have internet, wi-fi and satellite tv.
I have the same data-schema for the images, I store them in this table
ta_images
+---+-------------+
|id | src |
+---+-------------+
| 1 | URL_1 |
| 2 | URL_2 |
| 3 | URL_3 |
+---+-------------+
And use the following table to relate them to the publications
ta_publication_images
+---+-------------+----------------+----------+
|id | img_id | publication_id | order |
+---+-------------+----------------+----------+
| 1 | 1 | 1 | 0 |
| 2 | 2 | 1 | 1 |
| 3 | 3 | 1 | 2 |
+---+-------------+----------------+----------+
the column order gives the order in wich publications should be displayed when listing a single publication.
Philipp Reichart provided me with a query that will search and get all the publications that have certain features. It works for listing the publications, I can't modified it to return me the data I need.
So I figured I'll run that query and get all of the publications that pass the search criteria and then use another query to list them.
The listing of these publications shall include all publication data (everything on ta_publications)+ all of it's features + the most important (order 0) image src.
I could, for every publication, have two simple querys wich will return, separately, the most important image and all the features it has, but when listing 25 publications per page, it'll be 1 search query + (2 querys per publication * 25 publications) = 51 different querys, clearly not very efficient.
EDIT:
My question is, how can I create a SQL query that, given some publication ids, will return: all publication data (everything on ta_publications) + all of it's features + the most important (order 0) image src
A: Select pub.Name as [Publication], f.name as [Feature], i.name as [Image] from ta_publications pub
Join ta_publications_features pf on pf.publication_id = pub.id
Join ta_features f on f.id = pf.type_id
Join ta_publication_images pi on pi.publication_id = pub.id
Join ta_images i on i.id = pi.img_id
Where pub.id = 'appropriate id'
order by i.[order]
If I've followed your structure correctly this should give you the joins you need. and you can add desired columns to the result in the select statment by adding .. hope this helps.
A: You'll get redundant publication and image data with this one, but here is a way to do it with one query:
SELECT p.id, p.name, p.date,
f.id, f.name,
i.id, i.src
FROM ta_publications p
JOIN ta_publication_features pf ON p.id = pf.publication_id
JOIN ta_features f ON f.id = pf.type_id
JOIN ta_publication_images pi ON p.id = pi.publication_id
AND pi.order = 0
JOIN ta_images i ON i.id = pi.img_id
WHERE p.id IN ( -- list of publication ids );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Populating a flex 4.5 DataGrid using PHP and MySQL Hey so I recently started working with Flash Builder 4.5 so I am facing a lot of silly problems while building a mobile application, specially when connecting my application to a back end server.
The thing I am working on currently should update a DataGrid and this data is retrieved from a MySQL Database.
This code displays the data clearly on the browser, however the datagrid is not updated. Instead it throws the following error.
TypeError: Error #1034: Type Coercion failed: cannot convert mx.utils::ObjectProxy@1e43bc1 to mx.collections.IList.
at views::connectPHPHomeView/userRequest_resultHandler()[C:\Documents and Settings\s4710935\Adobe Flash Builder 4.5\connectPHP\src\views\connectPHPHomeView.mxml:17]
at views::connectPHPHomeView/__userRequest_result()[C:\Documents and Settings\s4710935\Adobe Flash Builder 4.5\connectPHP\src\views\connectPHPHomeView.mxml:29]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at HTTPOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\http\HTTPService.as:993]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:318]
at mx.rpc::Responder/result()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\Responder.as:56]
at mx.rpc::AsyncRequest/acknowledge()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:84]
at DirectHTTPMessageResponder/completeHandler()[E:\dev\4.5.1\frameworks\projects\rpc\src\mx\messaging\channels\DirectHTTPChannel.as:451]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
Can someone please guide me through this?
EDIT
Here is the PHP code:
<?php
// -----------------------------------------------------------------------------
// Initialization of the sql server
// -----------------------------------------------------------------------------
// hostname or ip of server (for local testing, localhost should work)
$dbServer='localhost';
// username and password to log onto db server
$dbUser='root';
$dbPass='password';
// name of database
$dbName='test';
mysql_connect("$dbServer", "$dbUser", "$dbPass") or die(mysql_error());
mysql_select_db("$dbName") or die(mysql_error());
//Creating the table and inserting the values in it...
mysql_query("CREATE TABLE IF NOT EXISTS mariah_transaction_log(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
date DATE,
details VARCHAR(150),
debit DOUBLE,
credit DOUBLE,
balance DOUBLE)")
or die(mysql_error());
mysql_query("INSERT INTO mariah_transaction_log
(date, details, debit, credit, balance) VALUES('2011-08-08','Zellers','12.56','0.00','12343.54') ")
or die(mysql_error());
$username = $_GET["username"];
// $namedGreeting = mysql_query("SELECT * FROM customer_list WHERE username='$username'") or die(mysql_error());
// $row = mysql_fetch_array( $namedGreeting );
// echo "Hello ".$row['name']."!";
$Query = "SELECT * from mariah_transaction_log";
$Result = mysql_query( $Query );
$Return = "<users>";
while ( $User = mysql_fetch_object( $Result ) )
{
$Return .= "<user><date>".$User->date."</date><details>".
$User->details."</details><debit>".
$User->debit."</debit><credit>".
$User->credit."</credit><balance>".
$User->balance."</balance></user>";
}
$Return .= "</users>";
mysql_free_result( $Result );
print ($Return)
?>
And here is the MXML and AS3 part to my code: NOTE The sample XML result was added just for simplicity
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView">
<fx:Script>
<![CDATA[
import mx.collections.IList;
import mx.collections.XMLListCollection;
import mx.rpc.events.ResultEvent;
protected function callService(event:ResultEvent):void
{
var results:XML = sampleResult;
var resultsList:XMLListCollection = results.users as XMLListCollection;
showTransactions_dg.dataProvider = resultsList;
}
]]>
</fx:Script>
<fx:Declarations>
<fx:XML id="sampleResult" xmlns="">
<users>
<user>
<date>2011-08-07</date>
<details>Camello Shop</details>
<debit>67.32</debit>
<credit>0.00</credit>
<balance>1233.42</balance>
</user>
<user>
<date>2011-08-07</date>
<details>Deposit</details>
<debit>0.00</debit>
<credit>600.00</credit>
<balance>1833.42</balance>
</user>
</users>
</fx:XML>
<s:HTTPService id="userRequest" url="{phpFile}"
method="GET" resultFormat="e4x"
result="callService(event)" useProxy="false">
<s:request xmlns="">
<username>{username_txt.text}</username>
</s:request>
</s:HTTPService>
<!-- The link to the php file -->
<fx:String id="phpFile">http://localhost:8080/connectPHP/phpFile.php </fx:String>
</fx:Declarations>
<s:TextInput id="username_txt" x="11" y="78"/>
<s:Label x="11" y="55" text="Username"/>
<s:Button id="getData_button" x="10" y="122" label="Done?"
click="userRequest.send()"/>
<s:Label id="showName_lbl" x="13" y="173" text="show name here"/>
<s:DataGrid id="showTransactions_dg" x="10" y="218" width="300" height="86">
<s:columns>
<s:ArrayCollection>
<s:GridColumn dataField="date" headerText="Date" />
<s:GridColumn dataField="details" headerText="Details"/>
<s:GridColumn dataField="debit" headerText="Debit"/>
<s:GridColumn dataField="credit" headerText="Credit"/>
<s:GridColumn dataField="balance" headerText="Balance"/>
</s:ArrayCollection>
</s:columns>
</s:DataGrid>
<s:Label id="testLbl" x="13" y="334" width="266" height="90" text="Label"/>
</s:View>
A: In a spark DataGrid the dataProvider must implement an iList interface. It looks like you are returning XML and storing it in a generic object. A generic object does not support the IList interface.
Instead of binding the results of the remote call to the dataGrid's dataProvider, you should add a result handler to the HTTPService:
<s:HTTPService id="userRequest" url="{phpFile}"
method="GET" resultFormat="object" useProxy="false" result="onResult(event)">
Then cast your data in the result Handler to something that implements IList. I recommend an XMLListCollection in this case.
protected function onResult(event:ResultEvent):void{
var resultsXML : XML = event.results as XML
showTransactions_dg.dataProvider = new XMLListCollection(resultsXML);
}
This code was written in the browser and may not be perfect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Blender game engine events with python We're searching for a way to script events in BGE instead of using there build in GUI version where you are using your mouse to make events trigger your scripts. Isn't there a way to use events with python directly? Thanks in advance.
A: The only way to bypass the BGE event system is to read events with Python (which by it's nature inefficient).
You can read keyboard and mouse events or verify the scene with own algorithms.
I suggest to trigger code that depends on keyboard events with a keyboard sensor (allKeys mode) to get a better performance rather then an always sensor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to test HtmlHelpers that call Partial? I've been looking at this Stackoverflow question and have the answer implemented. It works all fine and dandy until I get to call HtmlHelper.Partial in my helper method, which is listed below. I know it might not be the best code, but this is until I can refactor more of the app. The error it throws is
Previous method 'ViewContext.get_TempData();' requires a return value or an exception to throw.
Am I missing mocking something, or is there a better way to render a usercontrol?
Edit Ok I did miss something, I didn't call mocks.Replay(). Now have another error which it wants something named controller in routeData...progress.
Edit #2 Clarifying I'm trying to mock the call to HtmlHelper.Partial(partialPath, model), I just want that to return whatever partialPath I send in I suppose, or at least not blowup. I did find this page http://andrevianna.com/blog/?p=8 which was very helpful and I almost got things working. This was helpful as well http://farm-fresh-code.blogspot.com/2009/10/mocking-htmlhelper-class-with.html
public static string RenderRateDetails(this HtmlHelper html, string partialPath, RatesViewData model, RateDetailType type)
{
switch (type)
{
case RateDetailType.AR:
if (model.ExistingRateDetailAR != null)
return html.Partial(partialPath, model).ToString();
break;
case RateDetailType.AP:
if (model.ExistingRateDetail != null)
return html.Partial(partialPath, model).ToString();
break;
}
return string.Empty;
}
A: I think the example given at 'farm fresh code' is the right way to go, you can't directly mock the HtmlHelper, but you can build an instance where all of it's dependencies are mocked.
When you're code calls html.Partial(partialPath, model).ToString(), the HtmlHelper calls properties and methods on the dependencies that you mocked, and you get errors if these don't return reasonable default values.
In this case it looks like the TemplateData property of the mocked ViewContext object was called, and I imagine it returned null, hence:
Previous method 'ViewContext.get_TempData();' requires a return value or an exception to throw.
Once you mock this property, you should be able to get past this error, but you might need to mock a few more things before you get it all working.
It might save you some time to take a look at the MVC source code to see what gets called in the Partial method. You can get that here http://aspnet.codeplex.com/releases/view/58781.
EDIT
BTW. The TempData property returns a System.Web.Mvc.TempDataDictionary. Mocking the property to return an empty instance of one of those should solve the immediate problem.
A: Have you considered using Display and Editor templates for your user controls rather than extending HtmlHelper?
I used to do the same thing quite a lot in the early MVC versions, but I have switched almost completely to using templates now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby GEM for File and Directory manipulation i'm looking for gem(s) which will provide me tools for File and Directory manipulation.
Basicly i would like to get possibility to:
*
*search file in provided directory
*search pattern inside file (different extensions)
*insert into file at precise place content
I know how to do it using Ruby, but it would be nice to get such gem :)
Thanks
A: Anwser is NO, there isn't one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: onBind and Service connect? There seems to be a small delay after I bind to a remote service. The onServiceConnection works fine. The binding work fine. There is just a delay problem I think. For example in the onCreate() method of my activity if for instance say:
*
*Note the mConnection onServiceConnect() sets mRemoteServiceStub correctly.
bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
mRemoteServiceStub.doThis();
If I run this I get an error that says that no connection yet exists. However if I put the mRemoteServiceStub.doThis() in a method to a onClickListener it work perfect. So either the connection is not made until the activities onCreate has finished running or there is a delay on the connection being made.
Does anybody know ?
And is there way to delay the application from running until the connection is made this way I can use the connection right away with no trigger. (My implementation is correct)
A:
If I run this I get an error that says that no connection yet exists.
bindService() is not synchronous. You cannot use your stub until onServiceConnected() is called on your ServiceConnection object and you create the client-side proxy from the IBinder.
And is there way to delay the application from running until the connection is made this way I can use the connection right away with no trigger.
Put your binder-dependent logic in onServiceConnected().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tracking multiple QR tags from a distance using webcam and Java I'm currently trying to build an application in Java, which should be able to read QR tags from a couple of meters.
At the moment, I have JavaCV running, for capturing frames from my iSight on my MBP.
The problem is that it only supports a resolution of 640x480, which does not seem enough for ZXing to recognizing the QR tags.
I have been looking at a Logitech QuickCam Pro 9000, but I'm not entirely convinced, from my search, that it supports a high enough resolution for my project.
The application need to be platform agnostic, at least regarding OS X, Windows and Linux, which is the reason I'm doing it in Java.
My questions are:
Will the QucikCam pro record frames in 1080p as promised using the UVC drivers?
Is there a better camera?
Should I look at another framework than JavaCV and/or ZXing?
-Which?
thanks for the help
A: Resolution is not the issue; it decodes 320x240 regions on phones, as Barcode Scanner, easily. QR codes are especially simple to read. However if your QR code is in a tiny region of that 640x480 capture, like 50x30, yeah that's not going to be enough to decode reliably. I don't think any software could help you there.
I'd look at zooming in if you can.
Otherwise, I think you have some other issue; maybe the image data is in the wrong format somewhere
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calculations and display in label I'm having a small bit of trouble trying to get this piece of code working. I received some answers related to this code bit but it was solving a different issue.
Basically two things for testing purposes that I would like to see working correctly here. One when I try to display dist I would like it to actually get the number that is inputted in the Text Field. Currently when I input something it comes up as zero. (I set it up for doubles cause often a double may be used). The other thing is when I place the timePassed into the display instead of dist it comes up with a serious of numbers that should be the amount of time passed between these two buttons. I'm not sure why but it often displays a negative number and the numbers are a little on the high side to begin with. Any ideas or help is always appreciated. (I'm trying to get these to display on the screen correctly because once I know they are working correctly then I can put them into a calculation and have the calculation display).
-(IBAction)triggerDown:(id)sender{
[timeStart release];
timeStart = [[NSDate alloc] init];
}
-(IBAction)triggerUp:(id)sender{
double calc, dist;
int mph;
NSString *display;
NSTimeInterval timePassed = [timeStart timeIntervalSinceNow]*1000;
if ([distance.text length]== 0) {
display = @"Please enter a distance";
}
else{
dist = [distance.text doubleValue];
display = [[NSString alloc] initWithFormat:@"%d MPH",dist];
}
speed.text = display;
[display release];
}
Just so you understand what is happening. When triggerDown is pressed it is a button that passes the starting time. Then when that same button is released the triggerUp button is called and it is supposed to get the time that passed between the two as well as do calculations. (Calculations haven't been written in yet).
A: Regarding the negative (and too large by modulus) time: your timeStart is in the past, so when you do [timeStart timeIntervalSinceNow] you get a negative interval. Since timeStart will always be in the past, you can just multiply the interval by -1 to get the positive number.
Furthermore, when you multiply the interval a thousand, you turn a second into a thousand seconds - you need to divide instead to get seconds from milliseconds.
As for displaying the 0 in display - try setting the text field's value to the label directly: speed.text = distance.text. Will it work? If not, make sure the text field is connected to the outlet ("distance").
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Processing cURL and other POST types of requests I'm afraid that you're all gonna need to reach over and put on your "this-is-a-dumb-question" hat, but I can't find a legitimate answer online.
I can find all sorts of crazy info on sending cURL requests to a site and have them send back a response and processing that response.
My question is I want to BE the site that receives this cURL requests. How do you set up a page to process those types of requests? How does it work?
I ask because in the near future I will need to integrate this into a project I'm working on. Other sites will send me info that I'll need to process and store in a database. Ideally, I'll probably need something to handle HTTP POST requests and obviously I'll need to know what security measures I'll need to take as well. It also would be nice to know how to fire back a response to the person who's making the request. I also will need to know how to configure user authentication....such as with:
curl_setopt($request, CURLOPT_USERPWD, "Username:Password");
I feel silly asking, but I can't figure out the right search keywords to use to look up this kind of info. Even just a link to a relevant site would be appreciated.
Thanks in advance. You all rock.
A: All that cURL does is act as a user agent. Any user agent can access a php page.
So to be the site that receives cURL requests (or to have such a page) all you really need to do is create a normal php page that would work as if a user were using it. Whoever is using cURL to make the request will have to know what data you are expecting on your end.
If you want to use CURLOPT_USERPWD for authentication, you have to set up apache (or whatever server you are using) to password protect that page. This can't be done in the php script directly. However, the php script can have it's own form of authentication either instead of or in addition to this authentication. There are millions of ways to do this (openssl for example, or just anticipating a static string depending on how secure you want to be).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Basic than the Basic-est question on Spring Security? I have an extremely basic question about Spring security, however this question may be generalized to any Authorization scheme:
Should a Group have a single authority and a user may be a member of multiple groups?
OR
A group may have multiple authorities and a user may be assigned to just one group?
I need a user to have the following three authorities: ROLE_ADMIN, ROLE_MANAGER, ROLE_EMPLOYEE.
Following Table structures illustrate the question in a bit more detail:
Route 1.
GROUP TABLE
===========
ID, NAME
1, 'Admins'
2, 'Managers'
3, 'Employees'
GROUP_AUTHORITY TABLE
=====================
GROUP_ID, AUTHORITY
1, 'ROLE_ADMIN'
1, 'ROLE_MANAGER'
1, 'ROLE_EMPLOYEE'
2, 'ROLE_MANAGER'
2, 'ROLE_EMPLOYEE'
3, 'ROLE_EMPLOYEE'
GROUP_MEMBER TABLE
==================
GROUP_ID, USERS_ID
1, 1
USERS TABLE
===========
USERS_ID, NAME
1, 'John Admin'
//-------------------------------------------
Route 2:
GROUP TABLE
===========
ID, NAME
1, 'Admins'
2, 'Managers'
3, 'Employees'
GROUP_AUTHORITY TABLE
=====================
GROUP_ID, AUTHORITY
1, 'ROLE_ADMIN'
2, 'ROLE_MANAGER'
3, 'ROLE_EMPLOYEE'
GROUP_MEMBER TABLE
==================
GROUP_ID, USERS_ID
1, 1
2, 1
3, 1
USERS TABLE
===========
USERS_ID, NAME
1, 'John Admin'
I'll appreciate an input.
A: I vote for: have Groups with several autorities. But with REAL Authorities like: ROLE_MANAGE_USER, ROLE_MANAGE_STOCK, ROLE_CREATE_REPORTS,...
Let my explain why the Role based authority (no matter if Route1 or Route2) does not work in the long term.
If the real user groups are not fixed for ever (and that is it for every real application) then you will have the problem, that in some point in time you will need to support a new group, for example trainee. If you now have used real role names for your authorities like "ROLE_EMPLOYEE"... then you need to go through the code and modify every security statement that guard a function that should be available for trainees too.
But if you use real authorities for the authorises, and build an assignment between real groups and authorities then you will only need to define the new group and the assignment to the authories.
For example:
*
*Group_Admin: ROLE_MANAGE_USER, ROLE_MANAGE_STOCK, ROLE_CREATE_REPORTS
*Group_Employee: ROLE_MANAGE_STOCK, ROLE_CREATE_REPORTS
*Group_Trainee: ROLE_CREATE_REPORTS, MAKE_COFFEE
In your code you should have than only use real authorities like @Secured("ROLE_MANAGE_USER") but never anything that reveres to real roles.
BTW: If your application becomes bigger it is often not enough to assign only a single role to an User, then you need to assign more then one role to an user: user --m:n--> Role --m:n--> Authority.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: HTML content display limited lines How to display news items which comes from database on a web page limiting the number of lines to 3.
The news content is in html format for example
<p><span style="font-family: HelveticaNeue LT 77 BdCn;"><span style="font-size: large;">The average house price&nbsp;up by 0.3% in May</span></span></p>
<p><span style="font-family: HelveticaNeue LT 55 Roman;"><span style="font-size: small;">compared to the previous month <br />but fell 1.2% compared to May 2010</span></span></p>
<p><span style="font-family: HelveticaNeue LT 55 Roman;"><span style="font-size: small;"></span></span><span style="font-family: HelveticaNeue LT 55 Roman;"><span style="font-size: small;"><a href="http://www.nationwide.co.uk/hpi/historical/May_2011.pdf" title="Nationwide House Price Index">Nationwide House Price Index</a></span></span></p>
How can i display first three lines only from the above html news by using java script/css and append ... at the end.
I tried by setting height and overflow on div element that wraps the above news content but that will crop the bottom line of text depending upon the font or browser.
A: I think that the most reliable way to do this would be to set the line-height property (to whatever looks best to you), then setting the height property to 3 times the value you used for the line-height property. Then, just use the overflow property accordingly, like you've said.
For example:
.newsItems {
line-height: 1.2em;
height: 3.6em;
overflow: hidden;
}
A: If you know the height of the font, you can set the height of the div appropriately. The simple answer is to set the height to 3em, though you'll probably still need some tweaking.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Process Builder Incrementing Error I have written a program to monitor the status of some hard drives attached to a RAID on Linux. Through this program I execute several command line commands. An interesting error occurs though....the program runs for a good three minutes before it seems that it can no longer correctly execute the command it had been previously executing (for many iterations).
It spits out an array index error (my variable driveLetters[d]) because it appears to miss the drive somehow (even though it found it hundreds of times before).
Other things to note...if I tell it to reset int "d" to "0" if it exceeds the number of drives...the program won't crash and instead will just become stuck in an infinite loop.
Also, the time at which the program crashes varies. It doesn't appear to crash after a set number of intervals. Finally, I don't get any kind of memory leak errors.
Here is some of code that should reveal the error:
public static void scsi_generic() throws IOException, InterruptedException
{
int i =0;
int d =0;
int numberOfDrives = 8;
char driveLetters[] = {'b','c','d','e','f','g','h','i','j','k','l','m'};
String drive = "";
while (i <= numberOfDrives)
{
System.out.println("position 1");
List<String> commands = new ArrayList<String>();
commands.add("cat");
commands.add("/sys/class/scsi_generic/sg"+i+"/device/sas_address");
SystemCommandExecutor commandExecutor = new SystemCommandExecutor(commands);
int driveFound = commandExecutor.executeCommand();
if (driveFound == 0)
{
System.out.println("Folder: sg" + i + " was found." );
StringBuilder stdout = commandExecutor.getStandardOutputFromCommand();
String data = stdout.toString();
String sas = data.substring(11,12);
int sasA = Integer.parseInt(sas,16);
boolean matchedSG = false;
while (matchedSG == false)
{
System.out.println("position2");
List<String> lookSD = new ArrayList<String>();
lookSD.add("test");
lookSD.add("-d");
lookSD.add("/sys/class/scsi_generic/sg"+i+"/device/block:sd" + driveLetters[d]);
SystemCommandExecutor commandSearch = new SystemCommandExecutor(lookSD);
int sdFound = commandSearch.executeCommand();
StringBuilder stdout3 = commandSearch.getStandardOutputFromCommand();
StringBuilder stderr = commandSearch.getStandardErrorFromCommand();
String sdFound2 = stdout3.toString();
if (sdFound == 0)
{
matchedSG = true;
System.out.println("Found the SD drive.");
drive = "sd"+driveLetters[d];
System.out.println(sasA);
hdsas.set(sasA , sas);
d = 0;
i++;
loadDrives(drive , sasA);
}
/* else if (sdFound != )
{
System.out.println("Error:" + sdFound);
System.out.println(d+ " "+ i);
}
*/
else if ( d >= 8)
{
System.out.println("Drive letter: " + driveLetters[d]);
System.out.println("Int: " + i);
// System.out.println(sdFound2);
System.out.println("sd error: "+ sdFound);
// System.out.println(stderr);
//System.out.println(sdFound2 + " m");
}
else
{
d++;
}
}
}
else
{
System.out.println("Folder: sg" + i + " could not be found.");
i++;
}
d =0;
}
}
Any help or suggestions would be awesome! Thanks.
EDIT:
The solution I found was to use the java library for testing if a directory exists rather than doing it through the linux command line.
Ex:
File location = new File("directory");
if (location.exists())
{
}
No idea why it works and doesn't crash, where as the linux command line did after a short period of time, but it does.
A: This is no direct answer to your question, but it still might help you:
I often have to find bugs in code like yours (very long methods with "global" variables, that is, variables declared at the beginning of a method and used all over then). Just by refactoring the code properly (short methods with a single purpose each), the cause of the bug becomes immediately visible to me and is fixed within a second (while the refactoring itself takes much longer).
I guess that's what everyone trying to offer you help is doing anyway: Refactor your code (probably only in one's head) so that is (much) more easy to understand what's going on.
A: The solution I found was to use the java library for testing if a directory exists rather than doing it through the linux command line.
Ex:
File location = new File("directory");
if (location.exists())
{
}
No idea why it works and doesn't crash, where as the linux command line did after a short period of time, but it does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python introspection: Automatic wrapping of methods object of type A and Is there a way to programatically wrap a class object?
Given
class A(object):
def __init__(self):
## ..
def f0(self, a):
## ...
def f1(self, a, b):
## ..
I want another class that wraps an A, such as
class B(object):
def __init__(self):
self.a = A()
def f0(self,a):
try:
a.f0(a)
except (Exception),ex:
## ...
def f1(self, a, b):
try:
a.f1(a,b)
except (Exception),ex:
## ...
Is there a way to do create B.f0 & B.f1 by reflection/inspection of class A?
A: If you want to create class B by calling a function on a predefined class A, you can simply do B = wrap_class(A) with a function wrap_class that looks like this:
import copy
def wrap_class(cls):
'Wraps a class so that exceptions in its methods are caught.'
# The copy is necessary so that mutable class attributes are not
# shared between the old class cls and the new class:
new_cls = copy.deepcopy(cls)
# vars() is used instead of dir() so that the attributes of base classes
# are not modified, but one might want to use dir() instead:
for (attr_name, value) in vars(cls).items():
if isinstance(value, types.FunctionType):
setattr(new_cls, attr_name, func_wrapper(value))
return new_cls
B = wrap_class(A)
As Jürgen pointed out, this creates a copy of the class; this is only needed, however, if you really want to keep your original class A around (like suggested in the original question). If you don't care about A, you can simply decorate it with a wrapper that does not perform any copy, like so:
def wrap_class(cls):
'Wraps a class so that exceptions in its methods are caught.'
# vars() is used instead of dir() so that the attributes of base classes
# are not modified, but one might want to use dir() instead:
for (attr_name, value) in vars(cls).items():
if isinstance(value, types.FunctionType):
setattr(cls, attr_name, func_wrapper(value))
return cls
@wrap_class
class A(object):
… # Original A class, with methods that are not wrapped with exception catching
The decorated class A catches exceptions.
The metaclass version is heavier, but its principle is similar:
import types
def func_wrapper(f):
'Returns a version of function f that prints an error message if an exception is raised.'
def wrapped_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception, ex:
print "Function", f, "raised", ex
return wrapped_f
class ExceptionCatcher(type):
'Metaclass that wraps methods with func_wrapper().'
def __new__(meta, cname, bases, cdict):
# cdict contains the attributes of class cname:
for (attr_name, value) in cdict.items():
if isinstance(value, types.FunctionType): # Various attribute types can be wrapped differently
cdict[attr_name] = func_wrapper(value)
return super(meta, ExceptionCatcher).__new__(meta, cname, bases, cdict)
class B(object):
__metaclass__ = ExceptionCatcher # ExceptionCatcher will be used for creating class A
class_attr = 42 # Will not be wrapped
def __init__(self):
pass
def f0(self, a):
return a*10
def f1(self, a, b):
1/0 # Raises a division by zero exception!
# Test:
b = B()
print b.f0(3.14)
print b.class_attr
print b.f1(2, 3)
This prints:
31.4
42
Function <function f1 at 0x107812d70> raised integer division or modulo by zero
None
What you want to do is in fact typically done by a metaclass, which is a class whose instances are a class: this is a way of building the B class dynamically based on its parsed Python code (the code for class A, in the question). More information on this can be found in the nice, short description of metaclasses given in Chris's Wiki (in part 1 and parts 2-4).
A: Meta classes are an option, but generally hard to understand. As is too much reflection
if not needed in simple cases, because it is easy to catch too many (internal) functions. If the wrapped functions are a stable known set, and B might gain other functions, you can delegate explicitly function by function and still keep your error handling code in one place:
class B(object):
def __init__(self):
a = A()
self.f0 = errorHandler(a.f0)
self.f1 = errorHandler(a.f1)
You might do the assignments in a loop if they are many, using getattr/setattr.
The errorhandler function will need to return a function which wraps its argument with
error handling code.
def errorHandler(f):
def wrapped(*args, **kw):
try:
return f(*args, **kw)
except:
# log or something
return wrapped
You can also use errorhandler as decorator on new functions not delegating to the A instance.
def B(A):
...
@errorHandler
def f_new(self):
...
This solution keeps B simple and it is quite explicit what's going on.
A: You could try it old-school with __getattr__:
class B(object):
def __init__(self):
self.a = A()
def __getattr__(self, name):
a_method = getattr(a, name, None)
if not callable(a_method):
raise AttributeError("Unknown attribute %r" % name)
def wrapper(*args, **kwargs):
try:
return a_method(*args, **kwargs)
except Exception, ex:
# ...
return wrapper
Or with updating B's dict:
class B(object):
def __init__(self):
a = A()
for attr_name in dir(a):
attr = getattr(a, attr_name)
if callable(attr):
def wrapper(*args, **kwargs):
try:
return attr(*args, **kwargs)
except Exception, ex:
# ...
setattr(self, attr_name, wrapper) # or try self.__dict__[x] = y
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Working with percentages in PHP I'm trying to create a simple split tester in PHP but I'm having some trouble getting the percentages all figured out.
So, I have a settings page where I want to put a percentage, something like 20, so that 20% of the traffic to my page will be redirected.
This will obviously need to work with rand, but I'm not exactly sure how.
A: This if statement returns 20% true:
if (rand(1,5) % 5 == 0)
A: if (rand(1, 100) <= 20){
// show page 1
} else {
// show page 2
}
Some testing and comparison:
Results for round 0
Method1 redirect rate: 0.200302%
Method2 redirect rate: 0.200318%
Results for round 1
Method1 redirect rate: 0.199277%
Method2 redirect rate: 0.199479%
Results for round 2
Method1 redirect rate: 0.200262%
Method2 redirect rate: 0.19995%
Results for round 3
Method1 redirect rate: 0.200254%
Method2 redirect rate: 0.200315%
Results for round 4
Method1 redirect rate: 0.199943%
Method2 redirect rate: 0.19977%
Results for round 5
Method1 redirect rate: 0.20006%
Method2 redirect rate: 0.20024%
Summary:
Method1 deviation: -9.7999999999931E-5
Method2 deviation: -7.1999999999905E-5
and code for that testing:
<?php
function method1(){
return (rand(1,5) % 5 == 0)?true:false;
}
function method2(){
return (rand(1,100) <= 20)?true:false;
}
$iterations = 1000000;
for ($j = 0; $j <= 5; $j++){
$m1 = 0;
$m2 = 0;
for ($i = 0; $i < $iterations; $i++){
if (method1()){
$m1++;
}
if (method2()){
$m2++;
}
}
$dx1 = $m1/$iterations;
$dx2 = $m2/$iterations;
$dev1 += 0.2 - $dx1;
$dev2 += 0.2 - $dx2;
echo "Results for round $j\n";
echo "Method1 redirect rate: " . $dx1 . "%\n";
echo "Method2 redirect rate: " . $dx2 . "%\n";
}
echo "Summary:\n";
echo "Method1 deviation: $dev1\n";
echo "Method2 deviation: $dev2\n";
Also < would take less cpu power than % :) First in timing is the % and then <
$ /usr/bin/time -l php -q test.php
5.25 real 5.19 user 0.01 sys
8224768 maximum resident set size
0 average shared memory size
0 average unshared data size
0 average unshared stack size
2090 page reclaims
0 page faults
0 swaps
17 block input operations
4 block output operations
0 messages sent
0 messages received
0 signals received
17 voluntary context switches
592 involuntary context switches
$ /usr/bin/time -l php -q test.php
4.75 real 4.73 user 0.01 sys
8216576 maximum resident set size
0 average shared memory size
0 average unshared data size
0 average unshared stack size
2088 page reclaims
0 page faults
0 swaps
0 block input operations
0 block output operations
0 messages sent
0 messages received
0 signals received
0 voluntary context switches
100 involuntary context switches
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Heroku Deploy can't find devise-1.4.6 Trying to deploy to Heroku but get the following error:
-----> Gemfile detected, running Bundler version 1.0.7
Unresolved dependencies detected; Installing...
Using --without development:test
Fetching source index for http://rubygems.org/
Could not find devise-1.4.6 in any of the sources
FAILED: http(preventing hyperlink)://devcenter.heroku.com/articles/bundler
! Heroku push rejected, failed to install gems via Bundler
I have "gem 'devise'" in my gem file, have "source 'http://rubygems.org'" at the top, and have run both bundle install and bundle update. Not sure why Heroku is looking for 1.4.6. Any ideas?
Thanks!
John
Here is the gemfile:
source 'http://rubygems.org'
gem 'rails', '3.0.9'
gem 'devise'
gem 'sqlite3', '1.3.3', :group => :development
Looks like devise 1.4.6 is no longer at Rubygems.com: http://rubygems.org/gems/devise/versions
I tried using devise 1.4.5, but it didn't work either.
A: You need to update the locked version of Devise in your Gemfile.lock.
$ bundle update devise
Then commit, push and deploy to Heroku.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is applying styles to element a good practice? Applying styles to <form> tag is:
a) a good practice, it decreases the count of elements on a page and makes code clear
b) a bad practice because of semantics, use other elements instead, div is for style, form is for forms
c) don't ask silly questions and focus on real job!
A: d) none of the above
Style the form if that makes life easier for you. It is not against semantics if you do it.
a - Decreasing the amount of elements is not necessarily a good practice. If creating more elements will make your layout more readable/understandable then go ahead.
b - Divs are not for styling, they are there to divide sections in the document
c - You should worry about semantics. This is not a silly question.
A: a) Yes.
b) No. Div is a generic element. It is not for "style" it is for "when nothing else describes the semantics".
A: A and C. Simple way checking for good answer is: Write a code and validate it with validator.
A: Since semantics are seperate from style, applying style to a form has no semantic consequences. Go right ahead and style a form if you like, it makes no difference to the semantic meaning of the page.
A: In my personal experience, (a) is especially true because:
*
*You will be reducing the overall filesize of your page, with no real disadvantage (especially if you have multiple forms and run into this a lot).
*You will be reducing the amount of confusion when you have to go back to edit this style in the future (where someone may have the same question as you).
*You will be reducing the ambiguity as to where certain styles come from (e.g. this form has too large of a top margin. Is that coming from the margin on the <div> or the margin on the <form>?)
*You will be reducing the possibility of introducing bugs or cross-browser quirks, stemming from browsers not implementing the same default styles on all elements (in this case, the <form> element).
While I suppose one could argue that (b) is a "problem" in theory (and should therefore be avoided), it will never be a "problem" in practice. But as you can see above, wrapping it in a <div> can certainly be a problem in practice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: can't get my recursion function to work with a list Passing in a list such as: [1,2,3,4,5]
and get back [ [1,2,3,4,5] , [2,3,4,5] , [3,4,5] , [4,5] , [5] , [] ]
my approach is using recursion to add drop 1 list to another empty list until list is empty. but I can't seem to get my recursion to work correctly.
help please, thanks
my code so far:
test a = test2 a where
test2 a | size(a) > 1 = test (drop 1 a):[]
| otherwise = []
but that wouldnt work because the recursion is passing back a list in a list, not a list. I just cant figure out how you can assign it to something and return it at the same time.
A: First of all, what did you do the test a = test2 a for?
Then, you don't need (and shouldn't use) guards for this, do it with pattern matching:
test [] = [[]]
test (a:al) = (a:al):(test al)
If you insist on using guards, you still need do make it actually a list of lists:
test a
| null a = [[]]
| otherwise = a:(test $ tail a)
(Not a list of lists of lists, as I had in my original post...)
A: The function you're describing is already in the standard library, where it's called Data.List.tails. You can have a look at its source code to see how it works.
A: If you want to go with your drop 1 approach, you could write
test xs = take (1 + length xs) $ iterate (drop 1) xs
A slightly funny version is
import Data.List
test = (++[[]]) . transpose . zipWith replicate [1..]
A: fromNet [] = [[]]
fromNet lst = lst : fromNet (tail lst)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rows showing up multiple times in GridView I have a GridView control on my web page which makes use of paging. I am seeing apparently duplicate rows appearing, but I know they are not in the data, and they seem to disappear whenever I sort on a different column from the default one I'm using. However, they reappear when sorting on this original column again.
Here's a snippet of the ascx;
<asp:GridView
ID="gvResults"
AllowPaging="True"
CssClass="DataTable"
runat="server"
AutoGenerateColumns="False"
OnRowDataBound="gvResults_RowDataBound"
AllowSorting="True"
Width="750px"
OnSorting="gvResults_Sorting"
PagerSettings-Mode="NumericFirstLast"
PagerSettings-FirstPageText="<<"
PagerSettings-LastPageText=">>"
PagerSettings-PageButtonCount="5"
PagerSettings-Position="Bottom"
PagerStyle-CssClass="paginationContainer"
PagerStyle-HorizontalAlign="Left"
OnPageIndexChanging="gvResults_PageIndexChanging">
<PagerSettings
FirstPageText="<<"
LastPageText=">>"
Mode="NumericFirstLast"
PageButtonCount="5" />
<PagerStyle CssClass="paginationContainer" HorizontalAlign="Left" />
That might be irrelevant to my issue, but I'm including it just in case.
Now, I believe that the issue is possibly being caused because there is a particular scenario in which the column on which the grid is sorted by default, will be populated with an identical value for many rows. That might sound strange, but the column is a proximity, and the grid is displaying proximity search results, so it is possible that some searches are going to return many results with the same proximity.
The issue of the duplicate results only happens once the number of rows with an identical proximity exceeds the number of results displayed per page (in my case, 10).
Whenever this happens, I see a row appear on, e.g. the 2nd page, and also on the 3rd page (never on the same page however). Sorting on a different column and paging through the results seems to eradicate the issue.
Now, after much head / wall interfacing, I have arrived at a speculative explanation;
That this is totally expected behaviour because there is no specified way to sort the rows when the fields are identical. Some other mechanism must be deciding how to sort the rows, and whatever this mechanism is causes the duplicate issue whenever paging through results.
Am I on the right track here? And if so, how can I address this issue? Is there some way to sort on a secondary column in addition to the user specified one?
A: I don't know whether you are on the right track or not because w/o looking at the data it's difficult to tell, but to your question regarding sorting by a secondary column, you definitely can do this easily:
*
*If you are using a DataTable to bind your data, you can order by two columns with something like this on your gvResults_Sorting event:
Expression<Func<DataRow,object>> expCol1 = row => row["SortExpressionFirstColumn"];
Expression<Func<DataRow,object>> expCol2 = row => row["SortExpressionSecondColumn"];
OrderedEnumerableRowCollection<DataRow> result = yourTabale.AsEnumerable().OrderBy(expCol1.Compile()).ThenBy(expCol2.Compile());
DataTable sortedTable = new DataTable();
foreach (var item in result)
{
sortedTable.ImportRow(item);
}
gvResults.DataSource=sortedTable;
gvResults.DataBind();
*Or you don't get so fancy and use a DataView to sort the datatable:
DataTable t ....
t.DefaultView.Sort="SortExpressionColumn1 ASC/DESC , SortExpressionColumn2 ASC/DESC";
gvResults.DataSource=t.DefaultView.ToTable();
gvResults.DataSource=t.DataBind();
*If you are using custom business objects, much easier:
List<CutomObject> co = ....
co=co.OrderBy(x => x.FirstProperty).ThenBy(x => x.SecondProperty);
gvResults.DataSource=co;
gvResults.DataBind();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Save the selected value of a combobox in wxpython I'm working to design a gui using wxpython, a pecie of my code is that i have a class which a fram
declaration and also i declared variables that i wanna chage their values based on the comboboxes
selection. i did the folowing:
class myMenu(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(900, 700))
self.ct = 0
self.phaseSelection = ""
self.opSelection = ""
self.instSelection = ""
self.orgSelection = ""
panel = wx.Panel(self, -1)
panel.SetBackgroundColour('#4f3856')
phasesList = ["preOperations", "inOperations", "postOperations"]
self.cbPhases = wx.ComboBox(panel, 500, 'Phase', (50, 150), (160,-1), phasesList, wx.CB_DROPDOWN)
self.Bind(wx.EVT_COMBOBOX, self.OnPhaseSelection, id = self.cbPhases.GetId())
and this is the code of the "OnPhaseSelection" event :
def OnPhaseSelection(self, event):
self.phaseSelection = self.cbPhases.GetValue()
where i wanna save the selected value in the variable "self.phaseSelection" that i declared it with an
empty string as initial value, then i wanna use this variable with the new saved value, but when i run
the program, the variable contains the default value of the combobox! so please what is the problem in
my work ?
A: I'm not sure what's wrong with that. It looks like it should work. I copied most of it and put it into a runnable example that works on Windows:
import wx
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")
panel = wx.Panel(self, wx.ID_ANY)
self.ct = 0
self.phaseSelection = ""
self.opSelection = ""
self.instSelection = ""
self.orgSelection = ""
phasesList = ["preOperations", "inOperations", "postOperations"]
self.combo = wx.ComboBox(panel, choices=phasesList)
self.combo.Bind(wx.EVT_COMBOBOX, self.onCombo)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.combo)
panel.SetSizer(sizer)
#----------------------------------------------------------------------
def onCombo(self, event):
"""
"""
self.phaseSelection = self.combo.GetValue()
print self.phaseSelection
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can you use rsync to replicate block changes in a Berkeley DB file? I have a Berkeley DB file that is quite large (~1GB) and I'd like to replicate small changes that occur (weekly) to an alternate location without having the entire file be re-written at the target location.
Does rsync properly handle Berkeley DBs by it's block level algo?
Does anyone have an alternative to only have changes be written to the Berkeley DBs files that are targets of replication?
Thanks!
A: Rsync handles files perfectly, at the block level. The problem with databases can come into play in a number of ways.
*
*Caching
*File locking
*Synchronization/transaction logs
If you can insure that during the period of the rsync, no applications have the berkeley db open, then rsync should work fine, and offer a significent advantage over copying the entire file. However, depending on the configuration and version of bdb, there are transaction logs. You probably want to investigate the same mechanisms used for backups and hot backups. They also have a "snapshot" feature that might better facilitate a working solution.
You should probably read this carefully: http://www.cs.sunysb.edu/documentation/BerkeleyDB/ref/transapp/archival.html
I'd also recommend you consider using replication as an alternative solution that is blessed by BDB https://idlebox.net/2010/apidocs/db-5.1.19.zip/programmer_reference/rep.html
They now call this High Availabity -> http://www.oracle.com/technetwork/database/berkeleydb/overview/high-availability-099050.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Group by an array's element in PostgreSQL In Postgres 8.3, I need to group by certain elements within an array field. When I group by the array itself, all possible combinations are shown. I only want to group by the element.
something like this works for finding the count of a single element:
SELECT count(*)
FROM table
WHERE foo=any(bar)
this will return the correct count for a single element in an array. How do I return multiple counts for all elements in an array? If I group by the array, it will use all array elements in the identical order they are stored (not what I need).
edit for clarity:
bar is an array with values like {foo, some, thing} or {foo, thing} or {some, thing, else}
I want to know how many records have an element value of foo, some, thing, and else in the array "bar".
A: Something like
GROUP BY bar[4]
A: Hm.. you can't group by a value.. but of course the value is the column that contains it...
So.. you might want this:
SELECT AVG(blah), foo
FROM whatever
WHERE foo=any(bar)
GROUP BY foo
should work..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Curl::Err::HostResolutionError (Couldn't resolve host name) I'm running Rails 3.0 with a custom Devise authentication strategy that makes an SSL call using Curb. I get an "Curl::Err::HostResolutionError (Couldn't resolve host name)" error. Works fine manually from the command line.
The production environment is Apache running Passenger standalone with rvm 1.9.2@rails3, because the main Passenger is running ruby 1.8.7 and rails 2.3.4. I don't get this error with the my other app running the earlier versions of ruby and rails. Same code, but the difference seems to be Devise.
I've read elsewhere that this might have something to do with DNS and Apache, but I can't for the life of me figure this out and I'm really grasping at straws here. Any ideas would be greatly appreciated! Thanks in advance!
A: The issue actually turned out to be related to user permissions. When I ssh in with my user account and start Passenger standalone, no problem. When I start it remotely from Capistrano with the deploy user I get the error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Strange extra top space in body In this test page, the element has a strange extra amount of space on the top:
http://dl.dropbox.com/u/3085200/canvasTest/index.html
I tried putting margin, padding, top all to 0 for body, and padding to 0 for html, but none of it helped.
html
{
padding:0px;
}
body
{
margin:0px;
padding:0px;
top:0px;
}
A: Try this in css:
h1 {
margin-top: 0;
}
This is a common scenario (logo image wrapped in h1 tag):
A: You <h1> has default margin-top added to it, so it's pushing the <body> down from the top of the window.
body > h1:first-child { margin-top: 0; }
A: My console is showing a 0.67em top margin on the <h1> surrounding your top element.
Try this...
h1 {
margin: 0;
}
A: I believe this is actually caused by the margin on your h1 element.
A: Well, I'm sure the experts will laugh at this. I started using Expression Web 4 and tried to place the header info for my pages into a file header.txt to include on every page. I changed the file type from html to shtml and used this line:
All okay, except for a pesky extra space at the top of the file.
The solution was this:
Tools>Page Editor Options>Authoring
Uncheck .txt under "Add a Byte Order Mark when creating or renaming UTF-8 documents with these file extensions."
I hope this helps someone else as naive as I.
A: You can try to put a display flex on your body, it worked in my case
Hope it will help someone :)
A: I recognize that space at the top. This often happens to me too. In my case there is a hidden break (<br/>) somewhere between the <head> and <body>. When you find this break and remove it, the top space will be fixed!
A: I know this post is old, but I wanted to share a different solution that worked for me, for anyone that might come across this same post, looking for help, as I have.
Every solution I found seemed to be the result of an error, but I didn't have any errors, that could see. After over an hour of problem solving and piecing apart one of my past designs, I found this solution:
In the CSS for the DIV that you want attached to the top of the browser, add this one simple line:
#ContentContainer{
border: 1px solid transparent;
};
I'm not quite sure why it works or why it's needed, but it made the gap disappear.
A: html > h1:first-child { margin-top: 0; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: VBA gives wrong plotarea width? I want to get the PlotArea width and height in order to calculate the proportion.
I used ActiveChart.PlotArea.Width to get the width, and then tested the width using Photoshop.
I discovered that the width returned by ActiveChart.PlotArea.Width is wrong.
Image shows what I am talking about:
I have no Idea why...
Please help me to understand why it happens and how to fix it...
Thanks!
A: PlotArea.Width is returning the width in points not pixels.
http://msdn.microsoft.com/en-us/library/ff198324.aspx
Points are a unit of length. Pixels are variable on a number of factors like monitor, fonts, truefont settings, ect. Here is a SO post about converting pixels to points: Convert Pixels to Points
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mac App Store app with Safari Extension I'm trying to understand how an app like 1Password can be on the Mac App Store and come with a Safari extension (and most importantly, how can the extension communicate with the app) because I'd like to do the same.
Is the native app running a server as a subprocess that get's called by the safari extension?
I'd like to know if it's possible to do that and still be Mac App Store + Sandboxing friendly.
A: 1Password uses an agent to communicate between the Mac App and the Safari Extension. The agent is most likely a small server process that can receive RESTful calls from the extension(s). This mechanism allows the synchronization between all the different extensions (Safari, Chrome, Firefox, etc), the client and the main database.
The Safari extension is no longer installed directly by the 1Password app, by the way. Instead, you are directed to a web page that contains the Safari extension download, thus making the App sandbox-friendly.
A: I believe it's a regular .app that has a Safari extension inside it as a resource.
The app will check for the existence of the Safari extension on application launch, and if it doesn't find it in the default locations it will prompt the user to install it. If the users chooses to install it, the app copies the extensions to the Safari extensions folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Building a '2d' Haskell list Let testFn be a function that takes two Ints.
I am trying to write a function that builds an N x M two-dimensional table (a list of lists) containing all the values of (testFn i j) for i < N and j < M.
How can this be done?
A: A list comprehension would be the easiest:
[[testFn i j | j <- [0..(m-1)]] | i <- [0..(n-1)]]
A: [ [testFn i j | j<-[0..(M-1)] ] | i<-[0..(N-1)] ]
where M and N are preprocessor macros to be replaced for the actual variable names (which must begin with a lowercase letter) in the process of making the code valid Haskell.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Display data from XML in a SSRS tooltip I am creating a SSRS report. I need to display text in a tooltip(The data is in XML format) . Below is my sample xml.
<warnings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<linetext>This is Sugar.</linetext>
</row>
<row>
<linetext>This is coffee.</linetext>
</row>
</warnings>
I need the data inside the linetext node in bulleted format in the tooltip.Below is the format I would want in my tooltip.
.This is Sugar
.This is Coffee
Please Help!!
Thanks
A: The nice answer would be to write a custom assembly (.dll) and deploy that to your reporting server. In the custom assembly you can use the .NET xml parsing classes and iterate through your XML to get what you want.
But a hack answer is below. Embed this code in the report (Report menu -> Report Properties -> Code & paste to the text pane.)
Public Function ParseMyXML(ByVal s As String) As String
Dim parts() AS String = Split(s, "<linetext>")
Dim strBuilder As New System.Text.StringBuilder()
For i As Integer = 1 To parts.length - 1
strBuilder.Append(". ")
strBuilder.Append(Left(parts(i) , Instr(parts(i),"<") -1) & ControlChars.NewLine )
Next i
Return strBuilder.ToString()
End Function
Then call this from the body of the report with "=Code.ParseMyXML(stringFromWebService)"
The code above splits the xml and takes the text from the tag to the next "<" Not robust, but easy to implement and deploy. I think you can handle special characters by then treating the placeholder as html.
(First Visual Basic (> 1 line) I've written in months, maybe years.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery href behavior (waiting on a form completion from href link) As you can see below.. I would like to embed a simple HTML form in a hidden DIV.. I would like to SHOW that div on click.. Folding out the DIV and allowing the user to complete the form.. Once the Form Submit happens.. I would like to resume the action i.e. proceed to google.com
I'm stuck on the slide out and redirect behavior.. (is it possible to force the toggle open until form completion is successful?)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
body{
font-family:Verdana, Geneva, sans-serif;
font-size:14px;}
.slidingDiv {
height:300px;
background-color: #99CCFF;
padding:20px;
margin-top:10px;
border-bottom:5px solid #3399FF;
}
.show_hide {
display:none;
}
</style>
</head>
<body>
<div id="container">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
</script>
<a href="http://www.google.com" class="show_hide">check out google.com!</a><br />
<div class="slidingDiv">
<form>
some form... AJAX post
</form>
</div>
</div>
</body>
</html>
A: So you're looking for a link that triggers a form, and then after that form is submitted, to proceed with the link?
You need to disable the default behavior of the link and cache the URL. Then slide open the form and allow the user to do whatever. When the user submits the form (which is either a "Are you sure you want to leave?" question or a collection form processed with with AJAX) you then proceed with the link.
You want something to the effect of (on http://jsfiddle.net/Sb6CD/ too):
CSS:
body{
font-family:Verdana, Geneva, sans-serif;
font-size:14px;
}
.slidingDiv {
display:none;
height:300px;
background-color: #99CCFF;
padding:20px;
margin-top:10px;
border-bottom:5px solid #3399FF;
}
JS:
$(document).ready(function(){
$('a.show_hide').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
var url = $(this).attr('href');
$('.slidingDiv').slideDown();
$('form').submit(function() {
document.location = url;
return false;
})
});
});
A: I think I got your question. You want to follow the link only after the toggle is done sliding.. right?
This should be done like this:
<script type="text/javascript">
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
var el_link = $(this);
$(".slidingDiv").slideToggle(1000, function() {
document.location.href = el_link.attr('href');
});
return false;
});
});
</script>
Or something like this...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mercurial hosting with folders / repository organizing capabilities I'm currently using Bitbucket for my Mercurial repositories and it's working great. I would however like to be able to organize my repositories in folders, as having them all in one long list is a bit disorganized for my liking.
To be clear I'd like to be able to access my repositories kind of like this:
hg clone https://username@bitbucket.org/username/foldername/reponame
While (AFAIK) it is currently only possible to use a single reponame, no foldername.
Is there any Mercurial hosting provider that does this, or is there some other method that might help me organize my stuff?
I'm aware of subrepos and I might look into that, but it seems like a hackish solution to my problem (also one of the clusters I am working on uses an ancient Mercurial version from way before subrepos were added). Another possibility would be to have multiple user accounts for Bitbucket, but again that doesn't really scale well (I don't want to wind up with 10 accounts).
A: You will have to use separate repositories.
Kiln has a nice interface that supports multiple repositories.
Organize Your Code
Start simply by just creating the repositories you need for your
code. Kiln introduces branch repositories, repository groups, and
projects to help keep things organized as you develop your own
workflow.
...
Repository Groups and Projects are there to help keep related code
grouped together. Whether your software project is large or small, it
can be really helpful to separate different parts of the code into
different repositories. What used to be accomplished with complicated
naming schemes is now accomplished with simple labels and
drag-and-drop organization.
A: Kiln (kilnhg.com) has a concept of projects and groups for organizing repositories along with several other really cool features.
It is a commercial product, however. (Your question didn't mention whether or not that was a problem for you.)
A: The only way you can obtain this using Bitbucket is to create a single repository named "foldername" and put the sub-repository inside this 'root repository'. This however is not the best practice according to the mercurial philosophy. Also, you will have a single bitbucket panel as per a single repository.
You can then use the mercurial feature Suprepositories to manage the whole collection:
https://www.mercurial-scm.org/wiki/Subrepository
Read about the kind of layout you are looking for here:
https://www.mercurial-scm.org/wiki/UnderstandingMercurial
(point 6, at the end of the page)
Of course you can setup your personal mercural server to do this, but is a little bit tricky and I discourage it. If you wanto to try, you can start from here:
http://ekkescorner.wordpress.com/blog-series/git-mercurial/step-by-step-install-mercurial-server-on-ubuntu/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AndroidManifest.xml and style <activity android:name=".activity.MyHomePage" android:theme="@style/AppTheme.Light" android:label="New Tasks"/>
I have that Activity in my AndroidManifest.xml file. How do I set style on that android:label. I would like to set textsize and textcolor.
<style name="AppTheme.Light" parent="@android:style/Theme.Holo.Light">
<item name="android:windowBackground">@drawable/background</item>
<item name="android:actionBarStyle">@style/ActionBarTextSize</item>
<item name="android:windowTitleSize">14pt</item>
</style>
OR
<style name="ActionBarTextSize" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:textSize">14pt</item>
</style>
A: Are you talking about creating a custom window title style? If so, check this out: http://www.londatiga.net/it/how-to-create-custom-window-title-in-android/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating Membership DB (ASPNETDB) on remote server? I'm building a web application which soon I'll be promoting to production. This application has a login screen, as you know I used the integrated DB for developing. Now I want to move this database to a full SQL Server 2005. I'm using the aspnet_regsql.exe to create my membership tables and stored procedures in the SQL Server 2005 but I'm getting an error:
An error occurred during the execution of the SQL file 'InstallMembership.sql'. The SQL error number is 207 and the SqlException message is: Invalid column name 'FailedPasswordAnswerAttemptWindowStart'.
I google this for half of the day already and I can't seem to fine what's wrong, does anybody have ANY ideas on what am I doing wrong here? Any help will be really appreciate it.
A: The easiest way to deploy a brand new database to a remote server is to just publish the database from within Visual Studio. Once you do that you have the scheme and data all in one script. You then access your server either via a local SQL manager connection or a remote manager and run the script on your remote database.
The site 4GuysFromRolla has a nice little walk through with graphics which describe how to accomplish the publishing of your local database to your hosted one.
Good luck, and hope this helps you out some.
A: Go through the *.sql script file and see where that column reference is. Then you'll be able to see what exactly the script is doing to cause this error. My guess would be that it is getting caught up on referential integrity. If it is trying to create a foreign key constraint that that table/column does not exist then you'll see that error.
But back to the original question at hand. You don't need to recreate your whole database. That script file is to lay down the Membership for an empty database. If you have a working dev database you can just back it up and restore it to a production instance. No need to rebuild the membership database objects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: printk in driver I am really new to linux module programming.
I need to some how be able to do some tweak to the ath9k driver in linux.
I finally got the compat wireless source code of ath9k to compile in ubuntu 11.04 and was trying to play around with the code.
I tried using printk to tried to get to see what happen.
First I put printk in the init.c file, the message I printed show up when I use dmesg in the terminal. However, when I tried to use the same printk in another file like rc.c it does not show up at all.
I am wondering why is that?
And is there some other way that I could some how log some information from the code similar to the fprintf. What I need is I need to extract somehow the packet header from the driver.
Thank you
Best Regards.
A: read about the proc fs, it's a great framework to extract data from device drivers.
once you have registered a device node as proc fs, you can read from it.
once the the read function is called, a callback function you defined is creating the output. this is an excellent way to retrieve data from device.
there are also two other methods, one is sysfs, you can google for it. and the second,
if the the device is a char device, you can implement an ioctrl function which returns the info you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I create a route that matches an already ignored route? So, I have the following in my global.asax creating my MVC routes. They are called in the order that they appear below. What I expected to have happen was it would ignore the routes to the css folder, but then create the route to css/branding.css (which is generated at runtime from another view)
_routeCollection.IgnoreRoute("css/{*pathInfo}");
_routeCollection.MapRoute("BrandingCSS", "css/branding.css", new { controller = "Branding", action = "Css" });
Is this not possible? When I make a request to css/branding.css, I get a 404 error saying that the file does not exist. Is there a way to make this work, I'd rather it be transparent to anyone viewing source that this file is coming from anywhere but the css folder.
A: You can create and serve a custom css file by setting a RouteConstraint in your IgnoreRoute. Create the following constraint:
public class NotBrandingCss : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return values[parameterName].ToString().ToLowerInvariant() != "branding.css";
}
}
Then, change your IgnoreRoute to the following:
_routeCollection.IgnoreRoute("css/{*pathInfo}", new { pathInfo = new NotBrandingCss() });
Now, a request to /css/branding.css will fail your IgnoreRoute, and will go to your BrandingCSS route, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: instantiating an object from a web service vs instantiating an object from a regular class I have a very basic web service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebService1
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public int myInt = 0;
[WebMethod]
public int increaseCounter()
{
myInt++;
return myInt;
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
when I run that project my browser opens showing me the service:
on a different solution: (console application)
I am able to connect to that service by adding the reference:
then click on the add web reference button:
Lastly I type the url of the service I just created:
Now I am able to instantiate an object from the class Service1 from my console application as:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication36
{
class Program
{
static void Main(string[] args)
{
localhost.Service1 service = new localhost.Service1();
// here is the part I don't understand..
// from a regular class you will expect myInt to increase every time you call
// the increseCounter method. Even if I call it twice I always get the same result.
int i;
i=service.increaseCounter();
i=service.increaseCounter();
Console.WriteLine(service.increaseCounter().ToString());
Console.Read();
}
}
}
why does myInt does not increase every time I call the increaseCounter method? every time I call that method it returns 1.
A: Services created through the older .asmx technology are not singleton instances. This means that each call you make to the server instantiates a new instance of the service each time. Two real solutions, either use static variables (eugh....), or switch to using WCF.
A: Becaue on the server side the class is created and disposed with EVERY call you make from the client... your client is just a "proxy" and doesn't correspond directly to an instance on the server side...
You can either make myInt static or make the server side service class a Singleton... both options would mean that myIntis shared across ALL client... or you could implement some session management to achieve a client-specific myInt... using WCF for the server side seems IMHO the best solution - it comes with configurable options for singleton, session management etc.
EDIT - as per comments:
With WCF you can have .NET-clients with session management which in turn allows you to have different (client-specific) values for myInt...
A: webservice instance is destroyed at the end of each method call, so that's why you always get the same result. You need some way to persist that value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: font-variant: small-caps; shows different font sizes using Chrome or Firefox font-variant: small-caps;
font-size: 12px;
Firefox:
*
*Capital letters: 12px
*Lowercase letters: 10px
Chrome:
*
*Capital letters: 12px
*Lowercase letters: 8px
How to harmonize that without using JavaScript?
A: Webkit browsers display small-caps smaller than other browsers so.. You can use CSS media queries to easily sniff out webkit browsers like Chrome and Safari. Try something like this:
@media screen and (-webkit-min-device-pixel-ratio:0) {
.some-element-using-small-caps {
font-size: .85em
}
}
A: You can target the browsers individually by using css hacks like this:
@-moz-document url-prefix() {
//firefox specific css here
}
@media screen and (-webkit-min-device-pixel-ratio:0) {
//chrome specific css here - this will also hit other webkit browsers like safari tho
}
A nicer way however in my opinion involves a tiny bit of javascript that detects the browser and sets a class on the html element and then you can use that class as a base for targeting the individual browsers.
in the end it would look something like this:
<html class="firefox">
...
</html>
.firefox .rulename {
//firefox specific css here
}
and of course the same for chrome and whatever else browser
A: I am having a similar issue with a much weirder issue between Safari on iPad vs Safari on Desktops, showing a different scale for small-caps at 16px. For some reason small-caps is a bigger size on iPads, kinda matching that of Firefox.
Adjusting the font size or letter-spacing a half pixel less or so, can mitigate the issue without further additional hack. By essentially finding a tiny middle adjustment which trigger on one browser but not on another, to try and get as close as possible.
What I have observed for Firefox and IE, is that fonts tend to scale with many more intermediate sizes than that of Webkit. For example, in IE and Firefox, 15.6px is a tiny bit bigger or use more tracking to adjust, than that of 15.5px, and so is 15.7px, 15.8px etc. With a difference for nearly every 0.1 pixel. Whereas in Safari the difference is only perceived for every 0.4px or so.
For my small-caps case here which created an overflow issue, I used 15.5px, which is barely different from 16px on Safari (Desktop), yet bring down the small-caps size for IE and Firefox as close as possible to Safari's.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: case-insensitive key in xsd I have an XSD embedded into an XML like this:
<Replacements>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Replacements">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" ref="Replace" />
</xs:sequence>
</xs:complexType>
<xs:key name="ReplaceKey">
<xs:selector xpath="./Replace"/>
<xs:field xpath="@old"/>
</xs:key>
</xs:element>
<xs:element name="Replace">
<xs:complexType>
<xs:attribute name="old" type="AnythingButLowerCase" use="required" />
<xs:attribute name="new" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:simpleType name="AnythingButLowerCase">
<xs:restriction base="xs:string">
<xs:pattern value="[^a-z]+"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
<Replace old="A1020____9" new="A1020"/>
<Replace old="a1020____9" new="A1020"/>
</Replacements>
I've used xs:key to define a unique-key on "old" attribute of Replace elements.
my problem is I want this key to be CASE-INSENSITIVE.
I've read so many documents indicating I can use xsd functions like upper-case or translate to solve this, but if I write something like
<xs:field xpath="upper-case(@old)"/>
VS2010 gives me a warning like this:
'upper-case(@old)' is an invalid XPath for selector or field.
What is it I'm doing wrong?
Thanks :)
A: The correct XPath function is "upper-case", not "upper case". Just add in the hyphen.
A: OK!
I got that!
Using functions in an xpath for a xs:field is not allowed.
The workaround for what I was seeking is to define a simpleType and put a restriction there not allowing lower-case letters.
Something like this:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<Replacements>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Replacements">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" ref="Replace" />
</xs:sequence>
</xs:complexType>
<xs:key name="ReplaceKey">
<xs:selector xpath="./Replace"/>
<xs:field xpath="@old"/>
</xs:key>
</xs:element>
<xs:element name="Replace">
<xs:complexType>
<xs:attribute name="old" type="AnythingButLowerCase" use="required" />
<xs:attribute name="new" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:simpleType name="AnythingButLowerCase">
<xs:restriction base="xs:string">
<xs:pattern value="[^a-z]+"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
<Replace old="A1020____9" new="A1020"/>
<Replace old="a1020____9" new="A1020"/>
</Replacements>
Now this serves as what I want it to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7589303",
"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.