text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Django messages framework not working in template loop I recently upgraded to Django 1.3 and I want to start using the Messages system.
I have added my Middleware, Template context processors and also messages into the INSTALLED_APPS
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'facebook.djangofb.FacebookMiddleware',
'annoying.middlewares.RedirectMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
)
INSTALLED_APPS = (
'django.contrib.messages',
)
I'm simply just testing based on a view that makes a simple calculation.
in the admin, the messages show up, however when trying to render them in my base.html file I get the following error.
Caught TypeError while rendering: 'module' object is not iterable
and in the stack it fails here.
{% for message in messages %}
I have also removed the for statement and the I still get the following error, nothing more
<module 'django.contrib.messages' from '/Users/ApPeL/.virtualenvs/mysite.com/lib/python2.7/site-packages/django/contrib/messages/__init__.py'>
Any ideas?
A: I just encountered this problem. I had included the following in my context processor:
from django.contrib import messages
...
def allrequests(request):
ctx = {
...
'messages': messages
}
return ctx
Make sure you are not setting messages in the context, as it is set in the correct manner by django.contrib.messages.context_processors.messages.
A: How did you MIDDLEWWARE_CLASSES and TEMPLATE_CONTEXT_PROCESSORS in settings.py, it must look like :
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.i18n",
"django.core.context_processors.request",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages"
)
And in INSTALLED_APPS :
'django.contrib.messages'
And in your template (did you forgot the if? ):
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
I hope it will help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: OSM: convert ties from projected coordinates in spherical mercator "EPSG:900913" to "EPSG:4326" coordinates I'm using a map with a layer (from the example):
var lonLat = new OpenLayers.LonLat(40.4088576, -86.8576718)
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
map.getProjectionObject() // to Spherical Mercator Projection
);
on moveend i'm get center coordinates:
map.getCenter();
map.getZoom();
and zoom level: 4925535.4503328, -9668990.0134335, 12
Using algorithm from documentation
public PointF TileToWorldPos(double tile_x, double tile_y, int zoom)
{
PointF p = new Point();
double n = Math.PI - ((2.0 * Math.PI * tile_y) / Math.Pow(2.0, zoom));
p.X = (float)((tile_x / Math.Pow(2.0, zoom) * 360.0) - 180.0);
p.Y = (float)(180.0 / Math.PI * Math.Atan(Math.Sinh(n)));
return p;
}
i get Y ~ 90, and X ~ 432662
but i need coordinates in bounds: -180..180
something like: 40.4088576, -86.8576718
what is wrong?
A: Why not just get OpenLayers to project it back for you? So if you want the centre point as WGS84 then just do:
var center = map.getCenter().transform(map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326"));
I think you'll find that will do what you want anyway, at least if I've understood the question right...
By the way, EPSG:4326 is the natural WGS84 lat/lon values that you seem to be looking for - the large numbers are the projected coordinates in spherical mercator, which is EPSG:900913.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Using php as a desktop application
Possible Duplicate:
PHP as a Desktop Programming Language
I have developed a sales application with php (codeigniter framework). i am using xampp to run this application in local PC's browser. now i want 2 things:
*
*is there any way to run this application as a desktop application? something like an icon will open the app and run without any browser. also without xampp to be set up.
*also i want to protect the code from unauthorized using. someone can easily copy the code and run it on other computer. i want to prevent this.
please help me about these issues. thanks in advance.
A: PHP is not really suitable for either of these things. You're going to need a browser either way, but you could if you really wanted to use some kind of custom browser (e.g., you can use Java or .NET to create a window that has a basic browser page with only whatever controls you want to add on it rather than a full browser).
You won't be able to prevent people copying it, but you could try googling for a PHP obfuscator to make the code hard to read and you could add whatever checks you may wish to determine the PC is one you've approved (perhaps some kind of license file and you could activate it against a MAC address or something).
A: PHP is a recursive acronym which stands for "PHP: Hypertext Preprocessor." At its core, PHP is designed to process information and output it as HTML ("Hypertext"). If you wish to output information primarily as something other than HTML, PHP is probably the wrong language.
PHP is also a scripting language. That means that it is not compiled (converted from source code to machine code). As such, the scripts are human-readable. Tools such as phc exist, but if you want a compiled application, PHP is probably the wrong language.
Can you use PHP as a desktop application? Yes. Can you compile PHP? Yes. Should you? Probably not, because you are circumventing the purpose and features of the language.
A: You can use PHP/GTK+ to create a PHP Desktop Application, but the code protection is very difficult, you can try ofuscating the code, or you can use a php compiler like this: http://www.phpcompiler.org/
I would not use php to develop a desktop application as you like, try using another language, dont use scripting, use compiled codes.
Luck with you project.
A: If you are interested in writing client-side applications with PHP, you have to use PHP-GTK. I don't know how flexible is that. In any case, you should try it to see what it can do for you ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: setText not working for EditTextPreference I'm trying to set value for EditTextPreference item
with hostPreference.setText("Not yet set");
But text is not showing
I want to show it like Use Name here
public class HostSettingActivity extends PreferenceActivity {
private final String MY_DEBUG_TAG = "SettingActivity";
SharedPreferences sharedPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(MY_DEBUG_TAG, "HostSettingActivity Started");
super.onCreate(savedInstanceState);
sharedPrefs = getPreferenceManager().getSharedPreferences();
setPreferenceScreen(createPreferenceHierarchy());
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e(MY_DEBUG_TAG, "On Destroy");
}
private PreferenceScreen createPreferenceHierarchy() {
// Root
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this);
dialogBasedPrefCat.setTitle("Host Settings");
root.addPreference(dialogBasedPrefCat);
EditTextPreference hostPreference = new EditTextPreference(this);
hostPreference.setKey("host");
hostPreference.setDialogTitle("Host");
hostPreference.setText("Not yet set");
hostPreference.setDefaultValue("http://example.com");
hostPreference.setSummary("Set host");
dialogBasedPrefCat.addPreference(hostPreference);
EditTextPreference portPreference = new EditTextPreference(this);
portPreference.setKey("port");
portPreference.setDialogTitle("Port");
portPreference.setDefaultValue("8080");
portPreference.setSummary("Set port");
dialogBasedPrefCat.addPreference(portPreference);
hostPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
EditTextPreference etp = (EditTextPreference) preference;
String newHostValue = newValue.toString();
Log.i(MY_DEBUG_TAG, "New Host: "+newHostValue);
etp.setText(newHostValue);
return true;
}
});
return root;
}
}
A: Text is not seen in EditTextPreference, but can be edited.
What is seen is TITLE, and it is set by setTitle.
If you want to display your edited text in title, you must set it as title yourself.
A: I think you're confusing setText with setTitle...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compare two SQL Server Profiler traces I want to compare two SQL Server profiler traces, any tool does this?
Thanks,
Ramkumar
A: In the profiler you can export the trace files by using File | Export | Extract SQL Server Events | Extract Transact-SQL Events.
When you do this for both traces, you can compare them for instance with Notepad++ (compare plugin).
A: There is an option to write your results to a database table. If you do that, then you can write queries to compare the aggregate results of both. This would be meaningful, provided that both runs occur at the same time of day and go for the same duration.
I've recently blogged about how to use SQL Profiler to optimize databases.
A Beginner's Guide to SQL Server Database Optimization
A: Save them to a text file and use a file comparison tool like Beyond Compare?
A: The first part of Wilco's answer is good (In the profiler you can export the trace files by using File | Export | Extract SQL Server Events | Extract Transact-SQL Events) and I do use Notepad++ from time to time to compare, however using Winmerge is very easy. Install the little component: http://winmerge.org/?lang=en
Find the two files you want to compare with Winmerge installed, highlight them, right-click and choose "Winmerge", will then open the editor in compare mode.
A: Most answers are about comparing, literally, two trace files.
However, I think the OP was asking how to determine if a change in code or hardware improved/degraded performance.
In that case:
*
*Database Experimentation Assistant, from Microsoft - painful to use
*DBSophic Qure Optimizer - now owned by "EZ Manage", whom I've never heard of. Doesn't support SQL Server 2016
*Roll your own - http://sqlmag.com/database-performance-tuning/sql-servers-trace-and-replay-tool - be sure to install Itzik Ben-Gan's sqlsig SQL CLR helper for aggregating your data, available here: https://technet.microsoft.com/en-us/library/cc293616.aspx
A: @Narnian is correct, comparing the traces in a database is usually easiest. If your traces were captured into files, you can use fn_trace_gettable to read those files into a database.
Do note that I said, a database. You're rarely going to want to load them into the same database that you profiled. Typically I use a different instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Changing UIView when applicationWillEnterForeground fires I am looking for a way to grab the current view being shown to the user when they send the application to the background.
The situation is that I have provided options in my settings bundle for look and feel that I would like to take effect when the applicationWillEnterForeground is fired.
Anyone have a suggestion as to how to attack this problem?
I tried to register a NSNotification, but it fires to late and the view appears to the user before the NSNotification method runs.
A: To grab the current view being shown when the user backgrounds your app, use your AppDelegate's applicationDidEnterBackground method.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Get current view...
// (get from UITabbarController or whatever logic you like)
// For this code sample, just grab first UIView under the main window
UIView *myView = [self.window.subviews objectAtIndex:0];
}
To change the view before it shows, use the AppDelegate's applicationWillEnterForeground method like this:
- (void)applicationWillEnterForeground:(UIApplication *)application
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 80, 80)];
label.backgroundColor = [UIColor whiteColor];
label.text = @"yo";
[self.myLastView addSubview:label];
}
I realize you mentioned the applicationWillEnterForeground in your question. Can you be more specific with what you are trying to do or possibly include code? I actually tried the code above and the view update (I see the label "yo" above my view).
My last suggestion is to try calling [view setNeedsDisplay] and [view setNeedsLayout] which should force the UIView to redraw itself. (note - issue isn't that uiview changes don't show up, issue is that they show up after the old view is shown. It appears a screenshot is taken before suspending app and this screenshot is initially shown upon resuming app for performance)
Edit
Code above is a good example of what user is seeing. The label "yo" shows up, but only after the view is restored. I'll see if I can fix this and repost.
Edit 2
It appears that resuming a suspended app shows a captured screenshot of the app's last known state as far as I can tell. I've tried to find docs to this effect, but I can't find it.
Alternative Solution 1
Have your app exit when the user hits the home button.
If you save the state of your app in either applicationWillResignActive: or applicationWillTerminate:, you can simply restore that state (navigate to correct tab user was last on) and in appDidFinishLaunchingWithOptions: you can update the UI before the user sees it. To have your app exit when backgrounded (suspended) put the key "Application does not run in background" - raw key: UIApplicationExitsOnSuspend to YES.
Doing this will guarantee that the user will see your app the way they configured it in settings without seeing a flicker of what it used to look like. I'm sorry I couldn't find a better way to do this. :(
Alternative Solution 2
Display your settings inside your app.
This obviously would require a design change, however more and more apps are showing settings inside the app. A popular third party library is In App Settings Kit. This lets you configure settings via a bundle / plist file just like you would for global app settings. It also looks and behaves just like the global settings. This will give you FULL control of any behavior you want inside your app.
A: I'm going to guess that you have it backwards.
The system may take a snapshot of the current screen, and it shows this when your app is restored to the foreground. It may be that this snapshot is showing the old look, before you get a chance to change it at applicationWillEnterForeground: time.
So, change when you get applicationWillEnterForeground:, then the snapshot will be taken from what you want to restore to.
A: In each viewDidLoad you can always post a notification, see NSNotification Class Reference, you can either store a reference to the view in NSUserDefaults, then do what you need to do when the user returns in applicationWillEnterForeground:
A: Just in case someone comes around with the same problem:
It seems that Apple has implemented a new property in iOS7 on UIApplication which prevents using the previously taken snapshot when reentering into foreground - ignoreSnapshotOnNextApplicationLaunch
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: unexpected non-whitespace character after JSON data? I want in output this PHP code echo name, star_type, service by jquery.each(), but i have error. how is fix it?
error:
An error has occured: [object Object] parsererror
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data
I have this PHP code:
//$hotel_id = $this->input->post('hotel_id');
$hotel_id = array('1','2','3');
//print_r($hotel_id);
foreach ($hotel_id as $val) {
$query_r = $this->db->query("SELECT * FROM hotel_submits WHERE id LIKE '$val' ORDER BY id desc");
$data = array();
foreach ($query_r->result() as $row) {
$data_s = json_decode($row->service, true);
$data_rp = json_decode($row->address, true);
$data[] = array(
'name' => $row->name,
'star_type' => $row->star . '-' . $row->type,
'site' => $row->site,
'service' => $data_s,
'address' => $row->address
);
}
echo json_encode($data);
}
This is output above PHP code:
[{
"name": "how",
"star_type": "5-hotel",
"site": "www.sasaas.assa",
"service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"]"address": "chara bia paeen"
}][{
"name": "hello",
"star_type": "4-motel",
"site": "www.sasasa.asas",
"service": ["koko", "sili", "solo", "lilo"]"address": "haminja kilo nab"
}][{
"name": "hi",
"star_type": "3-apparteman",
"site": "www.saassaas.aas",
"service": ["tv", "wan", "hamam", "kolas"],
"address": "ok"
}]
And this my js code that get error:
$.ajax({
type: "POST",
dataType: "json",
url: 'get_residence',
data: dataString_h,
cache: false,
success: function (respond) {
//alert(respond);
$.each(respond[0].name, function (index, value) {
alert(value);
});
},
"error": function (x, y, z) {
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
A: You are not echoing valid json. Try this:
$hotel_data = array();
foreach(...) {
// .. do stuff
$hotel_data[] = $data; // add $data to the end of the $hotel_data array
}
echo json_encode(array('data' => $hotel_data));
This will wrap all the $data arrays into an array and put it into an object's data attribute. You can access this data on the js side as follows:
$.each(response.data, function(i, obj) {
alert(obj.name);
});
Note: I am not sure about the php syntax I wrote above, its been a while since I wrote php :)
A: Your php output is not valid json, you missed a comma before "address".
You can check your json with this url: http://json.parser.online.fr/
A: Your JSOn is completely invalid. You shouldn't echo json-ecnoded array inside the loop, but outside it:
$all_data = array();
foreach ($hotel_id as $val) {
//..what you have there now, but instead if echo json_encode($data); you do
$all_data[] = $data;
}
//and finally
echo json_encode('data'=>$all_data);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to style parents of a certain element type in SASS? I want to do this:
.classname {
color: red
a& {
color: blue;
}
}
and for it to compile to:
.classname {
color: red;
}
a.classname {
color: blue;
}
Is there syntax available to support this? I have tried using a&, #{a&} and the compass function #{append-selector("a", "&")} but they don't compile, a & does, but results, obviously, in a .classname rather than a.classname.
A: I tried thinking through various options that would let you do this, but I can only come back with "why"? What's the use case, and why do you need to do this vs something else that achieves the same result as what you'd like to do.
A: I wasn't able to find a solution for tags but in this specific case you can use &[href]. It's slower but it's actually more precise (some <a> tags might not be links.)
Hopefully soon we'll be able to use &:any-link (What's the :any-link pseudo-class for?) but it's not supported by browsers yet
A: This isn't really possible with the nested syntax for SASS. From the SASS reference:
The inner rule then only applies within the outer rule’s selector.
Nested rules are syntactical sugar that makes CSS's descendent selectors easier to write, since they're one of the most common CSS constructs. While it's be nice to use your approach for writing that kind of rule, it's not what the syntax is designed (or defined) to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: jQuery dropdown navigation I am using simple jQuery code to make drop down navigation, but its not giving expected results...
jquery code
$(function() {
$('.nav li').hover(function () {
$('ul', this).slideDown(100);
}, function () {
$('ul', this).slideUp(100);
});
});
html code
<ul class="nav radius clearfix">
<li><a href="#">Dashboard</a></li>
<li><a href="#">Projects</a>
<ul class="radius">
<li><a href="#">Recent Projects</a></li>
<li><a href="#">Archive Projects</a></li>
<li><a href="#">New Project</a></li>
</ul>
</li>
<li><a href="#">Messages</a></li>
</ul>
Please check and let me know what's I am missing. thanks.
A: Edit: to address the animation "flickering issue" in addition to starting in a closed state, you can use the following (check it on jsfiddle here). It's not very elegant but this issue arises from the way some browsers handle the change in size of the elements involved, and this does resolve that:
$(function() {
$('.nav li').hover(function () {
$('ul:not(:animated)', this).slideDown(100);
}, function () {
$('ul:not(:animated)', this).slideUp(100);
});
$('.nav li ul').slideUp(0);
});
A: Try this -- it adds a delay to keep the "flickering" you're sometimes experiencing.
$(function() {
$('.nav li').hover(function () {
$('ul', this).delay(50).stop().slideDown(100);
}, function () {
$('ul', this).delay(50).stop().slideUp(100);
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to bind to an owning window's control-property (from a dialog window)? My friends,
i Have a problem in WPF which i just cannot solve. I have two Windows, Mainwindow and Window1. I'd like to bind a ListView in my child-window to a controls property in the parent-window. In detail:
Mainwindow has a control declared in XAML,
<local:MyControl x:Name="View"/>
Further down i have a Listview which get's fed by a public property of 'View', 'Session.Events' (Observable Collection)
<ListView ItemsSource="{Binding ElementName=View, Path=Session.Events}"/>
Which works fine, but now i have a second Window spawned from Mainwindow in such manner:
Window1 MyWin1 = new Window1();
MyWin1.Owner = this;
MyWin1.ShowDialog();
And this second window has a ListView which also needs to be fed by my 'View' control. I'd like to do it via binding but i bite my teeth out. It does not work, whatever i try. I do have a working version via code-behind ...
Window1 Parent = (Window1)this.Owner;
MyListView.ItemsSource = Parent.CCView.Session.Events;
But i would prefer doing the bind in XAML and save the extra-code. Also i hope it will help me to understand bindings better, which for me are still a mystery to some extend.
Thank you so much and my best regards,
Paul
A: You can bind across the logical tree of your XAML. The second window is not part of the first window's tree. I'd think the most simple way in your situation should be to pass over the DataContext to your child window:
MyWin1 = new Window1 {
DataContext = this.DataContext,
Owner = this
};
MyWin1.ShowDialog();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP - Cast int key to string? I have a few large PHP functions written some time ago. They contain some associative arrays. Until now, I had no problem with these arrays because they contained keys of type string and int (like "brown" and 118). The problem is, when the keys are all int, they are not kept, instead the are converted to 0, 1 etc.
Is there any way to force an array to keep the keys I give to it, even if they are all int? The functions are pretty large and it would take too long to change them.
EDIT
As Mike B intuited, I use a sorting function which seems to reindex the arrays. I was using a function I found here: Sort an Array by keys based on another Array?
It was the first one, the one of Erin, but it didn't keep the correct indexes. I tried the version edited by Boombastic and it works well.
Thanks for all your answers!
A: I have similar problem with $array = ['00'=>'x','11'=>'y'] that was converted to integer keys, losting a '0' digit.
Writing only to offer an answer 5 years after...
The KennyDs answer can be simplified by,
$array = array_map('strval',$array);
... but, as MikeB commented, KennyDs answer is wrong, the correct is:
foreach($array as $key => $val)
$array[(string) $key] = $val;
or in a (ugly) functional style,
$array = array_flip( array_map('strval', array_flip($array)) );
(no direct way as I checked).
About check by var_dump() or var_export(): show string as number when parse as number (eg. '123' as 123), but, it not lost string (!), the example array ( '00' => 'x', 11 => 'y',).
A: You could also just go over the array and cast all the int's to a string?
foreach($array as $key => $val){
$array[$key] = (string)$val;
}
Edit: if you need your keys to be int then just make sure when you are filling the array you add an (int) cast before the $key.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Programmatically insert a method call on each property of a class My question is based on this article.
Basically a class can implement a Freezable method to make sure that no properties can be changed once the object enters the Frozen state.
I have an interface that follow this design
public interface IFreezableModel
{
void Freeze();
bool IsFrozen{get;}
}
the objective is to make sure that once the Freeze method is called, the IsFrozen property is set to True and the properties of the object cannot be changed anymore.
To simplify, I will be using an abstract base class:
public abstract class BaseFreezableModel : IFreezableModel
{
public void Freeze()
{
_isFrozen = true;
}
public bool IsFrozen
{
get {return _isFrozen;}
}
protected ThrowIfFrozen()
{
if (IsFrozen)
throw new Exception("Attempted to change a property of a frozen model");
}
}
this way I can have a class like
public class MyModel : BaseFreezableModel
{
private string _myProperty;
public string MyProperty
{
get{return _myProperty;}
set
{
ThrowIfFrozen();
_myProperty = value;
}
}
}
This is all nice and simple, but which strategy can I adopt to make sure all properties follow the pattern above? (apart from writing setters and getters)
These are the alternatives I came up with:
*
*Find a mechanism to inject a method into each property setter using emit perhaps. But I have no idea how to do it, what potential issues I may encounter (and therefore how long it will take). If someone knows this and can point me in that direction, it would be great.
*Use some templates during the build process so that the Call to OnCheckFrozen is inserted just before compile time. This has the advantage of being really simple to understand and can work for similar scenarios.
*Find a framework that can do all of this for me, but it just as an extreme case as I am not allowed to use external framework on this project.
What solutions would you use to accomplish this?
A: As Matt already mentioned, you can use aspect oriented programming. Another possibility is to use a technique called interception, as it is provided by the Unity application block.
A: as Matt said with the addition of writing an FxCop rule to check for the method call
A: how about an extra bit of indirection using the proxy pattern so you can inject the frozen check there? if the object the proxy refers to is frozen throw, if not proceed. however, this means you need a proxy for every IFreezableModel (though maybe generics could overcome this) and it will apply for every class member you're accessing (or the proxy needs more complexity).
A: You're entering the world of Aspect Oriented Programming here. You could knock together this kind of functionality in 5 minutes using PostSharp - but it seems you're not allowed to use external frameworks. So then your choice comes down to implementing your own very simple AOP framework, or just biting the bullet and adding checks to every property setter.
Personally I'd just write checks in ever property setter. This may not be as painful as you expect. You could write a visual studio code snippet to speed up the process.. You could also write a smart unit test class which would, using reflection, scan through all the properties of a frozen object and attempt to set a value - with the test failing if no exception was thrown..
EDIT In response to VoodooChilds request..
Here's a quick example of a unit test class, using NUnit and the excellent FluentAssertions library.
[TestFixture]
public class PropertiesThrowWhenFrozenTest
{
[TestCase(typeof(Foo))]
[TestCase(typeof(Bar))]
[TestCase(typeof(Baz))]
public void AllPropertiesThrowWhenFrozen(Type type)
{
var target = Activator.CreateInstance(type) as IFreezable;
target.Freeze();
foreach(var property in type.GetProperties())
{
this.AssertPropertyThrowsWhenChanged(target, property);
}
}
private void AssertPropertyThrowsWhenChanged(object target, PropertyInfo property)
{
// In the case of reference types, setting the property to null should be sufficient
// to test the behaviour...
object value = null;
// In the case of value types, just create a default instance...
if (property.PropertyType.IsValueType)
value = Activator.CreateInstance(property.PropertyType);
Action setter = () => property.GetSetMethod().Invoke(target, new object[] { value });
// ShouldThrow is a handy extension method of the FluentAssetions library...
setter.ShouldThrow<InvalidOperationException>();
}
}
This method is using a parameterized unit test to pass in the types being tested, but you could equally encapsulate all of this code into a generic base class (where T : IFreezable) and create extended classes for each type being tested, but some test runners don't like having tests in base classes.. *ahem*Resharper!ahem
EDIT 2 and, just for fun, here's an example of a Gherkin script which could be used to create much more flexible tests for this kind of thing :)
Feature: AllPropertiesThrowWhenFrozen
In order to make sure I haven't made any oversights in my code
As a software developer
I want to be able to assert that all properties of a class throw an exception when the object is frozen
Scenario: Setting the Bar property on the Foo type
Given I have an instance of the class MyNamespace.MyProject.Foo
And it is frozen
When I set the property Bar with a value of 10
Then a System.InvalidOperationException should be thrown
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Defining an output file stream within a class How can I define an output file stream within a class, so that I don't have to keep passing it around to functions. Basically what I want to do is this:
class A {
private:
ofstream otp ;
};
Then in my constructor, I simply have otp.open("myfile"); and in other functions I have otp.open("myfile", ios::app); , but it fails during compile time, saying:
../thermo.h(18): error: identifier "ofstream" is undefined
ofstream otp ;
I have made sure to #include <fstream>
Thanks!
A: You'll need to use the fully qualified name, std::ofstream.
A: You need either place a using namespace std; statement above your class's declaration or declare the otp variable as std::ofstream because it exists within the std namespace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In Firefox insertRow() is not working in javascript I am working in a JSP file. In that I need to create one table with multiple rows onclick event. When I am trying the following code in IE7 and IE8, it is working fine. But when I am trying the same in Firefox[ (in any version) it is not creating the table.
This is the div part I need to create ,
<div id="acc" style="display:none" width="90%">
<table border=0 cellpadding=1 cellspacing=1 width="97%" align="center">
<tr>
<td class="txnSubHdrBg">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td nowrap>Account Details</td>
<td align="right">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="padding-right:2px;" valign="top"><a href="javascript:void(0)"><img src="/images/add_account_but.jpg" border="0" alt="Add account credit details" onclick="return addAccountRow(); return false;"/></a></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<% int rowId=0;%>
<table border=0 cellpadding=1 cellspacing=1 width="97%" id="AccountList" align="center" >
<logic:iterate name="xMBeneficiaryRegistrationForm" property="beneficiaryAccountList" id="row">
<tr><td>
<table cellpadding=0 cellspacing=6 width="100%">
<tr>
<html:hidden name="row" property="accountSerialNo"/>
<td class="fieldLabel" width="180"><bean:message key="XpressMoney.Xpress.AccountName"/></td>
<td class="fldtxt">
<html:text name="row" property="accountName" styleClass="fieldText" size="20" tabindex="27" style="width:167px" title="Input Account Name" onkeypress="return AcceptableCharsforAddress(event); return false;"/>
<span class="fieldLabel" ><bean:message key="label.mamStatus"/></span>
<html:select property="accountStatusDisplay" tabindex="28" styleClass="fieldText" size="1">
<html:option value="1"><bean:message key="XpressMoney.XM.Enable"/></html:option>
<html:option value="1073741824"><bean:message key="XpressMoney.XM.Disable"/></html:option>
</html:select>
</td>
</tr>
<tr>
<td class="fieldLabel"><bean:message key="XpressMoney.Xpress.AccountNo"/></td>
<td class="fldtxt">
<html:text name="row" property="accountNo" tabindex="29" styleClass="fieldText" onkeypress="return AcceptCharsandNumbers(event)" style="width:167px;padding:0 0 0 3px" size="20" title="Input Account No"/>
</td>
</tr>
<tr>
<td align="left" class="fieldLabel">Bank Name</td>
<td class="fldtxt">
<input type="hidden" name="beneficiaryBankTemp" value=<bean:write name="row" property="beneficiaryBank"/>>
<select class="fieldText" style="width:250px" name="beneficiaryBank" onchange="retrieveDestinationBeneficiaryBankName(<%=rowId%>)" >
<option value="0">--select Bank--</option>
</select>
</td>
</tr>
<tr>
<td align="left" class="fieldLabel">Beneficiary Bank</font></td>
<td class="fldtxt">
<input type="hidden" name="beneficiaryBankNameTemp" value=<bean:write name="row" property="beneficiaryBankName"/>>
<select class="fieldText" style="width:250px" name="beneficiaryBankName" onchange="setSelectedBankValuesToHidden();">
<option value="0">--select Beneficiary Bank--</option>
</select>
</td>
</tr>
</table>
</td>
</tr>
</logic:iterate>
</table>
<%rowId++;%>
The function which I have for addrows is,
function addAccountRow()
{
var AccountListTable = document.getElementById('AccountList');
receivingAgentCodeIndex = AccountListTable.rows.length;
var countryBankHTML = "<input type ='hidden' name='beneficiaryBankTemp' value=''/><select class='fieldText' name='beneficiaryBank' id='beneficiaryBank'"+receivingAgentCodeIndex+"' onchange='return retrieveDestinationBeneficiaryBankName("+receivingAgentCodeIndex+"); return false;' style='background-color:#FFFFFF;width:250px' maxlength='60' ><option value='0'>---Select Bank---</option></select>"
var countryBeneficiaryBankHTML = "<input type ='hidden' name='beneficiaryBankNameTemp' value=''/><select class='fieldText' name='beneficiaryBankName' id='beneficiaryBankName'"+receivingAgentCodeIndex+"' onchange='setSelectedBankValuesToHidden();' style='background-color:#FFFFFF;width:250px' maxlength='30' <option value='0'>---Select Beneficiary Bank---</option></select>" ;
var index = AccountListTable.rows.length;
if (validateAccountFields(index))
{
var AccountListTableRow = AccountListTable.insertRow();
AccountListTableRow.setAttribute("id",index);
var AccountFieldsHTM1 =" <table border=0 cellpadding=0 cellspacing=5 width='100%' id='AccountList1' style='padding:0 0 0 0'><tr><input type ='hidden' name='accountSerialNo'/>"+
"<td class='fieldLabel' width='181'><bean:message key='XpressMoney.Xpress.AccountName'/></td>"+
"<td class='fldtxt'><input type='text' name='accountName' class='fieldText' size='20' style='width:167px' title='Input Account Name' onkeypress='return AcceptableCharsforAddress(event); return false;'/>"+
" <span class='fieldLabel'><bean:message key='label.mamStatus'/></span>"+
"<select name='accountStatusDisplay' class='fieldText' size='1'><option value='1' selected><bean:message key='XpressMoney.XM.Enable'/></option><option value='1073741824'><bean:message key='XpressMoney.XM.Disable'/></option></select></td></tr>"+
"<tr><td class='fieldLabel'><bean:message key='XpressMoney.Xpress.AccountNo'/></td>"+
"<td class='fldtxt'><input type='text' name='accountNo' class='fieldText' onkeypress='return AcceptCharsandNumbers(event)' size='20' style='width:167px' title='Input Account No'/></td></tr>"
+ "<tr><td class='fieldLabel' >Bank Name</td><td class='fldtxt' >"+countryBankHTML+"</td></tr>"
+ "<tr><td class='fieldLabel' >Beneficiary Bank</td><td class='fldtxt' >"+countryBeneficiaryBankHTML+"</td></tr></table>"
var AccountCredit = AccountListTableRow.insertCell();
AccountCredit.insertAdjacentHTML('afterBegin',AccountFieldsHTM1);
retrieveDestinationCountryDetailsV1(receivingAgentCodeIndex);
}
}
How can I make it Firefox compatible?
A: See https://developer.mozilla.org/en/DOM/table.insertRow:
If index is omitted or greater than the number of rows, an error will
result.
I'd suggest using a cross-browser JavaScript library like jQuery, which will work whatever the browser is.
A: Here is a solution:
var row = infoTable.insertRow(-1);
var cell = document.createElement("td");
cell.innerHTML = " ";
cell.className = "XXXX";
row.appendChild(cell);
A: See https://developer.mozilla.org/en/traversing_an_html_table_with_javascript_and_dom_interfaces
You should use DOM method in FF/XUL. Check the above link, the code given there works fine in IE & FF.
Even, I would suggest you to use jQuery is the most recommendable one.
A: Use
var tr = document.createElement("TR");
AccountListTable.rows.append(tr)
or
var lastRow = AccountListTable.rows.length;
var row = AccountListTable.insertRow(lastRow);
A: I would use JQuery: http://api.jquery.com/
There is a similar question with an answer using JQuery:
Add table row in jQuery
Please let us know if using JQuery is not an option.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java - Socket not reading until client disconnects? So I made a Server and Client with sockets in Java. I'm trying to get the server to read/write from the socket, but it only reads once the client disconnects:
System.out.println("Server initialized");
clientSocket = server.accept();
System.out.println("Client connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
for(int loop = 0;loop<5;loop++){
out.write("Hello");
System.out.println(in.readLine());
} //end for
The problem is that once the client connects, it says "Client connected" but then it doesn't run through the for loop. Once the client disconnects, however, the server executes the for loop and returns
null
null
null
null
null
What am I missing here? Here is my full server code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public ServerSocket server;
public Server(int port){
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Cannot bind to port: "+ port);
System.exit(-1);
}
} //end constructor
public void WaitForClient() throws IOException{
Socket clientSocket = null;
try {
System.out.println("Server initialized");
clientSocket = server.accept();
System.out.println("Client connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
for(int loop = 0;loop<5;loop++){
out.write("Hello");
System.out.println(in.readLine());
} //end for
} //end try
catch (IOException e) {
System.out.println("Accept failed");
System.exit(-1);
} //end catch
clientSocket.close();
server.close();
} //end method
} //end class
(My main method is called from another class.)
A: You have to flush the stream on the server if you want to see the results immediately. The stream is auto-flushed on close(), that's why you seen the output then.
A: At first glance, it looks like your call to in.readLine() is blocking because it hasn't encountered a newline yet.
Thus, it blocks until your connection drops.
Try BufferedReader's read method:
public int read(char[] cbuf,
int off,
int len)
and pass in a fixed length array such as:
char[] cbuf = new char[1024];
Use the return value of the read call to see how many bytes were in the last read (0-1024)
if you read 1024, there is likely more to read. If you read 0, then there is likely no more to read.
A: You are reading lines but you aren't writing them. write() doesn't write a newline, and readLine() blocks until it receives one.
A: It is server side Code for accepting String From Client but according to my code u will have use DataInputStream and DataOutputStream instead of PrintWriter And BufferedReader.
This code is Completely Working for One to One Client..
In code "jta" is JTextArea ..
soc = server.accept();
while(true)
{
String data="";
try
{
dis = new DataInputStream(soc.getInputStream());
dos = new DataOutputStream(soc.getOutputStream());
data = dis.readUTF();
}
catch(Exception e)
{ }
jta.append(data + "\n");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Authenticating across domains : How to? Before you write off this question as a dupe, I would like to add that there are a few questions with the same subject/title on SO, but this one is a little different, coz most/all of them involve SSL and my question doesn't.
www.mysite.com is my website and it was built using wordpress cms. I am supposed to be building a user management feature (I guess wordpress provides this by default/would need a few plugins) on my website. When a user logs on into www.mysite.com, I am supposed to authenticate this user against www.thirdpartysite.com. This is a little similar to say OpenID in a way, but only that www.thirdpartysite.com does not offer/support any other authentication scheme other than web-based authentication.
So, am I pretty much stuck here with this problem? What would be the best way to proceed here? Do I go tell www.thirdpartysite.com that they would need to expose an API for authentication? Or can I use AJAX here and have a piece of code do authentication in the background to www.thirdpartysite.com - I am not sure if it is possible.
A: I wouldn't use AJAX here, I would use cURL.
Do a test on www.thirdpartysite.com with valid and invalid credentials to find a way to programatically determine if the login was successful or not. You might find the status codes are different, or that the page is redirected when login succeeds.
Once you have a way to determine successful and unsuccessful logins, create a login form on www.mysite.com. When a user tries to login, in the php code on www.mysite.com handling the post, send a corresponding post to www.thirdpartysite.com (e.g., using cURL). If the login to www.thirdpartysite.com succeeds then treat the user as authenticated, create the session and cookies, etc. If the login to www.thirdpartysite.com fails, then display an error back to the user.
There are security considerations that come into play with this approach as www.mysite.com will have access to the www.thirdpartysite.com username and password for users that login to www.mysite.com. This is something they may or may not trust you with.
A: The best thing you could do is to create an ajax request which pass SESSID to authenticate on all your sites. It is possible, if you're using, for example JSONP
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MYSQL Subctract Days and Seconds Greeting all
I update my field 'createdOn' datetime field to hold values of last 7 days in random like this:
UPDATE posts
SET createdOn
= DATE_SUB(DATE(NOW()), INTERVAL ROUND(RAND()*7) DAY)
Although this gives me the random dates I need, the hours, minutes and seconds are not random and are like 00:00:00. How can I include random hours, minutes and seconds also in the above? Unique hours, minutes and seconds in the last seven days would be even better.
Thanking you
A: Here it is an example of random hours, minites and seconds in the last seven days -
UPDATE posts
SET createdOn = DATE(NOW()) - INTERVAL FLOOR(RAND() * 604800) SECOND;
Where 604800 = 60 seconds * 60 minutes * 24 hours * 7 days.
A: You're casting NOW() as a DATE, which will strip out the time portion, and force it to 00:00:00. Perhaps do another RAND() on TIME(NOW()) and adding them together.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I fill an S-record with two byte values starting on even address boundaries? When I compile my code I eventually get Motorola S records (a.mot) with gaps (the whole address range is not covered by code and data).
I want to fill those gaps with the pattern 0x01 0x80. However, it is important that all of the two-byte pairs must start at even addresses. 0x0180 is an opcode from my micro that I want to be executed if the PC reaches an address of unused flash area.
Before you start answering I'd like to tell you that -repeat-data in srec_cat has an issue:
*
*Given two sections e.g. C and D put one after another (D after C) in address space.
*Given that last byte of section C ends on address 0x76 and first byte of section D is on address 0x78. In other words there is 1 byte long gap at address 0x77 between them.
Under such conditions, if I use -repeat-data 0x01 0x80 option, srec cat will fill that one byte with 0x01 and start filling following gap from 0x80.
I do not know sizes of those sections because linker handles it.
A: Use srec_cat to create a file covering your required address range filled entirely with the 0x01 0x80 sequence aligned as required.
Then use srec_cat with the -multiple and −disable-sequence-warning options to "merge" the "filler" file with your application image file. You should specify the filler file as the first file so that it is overwritten by the application data specified second.
It will issue many warnings, but it should work.
A: I would write a simple parser in Windows working like this:
*
*The program creates a new s-record file based on the one you got from the compiler.
*Loop through the generated file and read two s-record lines at a time.
*If the line is an information line, S0, S9, S5 etc, just write it to the new file.
*If line 1 has an address + size smaller than the address on line 2, you have found a gap. (address1 + size1) < address2.
*Write line 1 to the new file.
*If you found a gap, write a line with your gap constants S1xx01800180 and so on. Calculate the checksum as you go.
*Write line 2 to the new file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to parse RSS with GB2312 encoding in Python I have a RSS feed shich is encoded in GB2312
When I am trying to parse it using following code:
for item in XML.ElementFromURL(feed).xpath('//item'):
title = item.find('title').text
It is not able to parse the Feed.
Any Idea how to parse GB2312 encoded RSS feed
The error Log from Plex Media Server is below after using encoding as below
for item in XML.ElementFromURL(feed, encoding='gb2312').xpath('//item'):
title = item.find('title').text
:
***Error Log:***
> File "C:\Documents and Settings\subhendu.swain\Local Settings\Application Data\Plex Media Server\Plug-ins\Zaobao.bundle\Contents\Code\__init__.py", line 24, in GetDetails
for item in XML.ElementFromURL(feed, encoding='gb2312').xpath('//item'):
File "C:\Documents and Settings\subhendu.swain\Local Settings\Application Data\Plex Media Server\Plug-ins\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\api\parsekit.py", line 81, in ElementFromURL
return self.ElementFromString(self._core.networking.http_request(url, values, headers, cacheTime, autoUpdate, encoding, errors, immediate=True, sleep=sleep, opener=self._opener, txn_id=self._txn_id).content, isHTML=isHTML)
File "C:\Documents and Settings\subhendu.swain\Local Settings\Application Data\Plex Media Server\Plug-ins\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\api\parsekit.py", line 76, in ElementFromString
return self._core.data.xml.from_string(string, isHTML)
File "C:\Documents and Settings\subhendu.swain\Local Settings\Application Data\Plex Media Server\Plug-ins\Framework.bundle\Contents\Resources\Versions\2\Python\Framework\components\data.py", line 134, in from_string
return etree.fromstring(markup)
File "lxml.etree.pyx", line 2532, in lxml.etree.fromstring (src/lxml/lxml.etree.c:48270)
File "parser.pxi", line 1545, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:71812)
File "parser.pxi", line 1424, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:70673)
File "parser.pxi", line 938, in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:67442)
File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:63824)
File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:64745)
File "parser.pxi", line 565, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:64088)
XMLSyntaxError: switching encoding: encoder error, line 1, column 36
2011-09-28 09:34:33,453 (9d0) : DEBUG (core) - Response: 404
A: Your error message is XMLSyntaxError: switching encoding: encoder error, line 1, column 36. You asked for ideas. Here's a novel idea: Tell us what is in the first 50 or so bytes of "line 1". Then somebody may be able to come up with a remedy.
Update: The encoding declaration is incorrect. The data is NOT encoded in gb2312. It's at least GBK aka cp936. GB2312-80 (that's 80 as in the year 1980) is a limited character set. Chinese websites that are not using UTF-8 would be using at least the superset GBK (been in use for well over 10 years) and moving to the supersuperset GB18030 (which is itself a UTF). See below:
[Python 2.7.1]
>>> import urllib
>>> url = "http://www.zaobao.com/sp/sp.xml"
>>> data = urllib.urlopen(url).read()
>>> len(data)
10071
>>> data[:100]
'<?xml version="1.0" encoding="GB2312"?>\n\n<rss version="2.0"\n>\n\n<channel>\n<title>\xc1\xaa\xba\xcf\xd4\xe7\xb1\xa8\xcd\xf8 zaobao.co'
>>> x = data.decode('gb2312')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 1771-1772: illegal multibyte sequence
>>> data[1771:1773]
'\x95N'
>>> x = data.decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc1 in position 80: invalid start byte
>>> x = data.decode('gbk')
>>> y = data.decode('cp936')
>>> x == y
True
I suggest that you try XML.ElementFromURL(feed, encoding='gbk').
If that works, you may wish to bullet-proof your code against this not-uncommon problem by reading the data with urllib, checking for gb2312 and if you find it, use gb18030 instead.
Update 2: In case anyone mentions chardet: due to GBK using the many unused slots in GB2312, and chardet not working on actually-used slots, and not attempting to verify its answer by doing a trial decode, charget guesses GB2312.
A: I assume you are using the Plex XML API. The documentation states that you can call XML.ElementFromURL(feed, encoding='gb2312') if you know that this is really the encoding being used.
If the XML really is encoded with GB2312, then the declaration must be <?xml version="1.0" encoding="gb2312"?> (or begin with a byte order mark, for UTF-16), otherwise the XML is invalid. If there is no encoding in the XML declaration, and no byte order mark, parsers must assume UTF-8 encoding by default, and therefore it is invalid to use any other character encoding for XML without an encoding in the declaration. Since not specifying the encoding produces an error for you, I think it is possible that the RSS feed is not valid XML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a table using insert so columns are nullable? Using SQL Server 2008.
Here is a simplified example of my problem:
WITH cte ( a )
AS ( SELECT 1
UNION ALL
SELECT NULL
)
SELECT * INTO a_tmp FROM cte
SELECT * FROM a_tmp
This creates the table called a_tmp with a nullable int column.
The next snippet, however creates the table with a non-nullable column:
WITH cte ( a )
AS ( SELECT 1
UNION ALL
SELECT 2
)
SELECT * INTO a_tmp FROM cte
How can I change the second snippet to force the table to be created with all its columns nullable?
A: Make it into a computed expression as generally these get treated as NULL-able unless wrapped in ISNULL()
WITH cte ( a )
AS ( SELECT CAST(1 AS INT)
UNION ALL
SELECT 2
)
SELECT * INTO a_tmp FROM cte
A: If you want to explicitly define a field as nullable in a table, the right way is to use CREATE TABLE.
As a workaround you can explicitly cast all your fields as their data types, but to me that seems like MORE work than just
CREATE TABLE MyTable (id INT NULL, Otherfield varchar(100)...)
A: When you use SELECT ... INTO, any expression that uses a built-in function (e.g. CAST) is considered as NULL-able by the engine.
So if you use CAST(somecol as int) then the expression is NULLable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Launch Settings->Sounds Launch Settings->Sounds
I need to launch the view of Sounds Settings in iPhone device..
Just like we get the Mail composer and Contact View using API's , can we get the Sounds Settings view?
Thanks in advance of any suggestion and help.
A: Apple like to use a standard methods for certain operation. For example changing to silent mode or adjusting the volume. Also I wouldn't want an app changing the volume if I lowered the volume.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best Utility Class Implementation I have read several questions regarding when to use a utility class or any class that doesn't have a state associated with it.
My question is what is the best implementation once you have decided to use a utility class? A static class, a normal class with private constructor and only static methods (similar to java's math class), or an alternative?
I understand that this will probably depend on my specific situation but I do not have one and was looking for more general guidelines or advantages and disadvantages to each implementation method.
A: What is the best implementation once you have decided to use a utility class?
Exactly what you proposed. Create a private constructor, make the class final and implement static utility methods. In such cases, there's no need to make things more complex.
Of course, you must be careful to not falling back into imperative/procedural programming style... just one opinion.
A: IMHO:
For Utilty Classes for little everyday Problems like Converting Stuff etc is a static class with no constructor the best implementation. Very Handy to access:
Utils.ConvertDateToCake();
My Utility Classes which need an Constructor are implemented as Singletons. So you can access them like this:
DatabaseUtils.getInstance().DoSomething();
A: Utility classes are pure evil in OOP. Check this blog post for better explanation: http://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html
In a nutshell, utility classes bring procedural programming into OOP, making your code less testable, less maintainable/readable, and slower (!).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android/Java: Import text file and read out random lines from within the text file I got this code I've been working on so far, it is going to be a game im trying to create which just switches between two players. Every time it switches it is supposed to write out a question, like truth or dare. It is not allowed to write the same question twice, and should therefore be able to see if it has already used that question.
So far I've got it running, and it switches between the two players every time you hit Next.
But what I have a lot of trouble with, is fetching the data from within the txt file called man, here there is three lines, text1 text2 and text3. It should be able to take these randomly and know if it has already read one. I can not get the current InputStream to work, it says the man file is int, but it contains string?
Here is the code so far:
package truthordare;
import java.io.FileInputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
//import android.content.Intent;
public class truthordareActivity extends Activity
{
public int i = 0;
//public String man;
//public String woman;
TextView w;
TextView m;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
final Button buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
gameCode();
}
});
}
}
/*public FileInputStream openFileInput(int man) throws IOException
{
String collected = null;
try
{
FileInputStream fis = openFileInput(R.raw.man);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1)
{
collected = new String(dataArray);
}
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
*/
public void gameCode()
{
// Perform action on click
setContentView(R.layout.game);
if(i == 0)
{
w = (TextView)findViewById(R.id.textView1);
w.setText("This is a player1");
i = 1;
final Button buttonNext = (Button) findViewById(R.id.buttonNext);
buttonNext.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
gameCode();
}
});
}
else
{
m = (TextView)findViewById(R.id.textView1);
m.setText("This is player2");
i = 0;
final Button buttonNext = (Button) findViewById(R.id.buttonNext);
buttonNext.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
gameCode();
}
});
}
}
}
A: Grab an InputStream using Resources.openRawResource. In your case this is getResources().openRawResource(R.raw.man).
A: Have you considered using an XML-file for your questions? From the information you provided, the structure should be like this:
<questions>
<question>
<id>1</id>
<text>This is question nr. 1</text>
</question>
<question>
<id>2</id>
<text>This is question nr. 2</text>
</question>
<question>
<id>3</id>
<text>This is question nr. 3</text>
</question>
</questions>
Load all the questions into a List/ArrayList as Question-objects and when a question is asked - remove it from the list. If you need to save the questions for later, don't remove them but rather save the ID's of all asked questions in another list, and when you try to get the next question make sure its ID is not in the list of ID's.
To get a random question you just use a random number generator that provides you with values between 0 and list.size().
This way you won't have to spend time opening and closing InputStreams all the time and you have an easy way of making sure that a question is only asked once.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MYSQL: Query to update an incremental value and store the returning value I have a query to substract a value stored on the DB.
UPDATE tablename SET
available = IF( available > 0, available - " . $var . ", 0 ) ,
purchases = purchases + 1
WHERE condition
Is posible to get the new value of field available without make a new SELECT and then penalize the performance?
A: You could use a mysql user-defined function:
CREATE FUNCTION registerPurchase(idParam INT, qty INT)
RETURNS INT
BEGIN
DECLARE avail INT, purc INT,
SELECT available, purchases INTO avail, purc FROM tablename WHERE id = idParam;
SET avail = IF( avail > 0, avail - qty, 0 );
SET purc = purc - 1;
UPDATE tablename SET
available = avail,
purchases = purc
WHERE id = idParam;
RETURN avail;
END
Or something like that. You can call this using SELECT registerPurchase(1234, 2);, for example. This could be combined with @Johan's solution for even greater justice.
EDIT:
Here's a link: http://dev.mysql.com/doc/refman/5.6/en/create-procedure.html.
A: I haven't tested this code, but I'm 87,587% sure it works.
An update statement does not return a resultset, however you can set a @var variable and select from that.
UPDATE tablename
SET
available = @fastpeek:= IF( available > 0, available - " . $var . ", 0 )
,purchases = purchases + 1
WHERE condition
LIMIT 1;
SELECT @fastpeek as available_in_update;
This will break if you update more than 1 row however: when updating more than 1 row, @fastpeek will only show the last update. Hence the limit 1.
You still need an extra select, but it will not need to query the database, it will just retrieve the @var from memory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting the class name from within the initialize method when class inherited from Hash I have a class that inherits from Hash. When this class itself gets inherited from, I want to know the class name of the inheriting class from within the initialize method. When I call self I get {}, which doesn't know of the name method.
class Foo < Hash
def initialize
# Here i want to know that the class is Foo
end
end
How do I get the class name?
A: It’s very simple: self.class.name
A: Daniel Brockman's answer will return you the string if you want to do a check:
if self.kind_of?(Foo)
#whatever you want
end
The thing is due to the intent of the initializer, when you call Foo.new the instance will always be an instance of the class Foo or child, so I'm confused about what you're trying to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rete Tree view not being displayed using drools plugin for Eclipse I have been trying to display the Rete Tree view for drools files using the drools plugin for eclipse. But it is failing for me with the following error :
I am using Eclipse Indigos, Drools 5.3 and JDK 1.7 .
I googled around a bit to solve this issue but none of the suggestions worked. Any help would be highly appreciated ?
On a parallel note is their any other way to validate the drools rules other than generating the Rete Tree view ? I want to find any syntactical mistakes as early as possible rather than invoking the validations and finding the drl mistakes at runtime.
org.drools.RuntimeDroolsException: Unable to load dialect 'org.drools.rule.builder.dialect.java.JavaDialectConfiguration:java:org.drools.rule.builder.dialect.java.JavaDialectConfiguration'
at org.drools.compiler.PackageBuilderConfiguration.addDialect(PackageBuilderConfiguration.java:277)
at org.drools.compiler.PackageBuilderConfiguration.buildDialectConfigurationMap(PackageBuilderConfiguration.java:262)
at org.drools.compiler.PackageBuilderConfiguration.init(PackageBuilderConfiguration.java:175)
at org.drools.compiler.PackageBuilderConfiguration.<init>(PackageBuilderConfiguration.java:153)
at org.drools.eclipse.DroolsEclipsePlugin.generateParsedResource(DroolsEclipsePlugin.java:393)
at org.drools.eclipse.DroolsEclipsePlugin.generateParsedResource(DroolsEclipsePlugin.java:360)
at org.drools.eclipse.DroolsEclipsePlugin.parseResource(DroolsEclipsePlugin.java:273)
at org.drools.eclipse.editors.DroolsLineBreakpointAdapter.canToggleLineBreakpoints(DroolsLineBreakpointAdapter.java:44)
at org.eclipse.debug.ui.actions.ToggleBreakpointAction.update(ToggleBreakpointAction.java:187)
at org.eclipse.ui.texteditor.AbstractRulerActionDelegate.update(AbstractRulerActionDelegate.java:132)
at org.eclipse.ui.texteditor.AbstractRulerActionDelegate.setActiveEditor(AbstractRulerActionDelegate.java:89)
at org.eclipse.debug.ui.actions.RulerToggleBreakpointActionDelegate.setActiveEditor(RulerToggleBreakpointActionDelegate.java:98)
at org.eclipse.ui.internal.EditorPluginAction.editorChanged(EditorPluginAction.java:75)
at org.eclipse.ui.internal.EditorActionBuilder$EditorContribution.editorChanged(EditorActionBuilder.java:83)
at org.eclipse.ui.internal.EditorActionBuilder$ExternalContributor.setActiveEditor(EditorActionBuilder.java:129)
at org.eclipse.ui.internal.EditorActionBars.partChanged(EditorActionBars.java:346)
at org.eclipse.ui.internal.WorkbenchPage$3.run(WorkbenchPage.java:709)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.runtime.Platform.run(Platform.java:888)
at org.eclipse.ui.internal.WorkbenchPage.activatePart(WorkbenchPage.java:698)
at org.eclipse.ui.internal.WorkbenchPage.setActivePart(WorkbenchPage.java:3632)
at org.eclipse.ui.internal.WorkbenchPage.requestActivation(WorkbenchPage.java:3159)
at org.eclipse.ui.internal.PartPane.requestActivation(PartPane.java:279)
at org.eclipse.ui.internal.EditorPane.requestActivation(EditorPane.java:98)
at org.eclipse.ui.internal.PartPane.setFocus(PartPane.java:325)
at org.eclipse.ui.internal.EditorPane.setFocus(EditorPane.java:127)
at org.eclipse.ui.internal.PartStack.presentationSelectionChanged(PartStack.java:837)
at org.eclipse.ui.internal.PartStack.access$1(PartStack.java:823)
at org.eclipse.ui.internal.PartStack$1.selectPart(PartStack.java:137)
at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation$1.handleEvent(TabbedStackPresentation.java:133)
at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:269)
at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:278)
at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder.access$1(DefaultTabFolder.java:1)
at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder$2.handleEvent(DefaultTabFolder.java:88)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1077)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1062)
at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:774)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CUDA warp vote functions make the code slower? I have written a CUDA function that calculates a convex envelop in a set of points in 2D. But it is extremely slower than the CPU code!
I am using warp vote functions and __syncronisation(); quite number of times. So does that make the code slower ?
Thanks
Adding the code :
__global__ void find_edges_on_device(TYPE * h_x, TYPE * h_y, int *h_edges){
int tidX = threadIdx.x;
int tidY = threadIdx.y;
int tid = tidY*blockSizeX + tidX;
int i = threadIdx.x+blockIdx.x*blockDim.x;
int j = threadIdx.y+blockIdx.y*blockDim.y;
int hxi = h_x[i];
int hxj = h_x[j];
int hyi = h_y[i];
int hyj = h_y[j];
long scalarProduct = 0;
TYPE nx;
TYPE ny;
bool isValid = true;
__shared__ int shared_X[blockSizeX*blockSizeY];
__shared__ int shared_Y[blockSizeX*blockSizeY];
__shared__ bool iswarpvalid[32];
__shared__ bool isBlockValid;
if (tid==0)
{
isBlockValid=true;
}
if (tid<(blockSizeX*blockSizeY-1)/32+1)
{
iswarpvalid[tid]=true;
}
else if (tid<32)
{
iswarpvalid[tid]=false;
}
//all the others points should be on the same side of the edge i,j
//normal to the edge (unnormalized)
nx = - ( hyj- hyi);
ny = hxj- hxi;
int k=0;
while ((k==i)||(k==j))
{
k++;
} //k will be 0,1,or 2, but different from i and j to avoid
scalarProduct=nx* (h_x[k]-hxi)+ny* (h_y[k]-hyi);
if (scalarProduct<0)
{
nx*=-1;
ny*=-1;
}
for(int count = 0; count < ((NPOINTS/blockSizeX*blockSizeY) + 1); count++ ){
int globalIndex = tidY*blockSizeX + tidX + count*blockSizeX*blockSizeY;
if (NPOINTS <= globalIndex){
shared_X[tidY*blockSizeX + tidX] = -1;
shared_Y[tidY*blockSizeX + tidX] = -1;
}
else {
shared_X[tidY*blockSizeX + tidX]= h_x[globalIndex];
shared_Y[tidY*blockSizeX + tidX]= h_y[globalIndex];
}
__syncthreads();
//we have now at least one point with scalarProduct>0
//all the other points should comply with the same condition for
//the edge to be valid
//loop on all the points
if(i < j){
for (int k=0; k < blockSizeX*blockSizeY; k++)
{
if((count * blockSizeX*blockSizeY + k < NPOINTS )&&(isValid)) {
scalarProduct=nx* (shared_X[k]-hxi)+ny* (shared_Y[k]-hyi);
if(__all(scalarProduct) < 0){
iswarpvalid[(tidY*blockSizeX + tidX)/32] = false;
break;
}
else if(0 > (scalarProduct) ){
isValid = false;
break;
}
}
}
}
__syncthreads();
if (tid<32)
{
isBlockValid=__any(iswarpvalid[tid]);
}
__syncthreads();
if(!isBlockValid) break;
}
if ((i<j) && (true == isValid )){
int tmp_i = i;
int tmp_j = j;
if( -1 != atomicCAS(&h_edges[2*i], -1, tmp_j) )
h_edges[2*i+1]=j;
if( -1 != atomicCAS(&h_edges[2*j], -1, tmp_i) )
h_edges[2*j+1]=i;
}
}
A: The answers you're looking for can be found in the NVIDIA CUDA C Programming Guide.
Section 5.4.3 states that:
Throughput for __syncthreads() is 8 operations per clock cycle for
devices of compute capability 1.x and 16 operations per clock cycle
for devices of compute capability 2.x.
Warp vote functions are tackled in Section B.12 and in Table 109 of the PTX ISA manual. The latter indicates that two instructions are required to perform a warp vote. However, I couldn't figure out any clock cycle figure for warp vote functions in the reference documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Figure out which row in an HTML table was clicked
Possible Duplicate:
How to detect which row [ tr ] is clicked?
I have a table like this:
<table>
<tr>
<td>1</td><td>1</td><td>1</td>
</tr>
<tr>
<td>2</td><td>2</td><td>2</td>
</tr>
<tr>
<td>3</td><td>3</td><td>3</td>
</tr>
</table>
In JavaScript (no jQuery please) how do I work out if a user clicks on the table on which row he/she clicked?
A: event.target, getElementsByTagName, traditional event method:
var trs = document.getElementsByTagName('tr');
for (var i = 0; i < trs.length; i++) {
trs[i].onclick = clickHandler;
}
function clickHandler(event) {
alert(this.innerText || this.textContent); // edit: textContent for firefox support
}
jsFiddle
A: If you attach a click event handler to the table, you can get the event target, which will contain the element that was actually clicked:
document.getElementById("yourTable").onclick = function(e) {
console.log(e.target);
}
In your example, that's likely to be a td, so you could access the tr like this:
var tr = e.target.parentNode;
You can check the type of element that has been clicked with the tagName property:
var clickedElementType = e.target.tagName; //Returns something like "TD"
Alternatively, you could iterate over all the tr elements in your table and bind a click event handler to each.
A: function handleEvent(e) {
// Do stuff with the row
}
var rows = document.getElementsByTagName('tr');
for (var row in rows) {
row.addEventListener('click', handleEvent);
// or attachEvent, depends on browser
}
A: window.onload = function(){
var table = document.getElementById('myTableID');
table.addEventListener('click',test,false);
}
function test(e){
var element = e.srcElement || e.target;
if(element.nodeName == 'TABLE') return;
while(element.nodeName != 'TR') element = element.parentNode;
alert(element.rowIndex);
}
A: I prefer to attach an event to the DOM element vs setting onclick. You'll have to do some checking if you want it to work with IE:
var trs = document.getElementsByTagName('tr');
var len = trs.length
var clickHandler = function(i){
alert('clicked');
};
for(var i = 0; i < len; i++){
var theRow = trs[i];
if(theRow.addEventListener){
theRow.addEventListener('click',clickHandler);
}
else{
theRow.attachEvent('onclick',clickHandler);
}
}
A: Add an id to each row and then you can query the node id from the Javascript onclick() handler
A: How about putting an onClick on the <tr>?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: xlabel and ylabel for facet I'm doing like this:
ggplot(IDPlotLn, aes(x=CO3, y=CRf)) +
xlab(xlabel) +
ylab(ylabel) +
opts(
axis.text.x = theme_text(size=10, face="plain", colour="black",vjust=1),
axis.text.y = theme_text(size=10, face="plain", colour="black", hjust=1)) +
scale_y_continuous(limits = c(-1.3 , 1.3), expand = c(0,0)) +
opts(panel.margin=unit(1, "cm")) +
geom_point() +
geom_smooth(method="lm",se=F) +
facet_wrap(~ ID, nrow=7, ncol=3, scales = "free") +
opts(strip.text.x = theme_text(size = 8))
I want to plot Xlabel and ylabel for each one of my facet, the same xlabel and ylabel. Like this I have only one xlabel and ylabel for all of the facet.
Is it possible?
Thank you for yours answer, I didn't know gridExtra.
But in this example, I'm faceting and I just want to make it more beautiful, it is the same xlabel and ylabel that I want to add for each panel.
Because after for I want to choose several panels from all my panels, so it can be nice if I have already x and y label.
A: If you are trying to use different labels for the x and y axes when faceting then the correct answer is that you probably shouldn't be using facets. The entire point of faceting is that each panel shares the same x and y axis. So if you're labeling them differently, chances are you're misusing faceting.
What you probably want instead is to simply plot each panel separately and then arrange them in a grid. This can be easily done in ggplot2 with the help of the gridExtra package:
dat <- data.frame(x = rep(1:5,3),
y = rnorm(15),
z = rep(letters[1:3],each = 5))
dat <- split(dat,dat$z)
p1 <- ggplot(dat[[1]],aes(x=x,y=y)) +
geom_point() +
labs(x = 'xlabel1',y='ylabel1')
p2 <- ggplot(dat[[2]],aes(x=x,y=y)) +
geom_point() +
labs(x = 'xlabel2',y='ylabel2')
p3 <- ggplot(dat[[3]],aes(x=x,y=y)) +
geom_point() +
labs(x = 'xlabel3',y='ylabel3')
library(gridExtra)
grid.arrange(p1,p2,p3)]
See ?grid.arrange for more examples.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Copy file from shared directory with given user name and password Is there a way to create/copy a file to/from specific network shared directory with different than current user name and password ?
A: Either what @Luke suggested in a comment, or you can PInvoke to NetUseAdd function. You can pass user name and password in a call to NetUseAdd and then all attempts from current user session to access resources on this file share will use those credentials. See example on pinvoke.net on how to call it -- you will have to translate this to Delphi.
A: Alternately you could use the Windows API CreateProcessWithLogon() (Link to MSDN).
A: Here's what I use to connect and map a remote drive to a local drive letter (along with the corresponding unmapping operation). Once you've mapped the drive to a drive letter, you copy just like you would with any other drive:
function MapNetworkDrive(const RemoteName, LocalDrive,
UserName, Password: string): Boolean;
var
NetRes: TNetResource;
Res: DWord;
begin
Result := True;
FillChar(NetRes, SizeOf(TNetResource), 0);
NetRes.dwType := RESOURCETYPE_DISK;
NetRes.lpRemoteName := PChar(RemoteName);
NetRes.lpLocalName := PChar(LocalDrive);
Res := WNetAddConnection2(NetRes, PChar(Password), PChar(UserName), 0);
Result := (Res = NO_ERROR);
if not Result then
SysErrorMessage(Res);
end;
function TForm1.UnmapNetworkDrive(const LocalDrive: string): Boolean;
var
Res: DWord;
begin
Res := WNetCancelConnection2(PChar(LocalDrive), 0, True);
Result := (Res = NO_ERROR);
end;
Example use:
begin
if MapNetworkDrive('\\192.168.1.56\C$', 'H:', 'fred', 'password') then
begin
try
// Do whatever between local drive and drive 'H:'
finally
UnmapNetworkDrive(Local);
end;
end;
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the difference between Lazy.Force() and Lazy.Value On the MSDN documentation for Lazy.Force<T> extension method says:
Forces the execution of this value and returns its result. Same as
Value. Mutual exclusion is used to prevent other threads from also
computing the value.
Does it mean that it's equivalent to creating a Lazy<T> instance with ExecutionAndPublication LazyThreadSafetyMode so that only one thread can initialize the instance?
Thanks
A: Yes. They are both the same, and both make sure that the value will be computed only once.
A: It's a bit strange that the method exists and is not a function - it's not composable and replicates the behavior of .Value.
I would define something like the following (as seen in the F# compiler):
module Lazy =
// Lazy.force : Lazy<'T> -> 'T
let force (x: Lazy<'T>) = x.Force()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Open Atrium - Default Front Page In OA I'm trying to set the default page to a group i.e. I've selected then put in a group name for example 'intranet' but this says that the page does not exist...
Does anybody know how I can default the front page to a specific group when users log in?
A: You need your group's nid/gid...Go to your group's page and click the 'edit' tab, you should see something like "node/123/edit" or "group/123/edit". The number in the middle is your node ID or group ID. if the path starts with 'node' your front page will be "node/node_id", if it's group your front page will be "group/group_id".
Hope that makes sense
A: A bit late replication but hope it will help someone else.
You can use function hook_user() with $op 'login'.
yourmoudlename_user($op, &$edit, &$account) {
if ($op == 'login') {
$groups = $account->og_groups;
// redirect to the first group of user
if ($groups) {
$groups = array_values($groups);
$group_node = node_load($groups[0]['nid']);
$_REQUEST['destination'] = $group_node->purl;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pass header information to the soap header SOAP_ENV__Header, in c++ using gsoap I am working on calling the webservices using the gsoap packages in c++ and get the responses.
I have to pass some header information as well, which I am not sure how to do that, as my header is like this -
/* SOAP Header: */
struct SOAP_ENV__Header
{
public:
void *dummy; /* transient */
};
Is there something I missed, or it is supposed to be like this only and we have to make changes here?
I have read here some info, but my header is just dummy.
Secondly, for further debugging, I wanted to enable DEBUGS and for that, as per the user-guide, I have uncommented the DEBUG macros in the stdsoap2.h and built with the DEBUG flag again but, I couldn't get the .log files getting created. Any idea?
Deepak
A: You can do something like
soap_init(&mysoap);
mysoap.header = (SOAP_ENV__Header *)soap_malloc(&mysoap, sizeof(SOAP_ENV__Header));
mysoap.header->ns3__MyHeader = (ns3__Header*)malloc(sizeof(ns3__Header));
mysoap.header->ns3__MyHeader->Value = (char*)malloc(10 * sizeof(char));
strcpy(mysoap.header->ns3__MyHeader->Value, str);
A: For rest calls this works -
#include "json.h"
#include <string.h>
#include "jsonStub.h"
struct Namespace namespaces[] = { {NULL, NULL} };
int main()
{
struct soap *ctx = soap_new1(SOAP_XML_NOTYPE);
soap_init(ctx);
struct value *request = new_value(ctx);
struct value response;
ctx->sendfd = 1;
ctx->http_extra_header = "userName:abcd\r\npassword:xyz";
*string_of(value_at(value_at(request, "add"), "i")) = "10";
*string_of(value_at(value_at(request, "add"), "j")) = "20";
json_write(ctx, request);
printf("\n");
if (json_call(ctx, "endpoint",request, &response))
{
printf( "json call failed " );
soap_print_fault(ctx, stderr);
printf("\n%d", ctx->error);
printf("\n1: SOAP faultcode = %s\n", *soap_faultcode(ctx));
printf("2: SOAP faultstring = %s\n", *soap_faultstring(ctx));
printf("3: SOAP faultdetail = %s\n\n", *soap_faultdetail(ctx));
soap_print_fault_location(ctx, stderr);
}
else
{
printf("Success !!!");
json_write(ctx, &response);
}
soap_destroy(ctx);
soap_end(ctx);
soap_free(ctx);
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Scrollbars - transparent and invisible until movement for scrollable divs I utterly hate the inconsistency of scrollbars across browsers. After recently seeing OSX lion in action with its transparent until movement scrollbars I wonder if we can recreate this cross browser.
I looked at a few JQuery plugins. The closest was called tiny scrollbars which was close and after fiddling with the PNG images, nearly close enough, but it was limited in that I could not work out how to show it only while the div is being scrolled and then gently fade it out again. Also if possible I would enjoy a bit of momentum and even elasticity.
Is there a way of doing this?
A: You can set overflow and toggle accordingly
Something like this might work:
Start with this in your css
body {
overflow: hidden;
}
Then
$(function(){
$(document).mousemove(function(e){
$("body").css("overflow", "auto")
});
});
Note you might have to specify width and heights to avoid inadvertent clipping when the page renders.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: trouble reading a 2D array of characters in C? This is the code:
#include <stdio.h>
#include <stdlib.h>
void acceptMaze(char maze[ROW][COLOUMN], int nrows, int ncols)
{
int i,j;
for (i = 0; i < nrows; i++)
{
fprintf(stdout,"I = %d",i);
for (j = 0; j < ncols; j++)
{
fprintf(stdout,"J = %d",j);
scanf("%c",&maze[i][j]);
}
}
}
wel while entering data it saysi =0 j=0j=1 .So you see the j=0 doesn't remains.I am using a linux system .Can anyone fix this.
A: Your problem stems from the fact that the %c conversion specifier doesn't skip whitespace. If there's a newline stuck in the input stream from a previous input operation, the scanf call will read that and assign it to maze[i][j].
Here's one workaround:
#include <ctype.h>
...
for (i = 0; i < nrows; i++)
{
for (j = 0; i < nrows; j++)
{
int c;
do c = getchar(); while (isspace(c));
maze[i][j] = c;
}
}
The line do c = getchar(); while (isspace(c)) will read input characters until you hit a non-whitespace character.
EDIT
Ugh, I just realized one ugly flaw of this scheme; if you want to a assign a whitespace character like a blank to your maze, this won't work as written. Of course, you can just add to the condition expression:
do c = getchar(); while (isspace(c) && c != ' ');
A: You need to output some newlines to make it easier for the user to read. How about:
#include <stdio.h>
#include <stdlib.h>
void acceptMaze(char maze[][],int nrows,int ncols)
{
int i,j;
for(i=0;i<nrows;i++)
{
for(j=0;j<ncols;j++)
{
printf("\nenter %d,%d: ",i, j);
scanf("%c",&maze[i][j]);
}
}
}
A: The enter key is being accepted as input for half of your queries. Say you prompt for i = 0, j = 0, and the user enters '5' followed by the enter key. Scanf inserts '5' into maze[0][0], and in the next iteration of the loop, it sees that the enter key is still in the buffer, so it inserts that into maze[0][1].
You need to flush the input after every scanf. One solution is to #include <iostream> and call std::cin.ignore() after each scanf.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JAVA the smartest embedded persistance solution I'm developing GWT application, so I have JAVA server with next to nothing configuration. And I'm in need of persisting my DomainObjects.
It's a tree with root Class containing String id, List<ClassB>, ClassC, List<ClassD>
CLassB,C,D contains only String and primitives.
I need to be able to search by String id of root class and retrieve whole tree.
I need to be able to update as well.
Whta is teh simpliest/smartest solution?
(I know how to do that with Spring,Hibernate and HSQLDB - but that seems like an overkill)
I want it to be as much portable as possible so embedded solution is the one I seek.
A: We use ORMLite http://ormlite.com/ for our handheld data-entry devices. It is very lightweight and simple to set up and use, and follows the same annotation-based configuration model as hibernate.
One thing to note is that although Hibernate may be overkill, there are many things it makes nice and simple. ORMLite is more suited where you want a lightweight implementation or more control over the output database, whereas a tool like Hibernate makes development a bit easier.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rewrite rule not trying to redirect I have this 301 redirect rule for Apache:
RewriteEngine On
RewriteRule ^park.php?park_id=3 http://hiking.comehike.com/outdoors/parks/park.php?park_id=3 [R=301,L]
I am trying to get this url:
http://www.comehike.com/outdoors/parks/park.php?park_id=3
to redirect to this url:
http://hiking.comehike.com/outdoors/parks/park.php?park_id=3
But as I have it now, it isn't trying to redirect. The .htaccess file with the rule is located in the /parks/ directory.
Is there anything I am doing wrong? Seems like this should be relatively straight forward.
Thanks!
A: It's the query string; you need to add a conditional to be able to pick up on it, something like:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^park_id=3$
RewriteRule ^park.php http://hiking.comehike.com/outdoors/parks/park.php?park_id=3 [R=301,L]
That works when I mung it into an .htaccess on my localhost anyway.
It might be better to eventually, since it's RegExp pattern matching to do something like:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^park_id=([0-9]+)$
RewriteRule ^park.php http://hiking.comehike.com/outdoors/parks/park.php?park_id=%1 [R=301,L]
Which will pick up the integer at the end of the address and pass it to the new address (it's actually easier if you don't have a query string in the original address of course).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reverse a string in Java I have "Hello World" kept in a String variable named hi.
I need to print it, but reversed.
How can I do this? I understand there is some kind of a function already built-in into Java that does that.
Related: Reverse each individual word of “Hello World” string with Java
A: public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
A: String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
A: It is very simple in minimum code of lines
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
A: This did the trick for me
public static void main(String[] args) {
String text = "abcdefghijklmnopqrstuvwxyz";
for (int i = (text.length() - 1); i >= 0; i--) {
System.out.print(text.charAt(i));
}
}
A: 1. Using Character Array:
public String reverseString(String inputString) {
char[] inputStringArray = inputString.toCharArray();
String reverseString = "";
for (int i = inputStringArray.length - 1; i >= 0; i--) {
reverseString += inputStringArray[i];
}
return reverseString;
}
2. Using StringBuilder:
public String reverseString(String inputString) {
StringBuilder stringBuilder = new StringBuilder(inputString);
stringBuilder = stringBuilder.reverse();
return stringBuilder.toString();
}
OR
return new StringBuilder(inputString).reverse().toString();
A: I am doing this by using the following two ways:
Reverse string by CHARACTERS:
public static void main(String[] args) {
// Using traditional approach
String result="";
for(int i=string.length()-1; i>=0; i--) {
result = result + string.charAt(i);
}
System.out.println(result);
// Using StringBuffer class
StringBuffer buffer = new StringBuffer(string);
System.out.println(buffer.reverse());
}
Reverse string by WORDS:
public static void reverseStringByWords(String string) {
StringBuilder stringBuilder = new StringBuilder();
String[] words = string.split(" ");
for (int j = words.length-1; j >= 0; j--) {
stringBuilder.append(words[j]).append(' ');
}
System.out.println("Reverse words: " + stringBuilder);
}
A: System.out.print("Please enter your name: ");
String name = keyboard.nextLine();
String reverse = new StringBuffer(name).reverse().toString();
String rev = reverse.toLowerCase();
System.out.println(rev);
I used this method to turn names backwards and into lower case.
A: One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.
String s = "Hello My name is Sufiyan";
Put it in the stack frontwards
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
myStack.push(st.nextToken());
}
Print the stack backwards
System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
System.out.print(myStack.pop());
System.out.print(' ');
}
System.out.println('"');
A: Take a look at the Java 6 API under StringBuffer
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
A: public String reverse(String s) {
String reversedString = "";
for(int i=s.length(); i>0; i--) {
reversedString += s.charAt(i-1);
}
return reversedString;
}
A: You can also try this:
public class StringReverse {
public static void main(String[] args) {
String str = "Dogs hates cats";
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}
A: public class Test {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("Game Plan");
buffer.reverse();
System.out.println(buffer);
}
}
A: All above solution is too good but here I am making reverse string using recursive programming.
This is helpful for who is looking recursive way of doing reverse string.
public class ReversString {
public static void main(String args[]) {
char s[] = "Dhiral Pandya".toCharArray();
String r = new String(reverse(0, s));
System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
if (source.length / 2 == i) {
return source;
}
char t = source[i];
source[i] = source[source.length - 1 - i];
source[source.length - 1 - i] = t;
i++;
return reverse(i, source);
}
}
A: Procedure :
We can use split() to split the string .Then use reverse loop and add the characters.
Code snippet:
class test
{
public static void main(String args[])
{
String str = "world";
String[] split= str.split("");
String revers = "";
for (int i = split.length-1; i>=0; i--)
{
revers += split[i];
}
System.out.printf("%s", revers);
}
}
//output : dlrow
A: Here is an example using recursion:
public void reverseString() {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
if(index == 0){
return stringToReverse.charAt(0) + "";
}
char letter = stringToReverse.charAt(index);
return letter + reverse(stringToReverse, index-1);
}
A: Here is a low level solution:
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inpStr = in.nextLine();
System.out.println("Original String :" + inpStr);
char temp;
char[] arr = inpStr.toCharArray();
int len = arr.length;
for(int i=0; i<(inpStr.length())/2; i++,len--){
temp = arr[i];
arr[i] = arr[len-1];
arr[len-1] = temp;
}
System.out.println("Reverse String :" + String.valueOf(arr));
}
}
A: I tried, just for fun, by using a Stack. Here my code:
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.toString();
}
A: For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
A: Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.
The Algorithm is based on :
1.(A XOR B) XOR B = A
2.(A XOR B) XOR A = B
Code snippet:
public class ReverseUsingXOR {
public static void main(String[] args) {
String str = "prateek";
reverseUsingXOR(str.toCharArray());
}
/*Example:
* str= prateek;
* str[low]=p;
* str[high]=k;
* str[low]=p^k;
* str[high]=(p^k)^k =p;
* str[low]=(p^k)^p=k;
*
* */
public static void reverseUsingXOR(char[] str) {
int low = 0;
int high = str.length - 1;
while (low < high) {
str[low] = (char) (str[low] ^ str[high]);
str[high] = (char) (str[low] ^ str[high]);
str[low] = (char) (str[low] ^ str[high]);
low++;
high--;
}
//display reversed string
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
Output:
keetarp
A: As others have pointed out the preferred way is to use:
new StringBuilder(hi).reverse().toString()
But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.
The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.
This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).
public static String reverseString(String s) {
char[] chars = new char[s.length()];
boolean twoCharCodepoint = false;
for (int i = 0; i < s.length(); i++) {
chars[s.length() - 1 - i] = s.charAt(i);
if (twoCharCodepoint) {
swap(chars, s.length() - 1 - i, s.length() - i);
}
twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
}
return new String(chars);
}
private static void swap(char[] array, int i, int j) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
sb.append(".");
fos.write(sb.toString().getBytes("UTF-16"));
fos.write("\n".getBytes("UTF-16"));
fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}
A: You can use this:
new StringBuilder(hi).reverse().toString()
StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.
A: Using charAt() method
String name = "gaurav";
String reversedString = "";
for(int i = name.length()-1; i>=0; i--){
reversedString = reversedString + name.charAt(i);
}
System.out.println(reversedString);
Using toCharArray() method
String name = "gaurav";
char [] stringCharArray = name.toCharArray();
String reversedString = "";
for(int i = stringCharArray.length-1; i>=0; i--) {
reversedString = reversedString + stringCharArray[i];
}
System.out.println(reversedString);
Using reverse() method of the Stringbuilder
String name = "gaurav";
String reversedString = new StringBuilder(name).reverse().toString();
System.out.println(reversedString);
Check https://coderolls.com/reverse-a-string-in-java/
A: public static void main(String[] args) {
String str = "Prashant";
int len = str.length();
char[] c = new char[len];
for (int j = len - 1, i = 0; j >= 0; j--, i++) {
c[i] = str.charAt(j);
}
str = String.copyValueOf(c);
System.out.println(str);
}
A: It gets the value you typed and returns it reversed ;)
public static String reverse (String a){
char[] rarray = a.toCharArray();
String finalvalue = "";
for (int i = 0; i < rarray.length; i++)
{
finalvalue += rarray[rarray.length - 1 - i];
}
return finalvalue;
}
A: public String reverseWords(String s) {
String reversedWords = "";
if(s.length()<=0) {
return reversedWords;
}else if(s.length() == 1){
if(s == " "){
return "";
}
return s;
}
char arr[] = s.toCharArray();
int j = arr.length-1;
while(j >= 0 ){
if( arr[j] == ' '){
reversedWords+=arr[j];
}else{
String temp="";
while(j>=0 && arr[j] != ' '){
temp+=arr[j];
j--;
}
j++;
temp = reverseWord(temp);
reversedWords+=temp;
}
j--;
}
String[] chk = reversedWords.split(" ");
if(chk == null || chk.length == 0){
return "";
}
return reversedWords;
}
public String reverseWord(String s){
char[] arr = s.toCharArray();
for(int i=0,j=arr.length-1;i<=j;i++,j--){
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return String.valueOf(arr);
}
A: public void reverString(){
System.out.println("Enter value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
String str=br.readLine();
char[] charArray=str.toCharArray();
for(int i=charArray.length-1; i>=0; i--){
System.out.println(charArray[i]);
}
}
catch(IOException ex){
}
A: recursion:
public String stringReverse(String string) {
if (string == null || string.length() == 0) {
return string;
}
return stringReverse(string.substring(1)) + string.charAt(0);
}
A: Sequence of characters (or) StringString's Family:
String testString = "Yashwanth@777"; // ~1 1⁄4→D800₁₆«2²⁰
Using Java 8 Stream API
First we convert String into stream by using method CharSequence.chars(), then we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence of stream into String.
public static String reverseString_Stream(String str) {
IntStream cahrStream = str.chars();
final int[] array = cahrStream.map( x -> x ).toArray();
int from = 0, upTo = array.length;
IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );
String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
.mapToObj( reverseMapper ) // array[ lastElement ]
.collect(Collectors.joining()) // Joining stream of elements together into a String.
.toString(); // This object (which is already a string!) is itself returned.
System.out.println("Reverse Stream as String : "+ reverseString);
return reverseString;
}
Using a Traditional for Loop
If you want to reverse the string then we need to follow these steps.
*
*Convert String into an Array of Characters.
*Iterate over an array in reverse order, append each Character to temporary string variable until the last character.
public static String reverseString( String reverse ) {
if( reverse != null && reverse != "" && reverse.length() > 0 ) {
char[] arr = reverse.toCharArray();
String temp = "";
for( int i = arr.length-1; i >= 0; i-- ) {
temp += arr[i];
}
System.out.println("Reverse String : "+ temp);
}
return null;
}
Easy way to Use reverse method provided form StringBuffer or StringBuilder Classes
StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's.
StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );
String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString );
StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.
A: public static String revString(String str){
char[] revCharArr = str.toCharArray();
for (int i=0; i< str.length()/2; i++){
char f = revCharArr[i];
char l = revCharArr[str.length()-i-1];
revCharArr[i] = l;
revCharArr[str.length()-i-1] = f;
}
String revStr = new String(revCharArr);
return revStr;
}
A: Simple For loop in java
public void reverseString(char[] s) {
int length = s.length;
for (int i = 0; i < s.length / 2; i++) {
// swaping character
char temp = s[length - i - 1];
s[length - i - 1] = s[i];
s[i] = temp;
}
}
A: The short answer is that Java does not provide a general solution to reversing a String due to the "surrogate pairs" problem, which you have to allow for.
If the requirement is that it is guaranteed to work for all Unicode and in all languages (including Welsh :), then you have to roll your own. Just do an in-place array swap of the string as its code points:
public static String reverse(String str)
{
// You get what you ask for ;)
if (str == null) return null;
// str.length() is equal to the number of unicode code points in a string
if (str.isEmpty() || str.length() == 1) return str;
final int[] codePoints = str.codePoints().toArray();
final int len = codePoints.length;
// swap in place
for(int i = 0; i < codePoints.length/2; i++)
{
int tmp = codePoints[i];
codePoints[i] = codePoints[len-i-1];
codePoints[len-i-1] = tmp;
}
return new String(codePoints,0,len);
}
If you do this by using String.getBytes(), then all the bytes will be reversed, which will reverse all UTF-8 encodings, and any attempt using a Character that isn't an int code point will fail with any "astral plane" code points (those outside the BMP).
As a general solution this is reasonably efficient, but it is extremely simple and guaranteed to work for any string, which is probably want you want from a "general solution".
The only gotcha is if you read the String out of a UTF8/16 encoded file, you might have a BOM at the start, but that's outside the scope of the question.
-Blue
A: Using apache.commons.lang3
StringUtils.reverse(hi)
A: String str = "Hello World";
char[] strCharArr = str.toCharArray();
for(int i = 0, k= strCharArr.length-1;i != k; i++, k--) {
char temp = strCharArr[i];
strCharArr[i] = strCharArr[k];
strCharArr[k] = temp;
}
System.out.println(String.valueOf(strCharArr));
A: import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner (System.in);
String word = input.next();
String reverse = "";
for(int i=word.length()-1; i>=0; i--)
reverse += word.charAt(i);
System.out.println(reverse);
}
}
If you want to use a simple for loop!
A: StringBuilder s = new StringBuilder("racecar");
for (int i = 0, j = s.length() - 1; i < (s.length()/2); i++, j--) {
char temp = s.charAt(i);
s.setCharAt(i, s.charAt(j));
s.setCharAt(j, temp);
}
System.out.println(s.toString());
A: There are many ways to reverse a string.
1. Converting String into Bytes: getBytes() method is used to convert the input string into bytes[].
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString{
public static void main(String[] args)
{
String input = "GeeksforGeeks";
byte [] strAsByteArray = input.getBytes();
byte [] result = new byte [strAsByteArray.length];
for (int i = 0; i<strAsByteArray.length; i++)
result[i] =
strAsByteArray[strAsByteArray.length-i-1];
System.out.println(new String(result));
}
}
2.Converting String to character array: The user input the string to be reversed. (Personally suggested)
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString{
public static void main(String[] args)
{
String input = "GeeksForGeeks";
// convert String to character array
// by using toCharArray
char[] try1 = input.toCharArray();
for (int i = try1.length-1; i>=0; i--)
System.out.print(try1[i]);
}
}
3.Using ArrayList object: Convert the input string into the character array by using toCharArray() built in method. Then, add the characters of the array into the ArrayList object. Java also has built in reverse() method for the Collections class. Since Collections class reverse() method takes a list object , to reverse the list , we will pass the LinkedList object which is a type of list of characters.
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString{
public static void main(String[] args)
{
String input = "Geeks For Geeks";
char[] hello = input.toCharArray();
List<Character> trial1 = new ArrayList<>();
for (char c: hello)
trial1.add(c);
Collections.reverse(trial1);
ListIterator li = trial1.listIterator();
while (li.hasNext())
System.out.print(li.next());
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "574"
}
|
Q: Weather predictions Peter decides what to do at weekends according to the weather predictions.
This is the available information:
Saturday will be sunny, Sunday will be uncertain.
whenever it is sunny, Peter goes to the beach.
Whenever it's rainy he stays at home.
When the weather is uncertain it depends on the day: Saturdays he goes to the cinema, Sundays he goes for a walk with his family.
Represent in Prolog the previous sentences.
Formulate queries which allow to answer the following questions:
What will Peter do next Saturday?
Will Peter stay at home next Sunday?
Here's the code I've made and that doesn't work:
out(saturday,suny,_).
out(sunday,uncertain,_).
out(saturday,sunny,beach).
out(sunday, sunny, beach).
out(saturday,rainny,home).
out(sunday, rainny,home).
out(saturday,uncertain,cinema).
out(sunday,uncertain,family).
Now I don't know what queries should I make to answer the questions.... I think I might do something like this:
:-out(saturday,_,X).
But it doesn't work...
If anyone can help me that would be great.
A: The main reason it doesn't work is that you can't unify your facts. It's easier to construct prolog programs if you think about them in terms of being a query rather than a program. In your code, you have out matching suny AND sunny. if you fix that spelling error, you get this:
?- out(saturday,_,X).
true ;
X = beach ;
X = home ;
X = cinema ;
true.
Which is still probably not what you want because it's still matching too many things. try this instead:
weather(saturday, sunny).
weather(sunday, uncertain).
prefers(peter, if_weather(uncertain), onday(sunday), walk_with_family).
prefers(peter, if_weather(sunny), onday(_), go_to_beach).
prefers(peter, if_weather(uncertain), onday(saturday), go_to_cinema).
prefers(peter, if_weather(rainy), onday(_), stay_home).
peter_will_do_next(Day,X) :- prefers(peter, if_weather(Y), onday(Day), X), weather(Day,Y).
peter_will_stay_home_on(Day) :- peter_will_do_next(Day,Y), Y == stay_home.
?- peter_will_do_next(saturday,What).
What = go_to_beach .
?- peter_will_stay_home_on(sunday).
false.
In this code, we specify the facts of the weather as one procedure and the preferences of peter in anther (mostly for clarity). We can then query the facts and get a result that is (more likely) what you had in mind.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does the Document TYPE ( or even the way HTML tag is written) affects the javascript engine in IE9? Does the Document TYPE ( or even the way HTML tag is written) affects the javascript engine in IE9? I am not talking about the rendition but the behavior other than it.
A: Yes. The <!doctype> is used as rendering mode switch. This is notable especially in Internet Explorer, because this browser maintains (almost) full backwards compatibility in quirks mode, so there's no getElementsByClassName, Element Traversal, addEventListener, Selection API, ES5 support and many many other things. ES5 support also means changes in parsing so you might experience differences in things not related to DOM.
Always use <!doctype html> at the top of your markup, it's simple and provides best cross-browser compatibility.
A: Not exactly, but there are some differences in DOM support between standards and quirks mode. (e.g. in standards mode the browser does not brokenly support name as id).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can my app be rejected by Apple if I changed an UISeachBar background? Will my app be rejected by Apple if I changed an UISearchBar background to be transparent?
A: If you use 'private' APIs, or modify controls when Apple documentation says not to, then Apple may indeed reject your App. Possibly during initial review, or at a later date.
There is also the possibility that the API may change or be removed, without warning, causing your App to crash.
However, there are Apps in the App Store that clearly do use private APIs, and have been approved, but it's a risk you take. If that concerns you, don't do it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call another property file? I'm having two property file called sample.properties and sample1.properties in src folder at same level.
It is having some information like,
A1 = please call {sample1:name}
Here,
sample1 -> property file name
name -> key defined in sample1 like [name = abc]
I want to call sample1 property file , get value of name from that file and store it into the A1 key in sample.properties.
Is there any way to include and fetch value from other property file?
Thanks in Advance.
Regards,
Mayur Patel
A: I'm afraid I don't think you can do this. My understanding is that you can only provide one properties file per portlet.
What are you trying to achieve with this approach? Why can't you just use one properties file?
A: I achieved same problem not by calling property file from the same but I used stringtokenzier to split that token n from that i get name of property file and i called that file from java code only.
actually I wanted to know is it poosible to achieve this..thanks for your ideas
Regards,
Mayur Patel
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: asp.net website stops responding when doing heavy query I have an asp.net website that is nearing release. The site deals with business management. One of the things I am doing to prepare for release is upload a whole bunch of data from purchased lists of businesses into our SQL database. To do this, I'm using a very simple method: I put the .csv files in a folder on the server, and use the Page_Load event on a temporary page to do the logic needed to process the data and put it in our database.
This is a lengthy process. the business lists are broken up into a whole bunch of files, and I've got my script on the page set up to import all the data from one file on each refresh of the page. It takes about 10 minutes per file.
The weird thing is this: When processing this data ( while the server is processing everything, before the page_load method terminates) the website is blocked - no other users can access it, and no other pages on the site will load. They get stuck on the "Connecting..." phase.
This isn't a huge problem right now, as the site is just running in a test environment. However, I may need to use similar scripts to put data into the database when the site is live, and obviously its not acceptable to have access to all users blocked when this is happening.
I am fairly sure this isn't a problem with the SQL Server, as I am able to do simultaneous queries while this process is running, so it must be something wrong with the web server.
I can't post a code exerpt, because it is long winded and technical. However, nothing difficult is going on: The method reads in the data from the .csv file, processes it, and makes an HTTP Request to an external service for each line of the file, to collect some more relevant data. Then, all the data is inserted into the SQL database.
As I understand it, web servers shouldn't block like this. They should be able to simulatenously serve pages to lots of users at once, even if one thread/user is requiring lots of resources.
Can any suggest what might be up? Where should I start looking for a solution?
A: Have the request be processed by an asynchrounous handler.
http://msdn.microsoft.com/en-us/library/ms227433%28v=vs.85%29.aspx
This will allow your website to continue doing it's business while the long process is running.
A: ASP.NET is not meant for heavy processing.
The ASP.NET page should just trigger the action. A background process should do the heavy lifting. Both can communicate using a queue or something similar.
The Web page should simply report the status of the background tasks.
This paradigm is central in modern computing (especially cloud computing).
A: Please refer to http://msdn.microsoft.com/en-us/library/ff647787.aspx#scalenetchapt06_topic8 from msdn.
I think the problem is that you are using the default settings for asp.net where you don't get enough threads and only 2 outbound tcp/ip connections. This is just horrible for a real website.
Please change maxconnections, maxworkerthreads and others in your machine.config. There is a formula for some of these settings like 12 * number of CPUs, etc.
This should give you the performance boost you need.
Hope this helps.
Edit:-
My comments were before I learnt about the autoconfig=true setting in the machine.config. I did some preliminary research and discovered that these settings work for most applications. so, these customized settings are only needed for specialized scenarios that might need carefully considered optimizations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Should I store values in the database or in an XML or text file? I have a few simple questions about data storage on a website I am developing. The site in question will allow users a personal profile space which they have the ability to customise with text, images, BB code and alike. These profiles will have a character limit of around 5000. I was wondering how best to store this data, as it seems like a large amount to store in the database.
I was thinking about maybe using simple text files to store the data, and name them with the users ID. What do you guys think would be best for access and write speed, and would it detract from database read/write performance; as viewing and updating profiles will be a large part of the website.
Thanks guys. I look forward to hearing your opinions.
A: If you’re already using a database, it will be much easier to store it there. 5000 characters is nothing. Performance seems kind of irrelevant here.
A: I would go for storing them in the database because:
*
*All data in the database can use transactions to keep stuff consistent;
*A single insert (transaction) will take care of all your storage needs;
*A single select will retrieve all data;
*Backup the database and you are done;
*If you run into slowness, setting up a master-slave scheme or partitioning is easy;
*You can use database tools to search in the data;
On the other hand if you use the filesystem:
*
*filesystems do not have transactions, what happens if an insert fails, and you need to rollback, the file has already been saved;
*what happens if the filesystem gets out-of-sync with the database?
*It complicates your code, adding to the bugpressure;
*Writing to the filesystem adds an extra security hole, because your DB-app can now write and perhaps overwrite existing files on the filesystem.
More generally
Using the filesystem is used because storing large blobs in a db can be slow.
However you should not optimize until slowness sets in. Premature optimization is the root of all evil.
Slowness may never be a problem and besides you can do lots of optimization in the DB as well.
A: Saving things like this into a database is probably the best option. Until you have files that are at least megabytes in size, any decent database should handle them fine.
A: Is the profile information in any way at all related to the existing database information? Is the structure of the profile information completely regular, or does the user have some degree of control the structure of his or her profile? How many users will you have?
If the profile information is completely separate from the database functionality of the database or if it's decidedly variably structured, and if you have few enough files so as not to bog down the file system, then storing it in separate XML files is worth considering.
If there are a very large number of profiles and the information is amenable to relational storage then I'd probably put it in a database. If it's tied to the functionality of your main database it probably belongs there. If not, you could consider a separate database just for the profiles.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 'for' loop vs vectorization in MATLAB I was programming something in MATLAB and, as recommended, I am always trying to use vectorization. But in the end the program was quite slow. So I found out that in one place the code is significantly faster when using loops (example below).
I would like to know if I misinterpreted something or did something wrong, because performance is important in this case, and I don't want to keep guessing if vectorization or loops are going to be faster.
% data initialization
k = 8;
n = 2^k+1;
h = 1/(n-1);
cw = 0.1;
iter = 10000;
uloc = zeros(n);
fploc = uloc;
uloc(2:end-1,2:end-1) = 1;
vloc = uloc;
ploc = ones(n);
uloc2 = zeros(n);
fploc2 = uloc2;
uloc2(2:end-1,2:end-1) = 1;
vloc2 = uloc2;
ploc2 = ones(n);
%%%%%%%%%%%%%%%%%%%%%%
% vectorized version %
%%%%%%%%%%%%%%%%%%%%%%
tic
for it=1:iter
il=2:4;
jl=2:4;
fploc(il,jl) = h/6*(-uloc(il-1,jl-1) + uloc(il-1,jl)...
-2*uloc(il,jl-1)+2*uloc(il,jl+1)...
-uloc(il+1,jl) + uloc(il+1,jl+1)...
...
-vloc(il-1,jl-1) - 2*vloc(il-1,jl)...
+vloc(il,jl-1) - vloc(il,jl+1)...
+ 2*vloc(il+1,jl) + vloc(il+1,jl+1))...
...
+cw*h^2*(-ploc(il-1,jl)-ploc(il,jl-1)+4*ploc(il,jl)...
-ploc(il+1,jl)-ploc(il,jl+1));
end
toc
%%%%%%%%%%%%%%%%%%%%%%
% loop version %
%%%%%%%%%%%%%%%%%%%%%%
tic
for it=1:iter
for il=2:4
for jl=2:4
fploc2(il,jl) = h/6*(-uloc2(il-1,jl-1) + uloc2(il-1,jl)...
-2*uloc2(il,jl-1)+2*uloc2(il,jl+1)...
-uloc2(il+1,jl) + uloc2(il+1,jl+1)...
...
-vloc2(il-1,jl-1) - 2*vloc2(il-1,jl)...
+vloc2(il,jl-1) - vloc2(il,jl+1)...
+ 2*vloc2(il+1,jl) + vloc2(il+1,jl+1))...
...
+cw*h^2*(-ploc2(il-1,jl)-ploc2(il,jl-1)+4*ploc2(il,jl)...
-ploc2(il+1,jl)-ploc2(il,jl+1));
end
end
end
toc
A: I didn't go through your code, but the JIT compiler in recent versions of Matlab has improved to the point where the situation you're facing is quite common - loops can be faster than vectorized code. It is difficult to know in advance which will be faster, so the best approach is to write the code in the most natural fashion, profile it and then if there is a bottleneck, try switching from loops to vectorized (or the other way).
A: MATLAB's just in time compiler (JIT) has been improved significantly over the last couple years. And even though you are right that one should generally vectorize code, from my experience this is only true for certain operations and functions and also depends on how much data your functions are handling.
The best way for you to find out what works best, is to profile your MATLAB code with and without vectorization.
A: Maybe a matrix of a few elements is not a good test for vectorization efficiency. In the end it depends on the application on what works well.
Also, usually vectorized code looks better (more true to underlying model), but it many cases it does not and it ends up hurting the implementation. What you did is great as now you know what works best for you.
A: I would not call this vectorisation.
You appear to be doing some sort of filtering operation. A truly vectorised version of such a filter is the original data, multiplied by the filter matrix (that is, one matrix that represents the whole for-loop).
Problem with these matrices is that they are so sparse (only a few nonzero elements around the diagonal) that it's hardly ever efficient to use them. You can use the sparse command but even then, the elegance of the notation probably does not justify the extra memory required.
Matlab used to be bad at for loops because even the loop counters etc were still treated as complex matrices, so all the checks for such matrices were evaluated at every iteration. My guess is that inside your for loop, all those checks are still performed every time you apply the filter coefficients.
Perhaps the matlab functions filter and filter2 are useful here?
You may also ant to read this post: Improving MATLAB Matrix Construction Code : Or, code Vectorization for begginers
A: One possible explanation is startup overhead. If a temporary matrix is created behind the scene, be prepared for memory allocations. Also, I guess MATLAB cannot deduce that your matrix is small so there will be loop overhead. So your vectorized version may end up in code like
double* tmp=(double*)malloc(n*sizeof(double));
for(size_t k=0;k<N;++k)
{
// Do stuff with elements
}
free(tmp);
Compare this to a known number of operations:
double temp[2];
temp[0]=...;
temp[1]=...;
So JIT may be faster when the malloc-loopcounter-free time is long compared to the workload for each computation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to create combo box in iphone? Hi anybody can tell me how to create combo box in iphone (like same as Spinner in Android). Here i developing a simple application, i need to load some value to combo box. But not using UIPicker. Can anybody help me pls.
A: you can set your pickerview frame like follow
[pickerView setFrame:CGRectMake(0, 100, 320, 120)];
A: Here try this Code..
https://github.com/werner77/WEPopover
it is the best solution for combo box.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Open Graph beta: How can you tag friends in a action? I've managed to publish an activity using the Graph API. How can you tag friends in a action?
I can see you can add tags in the action dashboard, but other than that it's not specified how to tag friends.
A: There's a simplified example at https://developers.facebook.com/docs/beta/opengraph/actions/#tagging
Actions can be tagged with places and people by specifying the place and tags optional parameters.
A sample call would be a POST to
https://graph.facebook.com/me/{APP_NAME}:{ACTION NAME}?
{YOUR OTHER ACTION PARAMETERS HERE}
&place={A PLACE ID}
&tags={COMMA SEPARATED LIST OF UIDS}&access_token=YOUR_ACCESS_TOKEN
That would tag the users in the action, and also tag them at a place
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Mysql Select Statement with respect to another table field I have two tables. One is newBus, and Second is newPassengers. The table newBus contain the columns startcity and endCity. Now let say newBus.startCity contains:
newBus.id----newBus.startCity-----newBus.endCity
4 ACity to xCity
5 tCity to MCity
newPassenger table:
3 passengers wants to go to
newPassengers.s_city------newPassengers.e_city
tCity to GCity
OCity to FCity
tCity to MCity
I want to select the all passenger who want to go from tCity to MCity but with respect to newBus.id = 5.
A: SELECT newPassengers.id
FROM newBus
INNER JOIN newPassengers ON newPassengers.s_city = newBus.startCity
WHERE newPassengers.s_city = 'tCity'
AND newPassengers.e_city = 'MCity'
AND newBus.id = 5
This assumes that all passengers will get on a bus that has a start city the same as their start city, and that the ID of the passenger is newPassengers.id . You can add more fields to the select list to get the information you are after.
A:
I want to select the all passenger who want to go from tCity to MCity but with respect to newBus.id = 5.
SELECT p.id
FROM newpassengers p
INNER JOIN newbus b ON (p.s_city = b.startcity AND p.e_city = b.endCity)
WHERE p.s_city = 'tCity' AND p.e_city = 'MCity' AND b.id = '5';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to split array of strings based on string's length? I hope it can be done with "NSPredicate". I have array of strings in thousands and i want to split into array using string length. i.e. Strings with length 2 will come into an array. Strings with length 3 will come in an array so on. Is it possible using "NSPredicate". I checked NSPredicate Class Reference. But could not find useful example.
ThanksNeal
A: I hope following code solve your problem.
NSString *regExp = @"[A-Z0-9a-z]{2,3}";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
NSMutableArray *array=[NSMutableArray new];
[array addObject:@"ABC"];
[array addObject:@"AGADF"];
[array addObject:@"ADFADS"];
[array addObject:@"DD"];
[array addObject:@"DFA"];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"filter : %@",filtered);
A: I believe the NSPredicate with regex might not be efficient. This code should solve it for sure and more efficiently, you'll get the dictionary where keys are the string lengths, and objects are the corresponding arrays containing strings of certain length.
NSMutableDictionary* filtered = [NSMutableDictionary dictionary];
NSMutableArray* strings =[NSMutableArray array];
[strings addObject:@"ABC"];
[strings addObject:@"AGADF"];
[strings addObject:@"ADFADS"];
[strings addObject:@"DD"];
[strings addObject:@"DFA"];
for (NSString* s in strings) {
NSNumber* key = [NSNumber numberWithInt:[s length]];
NSMutableArray* arr = [filtered objectForKey:key];
if (nil==arr) {
arr = [NSMutableArray array];
[filtered setObject:arr forKey:key];
}
[arr addObject:s];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Simple RMI Application I have created a simple RMI application, that just send a message to RMI server.But when sending a message i got the error message.I am using eclipse for running the programs.
sending hello to 10.0.0.12:3233
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: com.zoondia.ReceiveMessageInterface (no security manager: RMI class loader disabled)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at test.rmi.RmiClient.main(RmiClient.java:28)
Caused by: java.lang.ClassNotFoundException: com.zoondia.ReceiveMessageInterface (no security manager: RMI class loader disabled)
at sun.rmi.server.LoaderHandler.loadProxyClass(Unknown Source)
at java.rmi.server.RMIClassLoader$2.loadProxyClass(Unknown Source)
at java.rmi.server.RMIClassLoader.loadProxyClass(Unknown Source)
at sun.rmi.server.MarshalInputStream.resolveProxyClass(Unknown Source)
at java.io.ObjectInputStream.readProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
Anybody knows what is the issue.Am using eclipse for running the program.is i needed rmi compailor in eclipse, or it compails automatically when running the program.
Thanks,
VKS.
A: The exception is indicating a failure to install an RMI security manager in your server. Unless a security manager is set, RMI will be unable to download any code from your client.
You need to do something like the following in your server code:
if (System.getSecurityManager() == null)
{
System.setSecurityManager(new java.rmi.RMISecurityManager());
}
Check out the javadocs for RMISecurityManager for more information.
A: For the first error, i.e unmarshalling arguments, i had that error once. Ensure you change the directory to your src folder before running the rmiregistry
For the second error, ensure you have created your policy files for both the server and the client.
A: The exception is indicating that the class named is not present in the client's classpath.
That can be due to one of two causes:
*
*You aren't using the codebase feature and you haven't included the class in the client JAR files.
*You are using the codebase feature and you haven't installed a security manager.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to build a GWT Application What is the best way I can use to build a GWT app to a .war file?
I already have one ant file to build my project, but, it is very ugly and slow. I think one of you have a better option...
thanks
A: Use maven. It's proven and commonly used to build java and GWT projects.
http://maven.apache.org/
You should use GWT maven plugin: http://mojo.codehaus.org/gwt-maven-plugin/
But you should be aware: GWT builds are always slow (depending on code amount). For thus you have to use full build only for production purposes. In maven you can run only specific subtasks and can add profiles. For more info read plugin documentation.
UPD:
For thus you have to use full build only for production purposes.
This is really not so. But for common development process you don't need to run GWT compile each time. When you running GWT in debug mode - it runs in hosted mode. So you haven't to waste your time on often rebuilds.
A: I personally use maven, but hey, to each their own. (At least you're not using a Makefile).
However, compiling a GWT application is going to be slow. The GWT compiler needs to compile multiple flavors of javascript for common browser types, and even the google engineers can't affect the laws of physics (maybe in the next release of guava).
My project compiles 6 separate iterations, and produces a 40MB war. The advantage was once I had it into a war, performance in Tomcat blew away the performance of hosted mode.
A: I create a better ant build than I have before, the complete code is:
<?xml version="1.0" encoding="UTF-8"?>
<project name="Build GPA" basedir="." default="war">
<property name="gwt.module.name" value="com.geekvigarista.scrummanager.GWT_ScrumManager"/>
<property name="server.resources.name" value="server_resources"/>
<property name="jar.name" value="gpa.jar"/>
<property name="war.name" value="gpa.war"/>
<property name="src.dir" location="src"/>
<property name="server.resources.dir" location="war/${server.resources.name}"/>
<property name="build.dir" location="build"/>
<property name="build.server.resources.dir" location="war/WEB-INF/classes/server_resources"/>
<property name="lib.dir" location="war/WEB-INF/lib"/>
<property name="gwt.client.dir" location="com/geekvigarista/scrummanager/client"/>
<path id="project.classpath">
<fileset dir="${lib.dir}">
<include name="**/*.jar"/>
</fileset>
</path>
<target name="prepare">
<mkdir dir="${build.dir}"/>
</target>
<target name="clean">
<delete dir="${build.dir}"/>
</target>
<!-- Compile the java source code using javac -->
<target name="compile" depends="prepare">
<javac srcdir="${src.dir}" destdir="${build.dir}">
<classpath refid="project.classpath"/>
</javac>
</target>
<!-- Invoke the GWT compiler to create the Javascript for us -->
<target name="gwt-compile" depends="compile">
<java failonerror="true" fork="true" classname="com.google.gwt.dev.Compiler">
<classpath>
<!-- src dir is added to ensure the module.xml file(s) are on the classpath -->
<pathelement location="${src.dir}"/>
<pathelement location="${build.dir}"/>
<path refid="project.classpath"/>
</classpath>
<jvmarg value="-Xmx512M"/>
<arg value="${gwt.module.name}"/>
</java>
</target>
<!-- Package the compiled Java source into a JAR file -->
<target name="jar" depends="compile">
<jar jarfile="${lib.dir}/${jar.name}" basedir="${build.dir}/">
<!-- Don't wrap any of the client only code into the JAR -->
<exclude name="${gwt.client.dir}/**/*.class"/>
</jar>
</target>
<!-- Copy the static server resources into the required
directory ready for packaging -->
<target name="copy-resources">
<copy todir="${build.server.resources.dir}" preservelastmodified="true">
<fileset dir="${server.resources.dir}"/>
</copy>
</target>
<!-- Package the JAR file, Javascript, static resources
and external libraries into a WAR file -->
<target name="war" depends="gwt-compile, jar, copy-resources">
<war basedir="war" destfile="${war.name}" webxml="war/WEB-INF/web.xml">
<exclude name="WEB-INF/**" />
<exclude name="${server.resources.name}/**"/>
<webinf dir="war/WEB-INF/">
<include name="classes/${server.resources.name}/**" />
<include name="**/*.jar" />
<exclude name="**/gwt-dev.jar" />
<exclude name="**/gwt-user.jar" />
</webinf>
</war>
</target>
</project>
It needs a folder called "server_resources" in the war folder.
This solution works great for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android live video streaming issue I have a question about video streaming from Android devices and maybe someone who will give me some useful advice/suggestions about my question.So here is the deal :
I have a project for video streaming from Android device.The idea is that to connect to devices to a server and the first one is streaming live video and upload it to server and the second device is streaming and watching the video from the first device. So there is connection like this :
First Device ----live streaming----> Web Server ------live streaming---->Second Device , where second device is connecting to the web server.
Any suggestions/advice how can I do that and what should I use?I will be really glad to hear your ideas.
Thanks in advance!
A: I was playing with something similar. Basically:
android video capture --> upstream to server --> transcoding --> streaming to players
*
*the video is captured by a mobile phone (currently only a proof of concept for Android) and delivered to a server
*the server performs transcoding from the original format (H.263 and AMR-NB within a .3gp
container) to a Flash video, so that it can be played in vast majority of browsers
My biggest issue is that with the H.263, I'm not able to upstream it live to the server. The video has a header, which indicates among others its length and other info. Then, in order the video can be transcoded (I use ffmpeg), the header must be present. But it is set by Android AFTER the video capturing is finished.
So as a work around, I'm capturing the video in e.g. 5 second slices.
Take a look at http://code.google.com/p/moteve and feel free to contribute :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calculating standard deviation of samples with boostrapping in R Imagine: I have sampled 10,000 humans and measured their height in cm, and drawn the distribution as follows:
# Generate sample data
sampleSize = 10000
sampleData = round(rnorm(n=sampleSize, mean=175, sd=14))
# Draw histogram of sample
h = hist(sampleData, breaks=max(sampleData)-min(sampleData))
######################################################################
# Calculate the mean of the measurement
meanMeasure = mean(sampleData)
meanMeasure
abline(v=meanMeasure, col="red")
# Calculate the standard deviation of the measurement
sdMeasure = sd(sampleData)
sdMeasure
rect(
xleft=meanMeasure-sdMeasure,
ybottom=min(h$counts),
xright=meanMeasure+sdMeasure,
ytop=max(h$counts),
col="#0000ff22"
)
Now I want to estimate how large the standardDeviation is for each measured body height. I thought that bootstrapping my original dataset would be a good method, i.e sampling body sizes from my original dataset with replacement.
Is this a good method?
How can I perform this analysis in R (e.g. standard deviation for each height in a bootstrap analysis with 1000 cycles)?
A: If you measure each individual only once there is no way of obtaining the standard deviation "for each measured body height". Bootstrapping can only be used if you have more than one datapoint for which you want to obtain an estimate.
For obtaining the standard deviation "for each measured body height" , each body height would have to be measured more than once.
If you, however, want to obtain an bootstrapped estimate of the standard deviation of you overall sample, then the other two answers apply.
Furthermore, this question would be better suited on crossvalidated.com.
A: It's entirely unnecessary to use bootstrapping for that purpose when your sample size is so large. If you wanted to know the extent of plausible variation in the standard deviation in samples of only 100 or 200 or maybe even 500 individuals, then bootstrapping would be informative. But with 10,000 individuals the bootstrap variation in the standard deviation is going to be very, very small.
A: Bootstrapping is usually employed to calculate the variance of an estimator, in your case, the sample mean height. When you're just looking to find the variance of the heights of people, you don't need to do a bootstrap.
Why do we bootstrap? Because for our one sample we only have one sample mean. So we need many samples to get many sample means to calculate the variance of that estimator. Bootstrapping is a way to get many pseudo-samples when we only have one.
In your case, we already have many individual observations of heights, so we don't need any more---we can just calculate the variance directly based upon our "real" observations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Save Dynamically generated PDF from Web browser control I have a web browser control in my windows form. I am trying to automate some process in a website. During this process, the invoice pdf has been generated dynamically and shown in the web browser control. I need to save that pdf locally. Please note: there is no direct link to download the pdf. I googled a lot past couple of days and haven't found any solution yet.
Can someone help me on this?
Thanks.
A: I would recommend handling the WebBrowser.Navigating event. One of the parameters of this event is WebBrowserNavigatingEventArgs which has a property called Url. If you're lucky, that property will end in .pdf. If you're not lucky you might have to perform a manual HEAD request and inspect the returned MIME-type to see if its a PDF.
Another thing that you could try is handling the WebBrowser.FileDownload event but I'm not sure if it will be raised for PDFs viewed in-browser. If you have absolute control over the machine this is running on I would recommend disabling viewing of PDFs in the browser and just handle this event instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get a recursive parent list Using MySQL, I want to return a list of parents, from a table that has a field structure like this. ID,PARENTID,NAME (a standard parent-child hierarchy). I would like to traverse "up" the tree to return a list of ALL 'parents'.
I realize that "nested set", might be a better way to handle this - but currently I cannot change the structure of the data. I will look to do that in the future. Currently - my set of data will realistically contain a few levels of depth - nothing crazy... maybe 2-5 so my recursive hit shouldn't be 'too expensive'.
I've looked at the solutions presented in SQL Server get parent list - but this syntax bombs in mySQL...
Does anyone have an example of how to do this?
@kevin - thx for link - but I still get error. ("every derived table must have it's own alias")
Here's what I did (modified syntax form above article - to 'fit' MySQL) - I clearly missed something...
SELECT parents.*
FROM (
SELECT taskID, task, parentID, 0 as level
FROM tasks
WHERE taskidID = 9147
UNION ALL
SELECT taskID, task, parentID, Level + 1
FROM tasks
WHERE taskID = (SELECT parentID FROM parents ORDER BY level DESC LIMIT 1)
)
thoughts???
EXAMPLE:
ID PARENTID NAME
9146 0 thing1
9147 0 thing2
9148 9146 thing3
9149 9148 thing4
9150 0 thing5
9151 9149 thing6
Query for parents of "thing3"
Returns "9148,9146"
Query for parents of "thing6"
Returns "9149,9148,9146,0"
A: Here, I made a little function for you, I checked it in my database (MAMP) and it works fine
use mySchema;
drop procedure if exists getParents;
DELIMITER $$
CREATE PROCEDURE getParents (in_ID int)
BEGIN
DROP TEMPORARY TABLE IF EXISTS results;
DROP TEMPORARY TABLE IF EXISTS temp2;
DROP TEMPORARY TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 AS
select distinct ID, parentID
from tasks
where parentID = in_ID;
create TEMPORARY table results AS
Select ID, parentID from temp1;
WHILE (select count(*) from temp1) DO
create TEMPORARY table temp2 as
select distinct ID, parentID
from tasks
where parentID in (select ID from temp1);
insert into results select ID, parentID from temp2;
drop TEMPORARY table if exists temp1;
create TEMPORARY table temp1 AS
select ID, parentID from temp2;
drop TEMPORARY table if exists temp2;
END WHILE;
select * from results;
DROP TEMPORARY TABLE IF EXISTS results;
DROP TEMPORARY TABLE IF EXISTS temp1;
END $$
DELIMITER ;
this code will return all parents to any depth.
you can obviously add any additional fields to the results
use it like this
call getParents(9148)
for example
A: In this example we are checking 5 levels up:
select
t1.parentid, t2.parentid, t3.parentid, t4.parentid, t5.parentid
from
tableName t1
left join tableName t2 on t1.parentid = t2.id
left join tableName t3 on t2.parentid = t3.id
left join tableName t4 on t3.parentid = t4.id
left join tableName t5 on t4.parentid = t5.id
where
t1.name = 'thing3'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: how to fix interval on UISlider,iphone I have Slider,which works perfect.
But what i am trying to do is,
for ex, min =0 and max=50 and x=0
every time i slide or use buttons to change the value of slider, the interval should be of 5 only.
i.e x should be equal to only 0,5,10,15.....50
Suggestions.
Thanks
A: In the callback (value changed) - read the value, round it up or down to the nearest increment of 5, then set the slider to your preferred value. That way, it will 'jump' between your preferred values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby mysql gem works but I see an exception when I execute the script with debug option using -d $DEBUG I have got some CGI scripts. I use mysql connection and queries in these scripts. After seeing some anomalies in the scripts I wanted to execute them using ruby debug options.
Here, below, a small test script that shows the problem.
Without debug options, there is nothing, no error, I can connect to database and run queries but when I use debug option ( -d $DEBUG ) it throws an exception. Interesting thing is, even there is exception, it works, it connects to database.
Any idea ? What is the problem ? How can I fix it ? It is fresh Ubuntu 11.04 install. Details are below.
rvm -v:
rvm 1.8.4 by Wayne E. Seguin (wayneeseguin@gmail.com) [https://rvm.beginrescueend.com/]
ruby -v:
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]
gem -v:
1.8.10
gem list:
* LOCAL GEMS *
mysql (2.8.1)
mysql2 (0.3.7)
rake (0.9.2)
ruby dbtest.rb:
14701920
ruby -d $DEBUG dbtest.rb:
Exception `LoadError' at /home/mehmet/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36 - no such file to load -- mysql
11340120
more dbtest.rb:
#!/home/paul/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
require 'rubygems'
require 'mysql'
connection = Mysql.new("localhost", "", "", "mymarket")
puts connection.object_id
Cheers,
A: Rubgems first attempts to load a required file through the normal Ruby require mechanism. Only if this fails, it uses the gem infrastructure.
What you are seeing is the failure (exception) of the non-gem require. After that, the gem require catches up and correctly loads the gem.
The global variable $DEBUG makes Ruby display exceptions even if they are caught.
From the source of custom_require.rb with line 36 highlighted:
alias gem_original_require require
...
def require path
if Gem.unresolved_deps.empty? or Gem.loaded_path? path then
gem_original_require path # <---- line 36
else
...
end
rescue LoadError => load_error
if load_error.message.end_with?(path) and Gem.try_activate(path) then
return gem_original_require(path)
end
raise load_error
end
UPDATE:
For solving this issue, either
*
*ignore the message (It is harmless.)
*"activate" the gem with gem 'mysql' before the require (This will setup the search path for the gem to be found by the initial non-gem attempt.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to speed up my ArrayList searching? I currently have an ArrayList holding objects of a class I have created, I then parse through the ArrayList in a for loop searching and comparing some data from the ArrayList and some global variables that are loaded else where, however this ArrayList is constantly growing and will eventually have about 115 elements to it towards the end, which then takes a very long time to search through, the function that does this is also called once for every line I read from a text file and the text file will usually be around 400-500 lines long so as you can tell it is very slow process even when testing on small files. Is there a way to speed this up by maybe using another collection instead of an ArrayList, my reasoning for using the ArrayList is I have to know what index it is on when it finds a match.
Here is the class:
private ArrayList<PanelData> panelArray = new ArrayList<PanelData>(1);
public class PanelData {
String dev = "";
String inst = "";
double tempStart = 0.0;
double tempEnd = 0.0;
}
Function:
public void panelTimeHandler (double timeStart, double timeEnd) throws SQLException {
PanelData temps = new PanelData();
temps.dev = devIDStr;
temps.inst = instanceStr;
temps.tempStart = timeStart;
temps.tempEnd = timeEnd;
boolean flag = false;
if(!flag)
{
panelArray.add(temps);
flag = true;
}
for(int i = 0; i < panelArray.size(); ++i ) {
if(panelArray.get(i).dev.equals(devIDStr) && panelArray.get(i).inst.equals(instanceStr)) {
if(panelArray.get(i).tempStart <= timeStart && panelArray.get(i).tempEnd >= timeEnd ) {
//Do Nothing
}
else
{
temps.dev = devIDStr;
temps.inst = instanceStr;
temps.tempStart = timeStart;
temps.tempEnd = timeEnd;
insert();
panelArray.set(i, temps);
}
}
else
{
temps.dev = devIDStr;
temps.inst = instanceStr;
temps.tempStart = timeStart;
temps.tempEnd = timeEnd;
panelArray.add(temps);
insert();
}
}
}
If there is something more you would like to see just ask, thanks. Beef.
Update: Added insert() function
private void insert() throws SQLException
{
stmt = conn.createStatement();
String sqlStm = "update ARRAY_BAC_SCH_Schedule set SCHEDULE_TIME = {t '" + finalEnd + "'} WHERE SCHEDULE_TIME >= {t '" + finalStart + "'} AND" +
" SCHEDULE_TIME <= {t '" + finalEnd + "'} AND VALUE_ENUM = 0 AND DEV_ID = " + devIDStr + " and INSTANCE = " + instanceStr;
int updateSuccess = stmt.executeUpdate(sqlStm);
if (updateSuccess < 1)
{
sqlStm = "insert into ARRAY_BAC_SCH_Schedule (SITE_ID, DEV_ID, INSTANCE, DAY, SCHEDULE_TIME, VALUE_ENUM, Value_Type) " +
" values (1, " + devIDStr + ", " + instanceStr + ", " + day + ", {t '" + finalStart + "'}, 1, 'Unsupported')";
stmt.executeUpdate(sqlStm);
sqlStm = "insert into ARRAY_BAC_SCH_Schedule (SITE_ID, DEV_ID, INSTANCE, DAY, SCHEDULE_TIME, VALUE_ENUM, Value_Type) " +
" values (1," + devIDStr + ", " + instanceStr + ", " + day + ", {t '" + finalEnd + "'}, 0, 'Unsupported')";
stmt.executeUpdate(sqlStm);
}
if(stmt!=null)
stmt.close();
}
Update:
Thank you to Matteo, I realized I was adding to the array even if I didnt find a match till the 10th element it would then added to the array the first 9 times which created many extra elements in the array, which was why it was so slow, I added some breaks and did a little tweaking in the function, and it improved the performance a lot. Thanks for all the input
A: you can use LinkedHashSet. It seems you add only elements to the end of the list, which is exactly what LinkedHashSet does as well, when inserting an element.
Note however, a LinkedHashSet will not allow duplicates, since it is a set.
Searching if an element exists will be O(1) using contains()
Using the LinkedHashSet will also allow you to keep track of where an element was added, and iterating it will be in order of insertion.
A: What about using a hashmap?
I would create a small class for the key:
class Key {
String dev, instr;
// todo: implements equals & hashCode
}
and create the map:
Map<Key, PanelData> map = new HashMap...
then you can easily find the element you need by invoking map.get(new Key(...)).
Instead of creating a new class, you could also tweak the PanelData class, implementing methods equals & hashcode so that two classes are equal iff their dev and instr are equal. In this case, your map becomes:
Map<PanelData, PanelData> map ...
// to add:
map.put(temps, temps)
// to search:
PanelData elem = map.get(new PanelData(desiredDev, desiredInstr));
A: Quite a few optimiztions here.
1) the call: panelArray.get(i) is used repeatedly. Declare a PanelData variable outside the loop, but initialize it only once, at the very begining of the loop:
PanelData pd = null;
for (int i = 0; i < panelArray.size(); ++i) {
pd = panelArray.get(i);
...
}
2) If your dataset allows it, consider using a few maps to help speed look up times:
HashMap<String, PanelData> devToPanelDataMapping = new HashMap<String,PanelData>();
HashMap<String, PanelData> instToPanelDataMapping = new HashMap<String,PanelData>();
3) Consider hashing your strings into ints or longs since String.equals() is slow compared to (int == int)
4) If the ArrayList will be read only, perhaps a multithread solution may help. The thread that reads lines from the text file can hand out individual lines of data to different 'worker' threads.
A: 1) Create PanelArray with the max expected size + 10% when you first create it.
List<PanelData> panelArray = new ArrayList<PanelData>(130) - this will prevent dynamic reallocations of the array which will save processing time.
2) What does insert() do? Odds are that is your resource hog.
A: This problem might best be solved with a different data structure such as a HashMap or SortedSet.
In order to use a HashMap, you would need to define a class that can produce a hash code for the dev and inst string pairs. One solution is something like:
public class DevAndInstPair
{
private String dev, inst;
@Override
public int hashCode() {
return ((dev.hashCode() * 0x490aac18) ^ inst.hashCode());
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof DevAndInstPair)) {
return false;
}
DevAndInstPair other = (DevAndInstPair) o;
return (dev.equals(other.dev) && inst.equals(other.inst));
}
}
You would then use HashMap<DevAndInstPair, PanelData> as the map type.
Alternatively, if you know that a certain character never appears in dev strings, then you can use that character as a delimiter separating the dev value from the inst value. Supposing that this character is a hyphen ('-'), the key values would be dest + '-' + inst and the key type of the map would be String.
To use SortedSet, you would either have PanelData implement Comparable<PanelData> or write a class implementing Comparator<PanelData>. Remember that the compare operation must be consistent with equals.
A SortedSet is somewhat trickier to use than a HashMap, but I personally think that it is the more elegant solution to this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Passing a class property as a parameter I'd like to pass a class property (or a getter/setter if need be) reference to a function.
For example I have an array of a class with lots of boolean flags.
class Flags
{
public bool a;
public bool b;
public bool c;
public string name;
public Flags(bool a, bool b, bool c, string name)
{
this.a = a;
this.b = b;
this.c = c;
this.name = name;
}
}
I can write a method that returns all instances of Flags for which a chosen flag is true
public Flags[] getAllWhereAisTrue(Flags[] array)
{
List<Flags> resultList = new List<Flags>();
for (int i = 0; i < array.Length; i++)
{
if (array[i].a == true) // for each Flags for which a is true
{ // add it to the results list
resultList.Add(array[i]);
}
}
return resultList.ToArray(); //return the results list as an array
}
What would I use to allow me to pass a class property as a parameter, so as to save me from having to write this method once for each boolean property of Flags (in this example that's three times, once for a, b and c)?
I'm trying to avoid giving Flags an array of Booleans in an attempt to keep the resulting code easy to read. I'm writing a library for use by relatively inexperienced coders.
Thank you
(With apologies if this is a dupe of Passing property as parameter in method, I can't quite tell if it's the same issue)
A: You could use a Func<Flags, bool> as parameter:
public Flags[] getAllWhereAisTrue(Flags[] array, Func<Flags, bool> propertySelector)
{
List<Flags> resultList = new List<Flags>();
for (int i = 0; i < array.Length; i++)
{
if (propertySelector(array[i])) // for each Flags for which a is true
{ // add it to the results list
resultList.Add(array[i]);
}
}
return resultList.ToArray(); //return the results list as an array
}
Then you could use it like this:
var allAFlagsSet = getAllWhereAisTrue(flagsArray, x=> x.a);
But really you should not reinvent this - Linq does this out of the box (notice the similarity):
var allAFlagsSet = flagsArray.Where(x=> x.a).ToArray();
Both solutions would require the a,b,c to be public (should really be a public property in this case)
A: according to the language spec it is not possible to pass properties as ref parameters. this stackoverflow post is on the same subject. moreover, I'll second the comment of SLaks: LINQ has a method that does just this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Dynamically add items to TabBar in Sencha Touch New to senchatouch world, trying to make the following code work.
I have the following code :
myApp.views.Homecard = Ext.extend(Ext.TabPanel, {
id: 'myownid',
title : "home",
iconCls : "home",
defaults : {
styleHtmlContent : true
},
items : [{
title : 'Item1',
scroll : 'vertical',
iconCls : 'home',
html : 'Some Content'
}, {
title : 'Item2',
scroll : false,
iconCls : 'home',
html : 'Some Content'
}],
});
Ext.reg('homecard', myApp.views.Homecard);
And i'd like to add a new item :
myApp.views.Homecard.add({html: 'test'});
But i'm getting the following error :
Uncaught TypeError: Object function (){h.apply(this,arguments)}
has no method 'add'
What am I missing ?
A: You can't access the TabPanel like that. Either add an id property and then get it with Ext.getCmp(theId); or get it like item of it's parent, example parent.items.items[0];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Easy way to create menus in GTK#? Is there an easy way to make menus in Gtk# ? In Gtk+ and PyGtk there is the ItemFactory which creates menus easily but it is bugged and deprecated in Gtk#, so is there any other easier way? Except for using a GUI Designer...
A: Check out Gtk.UIManager.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: robots.txt and serving images from a separate domain I'm trying to find out if a robots.txt file set on domain A will still apply to an image served from domain B, but actually displayed on domain A.
Example:
Somewhere on the page on www.example.com, there is an:
<img src="http://img.example.com/images/myimage.jpg" />`
In www.example.com/robots.txt, it says:
User-agent: *
Disallow: /images/
So when the spider hits www.example.com and sees the image being served from img.example.com, will it index it?
A: robots.txt only applies to the hostname it actually exists on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python script that notifies me when a update is made to a website. I need to make a script that will notify me when a change is made to a website. I am not sure about the best way to go about this and I don't know what python has that will be useful. Any push in the right direction would be helpful.
A: You may use the last-modified date of the remote page :
import urllib
u = urllib.urlopen("http://www.google.com")
u.info().get("last-modified")
A: It all depends on what you define as an update to a website.
The simplest solution would be to use urllib2 to get the contents of the given website, storing it in a variable then quering the website again for contents and comparing them.
Have that running in an infinite loop and you are set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Drupal7: Trying to theme a specific page using a preprocess function, but...I get a blank screen instead I've just discovered that if you want to alter a specific page (or group of pages) all you need is to add templates file to the core templates. For instance, I need to theme my /helloword page using a page--helloworld.tpl.php and node--helloworld.tpl.php template files.
Now all I get is a blank screen so I tried to write a preprocess function that adds support for custom theme files like:
<?php
/**
* Adding or modifying variables before page render.
*/
function phptemplate_preprocess_page(&$vars) {
// Page change based on node->type
// Add a new page-TYPE template to the list of templates used
if (isset($vars['node'])) {
// Add template naming suggestion. It should alway use doublehyphens in Drupal7.
$vars['template_files'][] = 'page--'. str_replace('_', '-', $vars['node']->type);
}
}
?>
I see no syntax error but I still get a blank screen. Still no luck
Is someone able to figure out what's wrong in the code/routine?
Drupal7 + Omega Sub-Theme
Kind Regards
A: I think there's a tiny bit of confusion here: a template file named node--type.tpl.php will automatically be called for any node which has the type type...you don't need to add the template suggestions in yourself.
There is one caveat to this, you have to copy the original node.tpl.php to your theme folder and clear your caches otherwise Drupal won't pick it up.
Also you don't want to use the phptemplate_ prefix...rather you want your function to be called MYTHEMENAME_preprocess_page.
Your code to add the page template based on the node type looks spot on, see if you still have the problem after you change your function name and clear the caches.
Hope that helps :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS: Constrain a table with long cell contents to page width? Take the following CSS+HTML:
<style>
div.stuff {
overflow: hidden;
width: 100%;
white-space: nowrap;
}
table { width: 100%; }
td { border: 1px dotted black; }
</style>
<table>
<tr><td>
<div class='stuff'>Long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text</div>
</td></tr>
</table>
This causes the table to grow to accommodate the entire long text. (Make your browser window smaller to see if you have a humongous screen resolution.)
I added width: 100% and overflow: hidden to indicate that the long text should simply be cut off, but it seems to ignore that. How do I constrain the table/the table cell/the div in such a way that the table’s width does not exceed the width of the document?
(Please don’t comment on the merits of using a table at all. I am indeed displaying tabular data, so the use of a table is semantically correct. Also please don’t question the user-friendliness of cutting off the text; there is actually an “expand” button that allows the user to view the full contents. Thanks!)
(Edit: I tried max-width too, to no avail.)
A: To achieve this, you have to wrap the long text into two divs. The outer one gets position: relative and contains only the inner one. The inner one gets position: absolute, overflow: hidden, and width: 100% (this constrains it to the size of the table cell).
The table-layout algorithm now considers those table cells empty (because absolutely-positioned elements are excluded from layout calculations). Therefore we have to tell it to grow that column regardless. Interestingly, setting width: 100% on the relevant <col> element works, in the sense that it doesn’t actually fill 100% of the width, but 100% minus the width of all the other columns (which are automatically-sized). It also needs a vertical-align: top as otherwise the (empty) outer div is aligned middle, so the absolutely-positioned element will be off by half a line.
Here is a full example with a three-column, two-row table showing this at work:
CSS:
div.outer {
position: relative;
}
div.inner {
overflow: hidden;
white-space: nowrap;
position: absolute;
width: 100%;
}
table {
width: 100%;
border-collapse: collapse;
}
td {
border: 1px dotted black;
vertical-align: top;
}
col.fill-the-rest { width: 100%; }
HTML:
<table>
<col><col><col class="fill-the-rest">
<tr>
<td>foo</td>
<td>fooofooooofooooo</td>
<td>
<div class='outer'>
<div class='inner'>
Long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text
</div>
</div>
</td>
</tr>
<tr>
<td>barbarbarbarbar</td>
<td>bar</td>
<td>
<div class='outer'>
<div class='inner'>
Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text
</div>
</div>
</td>
</tr>
</table>
In this example, the first two columns will have the minimum possible size (i.e. spaces will make them wrap a lot unless you also add white-space: nowrap to them).
jsFiddle: http://jsfiddle.net/jLX4q/
A:
I added width: 100% and overflow: hidden to indicate that the long text should simply be cut off, but it seems to ignore that.
It's not ignoring that, your div is expanding 100% the width of your table, which is set to expand 100% as it is, just give your td a max-width and it should cutoff as you expect.
A: Building off of @Timwi's solution...
table {
width: 100%;
border: 1px solid #ccc;
}
td {
padding: 14px;
line-height: 1.5;
border: 1px solid #ccc;
}
.outer {
position:relative;
height: 22px;
}
.inner {
position: absolute;
overflow: hidden;
width: 100%;
white-space: nowrap;
margin: auto;
top: 0;
bottom:0;
}
<table>
<tr>
<td>
<div class="outer">
<div class="inner">
this_is_a_really_long_string_of_text
</div>
</div>
</td>
<td>
222222222
</td>
</tr>
</table>
I'm using bootstrap 2.3.2 so that's where the height value is coming from. Here's a link to the fiddle http://jsfiddle.net/YFCV6/
A: Slightly different answer: If you'd prefer the table to display all its contents, while still being constrained to the page width, try using overflow-wrap: anywhere. This forces text to wrap, breaking on word boundaries when possible.
To support older browsers, you can use the legacy word-break: break-word with word-break: break-all as a fallback.
Example here: https://jsfiddle.net/joseph_white3/nhj9fLrw/
Also note: only set table-layout: fixed if you want the column widths to be determined based on just the first row. See the documentation on MDN.
A: you have nowrap set so the td cannot properly constrain the content. Removing that value should achieve the desired result.
A: As long as you have any width: 100% tags, it going to expand to contain the content.
One way to get the desired result (text that does not wrap) is to have an outer div w/ overflow hidden + a set width, then an inner div with a super wide width.
http://jsfiddle.net/xvaEw/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Rooting android emulator - Error? I have to root android emulator. I've found some articles, but I've got the same error every time! It's 'cannot create su: not enough memory'!
What I did:
1. adb push su /data/local
2. adb shell
3. #su
4. #mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
5. # cd /system/xbin
6. # mv su osu
7. # cat /data/local/su > su // I've got an error!!!
//Cannot create su: Out of memory!
What do I wrong?
A: I've got answer on my question!
I must run an android emulator with -partition-size 128 option.
It should look like below:
android-sdk-windows\tools\emulator -avd MyAndroidVirtualDeviceName -partition-size 128
After that I can root my emulator.
A: Looks like /system/xbin is not rw.
The fact that mount -o remount,rw does not return errors doesn't mean that it succeeded.
Check what mount reports for /system after the remount.
Also, see if you have proper permissions to write there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to test abstract class in Java with JUnit? I am new to Java testing with JUnit. I have to work with Java and I would like to use unit tests.
My problem is: I have an abstract class with some abstract methods. But there are some methods which are not abstract. How can I test this class with JUnit? Example code (very simple):
abstract class Car {
public Car(int speed, int fuel) {
this.speed = speed;
this.fuel = fuel;
}
private int speed;
private int fuel;
abstract void drive();
public int getSpeed() {
return this.speed;
}
public int getFuel() {
return this.fuel;
}
}
I want to test getSpeed() and getFuel() functions.
Similar question to this problem is here, but it is not using JUnit.
In JUnit FAQ section, I found this link, but I don't understand what the author want to say with this example. What does this line of code mean?
public abstract Source getSource() ;
A: If you need a solution anyway (e.g. because you have too many implementations of the abstract class and the testing would always repeat the same procedures) then you could create an abstract test class with an abstract factory method which will be excuted by the implementation of that test class. This examples works or me with TestNG:
The abstract test class of Car:
abstract class CarTest {
// the factory method
abstract Car createCar(int speed, int fuel);
// all test methods need to make use of the factory method to create the instance of a car
@Test
public void testGetSpeed() {
Car car = createCar(33, 44);
assertEquals(car.getSpeed(), 33);
...
Implementation of Car
class ElectricCar extends Car {
private final int batteryCapacity;
public ElectricCar(int speed, int fuel, int batteryCapacity) {
super(speed, fuel);
this.batteryCapacity = batteryCapacity;
}
...
Unit test class ElectricCarTest of the Class ElectricCar:
class ElectricCarTest extends CarTest {
// implementation of the abstract factory method
Car createCar(int speed, int fuel) {
return new ElectricCar(speed, fuel, 0);
}
// here you cann add specific test methods
...
A: I would create a jUnit inner class that inherits from the abstract class. This can be instantiated and have access to all the methods defined in the abstract class.
public class AbstractClassTest {
public void testMethod() {
...
}
}
class ConcreteClass extends AbstractClass {
}
A: You could do something like this
public abstract MyAbstractClass {
@Autowire
private MyMock myMock;
protected String sayHello() {
return myMock.getHello() + ", " + getName();
}
public abstract String getName();
}
// this is your JUnit test
public class MyAbstractClassTest extends MyAbstractClass {
@Mock
private MyMock myMock;
@InjectMocks
private MyAbstractClass thiz = this;
private String myName = null;
@Override
public String getName() {
return myName;
}
@Test
public void testSayHello() {
myName = "Johnny"
when(myMock.getHello()).thenReturn("Hello");
String result = sayHello();
assertEquals("Hello, Johnny", result);
}
}
A: Create a concrete class that inherits the abstract class and then test the functions the concrete class inherits from the abstract class.
A: You can instantiate an anonymous class and then test that class.
public class ClassUnderTest_Test {
private ClassUnderTest classUnderTest;
private MyDependencyService myDependencyService;
@Before
public void setUp() throws Exception {
this.myDependencyService = new MyDependencyService();
this.classUnderTest = getInstance();
}
private ClassUnderTest getInstance() {
return new ClassUnderTest() {
private ClassUnderTest init(
MyDependencyService myDependencyService
) {
this.myDependencyService = myDependencyService;
return this;
}
@Override
protected void myMethodToTest() {
return super.myMethodToTest();
}
}.init(myDependencyService);
}
}
Keep in mind that the visibility must be protected for the property myDependencyService of the abstract class ClassUnderTest.
You can also combine this approach neatly with Mockito. See here.
A: My way of testing this is quite simple, within each abstractUnitTest.java. I simply create a class in the abstractUnitTest.java that extend the abstract class. And test it that way.
A: With the example class you posted it doesn't seem to make much sense to test getFuel() and getSpeed() since they can only return 0 (there are no setters).
However, assuming that this was just a simplified example for illustrative purposes, and that you have legitimate reasons to test methods in the abstract base class (others have already pointed out the implications), you could setup your test code so that it creates an anonymous subclass of the base class that just provides dummy (no-op) implementations for the abstract methods.
For example, in your TestCase you could do this:
c = new Car() {
void drive() { };
};
Then test the rest of the methods, e.g.:
public class CarTest extends TestCase
{
private Car c;
public void setUp()
{
c = new Car() {
void drive() { };
};
}
public void testGetFuel()
{
assertEquals(c.getFuel(), 0);
}
[...]
}
(This example is based on JUnit3 syntax. For JUnit4, the code would be slightly different, but the idea is the same.)
A: If you have no concrete implementations of the class and the methods aren't static whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API.
I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both protected and public, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.
A: You can not test whole abstract class. In this case you have abstract methods, this mean that they should be implemented by class that extend given abstract class.
In that class programmer have to write the source code that is dedicated for logic of his.
In other words there is no sens of testing abstract class because you are not able to check the final behavior of it.
If you have major functionality not related to abstract methods in some abstract class, just create another class where the abstract method will throw some exception.
A: As an option, you can create abstract test class covering logic inside abstract class and extend it for each subclass test. So that in this way you can ensure this logic will be tested for each child separately.
A: You don't need a fancy Mockito add on, or anonymous classes, or whatever other things the other answers are recommending. Junit supports test classes extending each other: so, write a thorough, abstract test class (literally just make the test class abstract) for your abstract base class, that examines how each of the methods behave. Do these tests on a set of instance-variable objects, that are set up as you desire in an @BeforeEach method in this base test class. Have that method call an abstract allocateObjects() method, which will do all the object allocation.
Then, for each class that extends your abstract base, have a test class that extends the abstract test class you just wrote. This test class will do the actual object allocation in the overridden allocateObjects() method. The objects it allocates will be used by the methods in the parent test class: methods which are inhertied by this test class, and therefore run as a part of its testing.
Could you do factory tomfoollery? I guess: but since you probably need to create test classes for each subclass anyways, you might as well just keep things simple with inheritence. I suppose if you have a lot of subclasses, and none of them do anything that is worth testing appart from the superclass stuff, it would be worth it: but why on earth would you be creating subclasses in that case?
A: Instead of doing @inject mock on abstract class create a spy and create a anonymous implementation in the test class itself and use that to test your abstract class.Better not to do that as there should not be any public method on with you can do unit test.Keep it protected and call those method from implemented classes and test only those classes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "93"
}
|
Q: Inactive session in Oracle by JDBC We have a web service written in Java and is connecting to Oracle database for data extraction. Recently, we encountered too many inactive session in Oracle database from JDBC which is our web service.
We are very sure that all the connection is being closed and set to null after every process.
Can anyone help us in this? Why is it causing inactive session in the database and what can be the solution to this.
Thank you.
A: What, exactly, is the problem?
Normally, the middle tier application server creates a connection pool. When your code requests a connection, it gets an already open connection from the pool rather than going through the overhead of spawning a new connection to the database. When your code closes a connection, the connection is returned to the pool rather than going through the overhead of physically closing the connection. That means that there will be a reasonable number of connections to the database where the STATUS in V$SESSION is "INACTIVE" at any given point in time. That's perfectly normal.
Even under load, most database connections from a middle tier are "INACTIVE" most of the time. A status of "INACTIVE" merely means that at the instant you ran the query, the session was not executing a SQL statement. Most connections will spend most of their time either sitting in the connection pool waiting for a Java session to open them or waiting on the Java session to do something with the data or waiting on the network to transfer data between the machines.
Are you actually getting an error (i.e. ORA-00020: maximum number of processes exceeded)? Or are you just confused by the number of entries in V$SESSION?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Insert a single pixel into HTML5 canvas I want to insert a pixel with a color, and I use this code:
context.fillStyle='RGB('+s[i]+')';
context.fillRect(i,y,1,1)
Is there a shorter way to do it? e.g. in a single line of code?
My main goal is to reduce the amount of code.
A: There really isn't a shorter way to do it besides the method you used above. You don't have to include a fillStyle every time so it essentially is only one line of code to fill a pixel.
Like Petteri pointed out there is another way to fill pixels, it involves manipulating the pixel data directly.
Live Demo
var canvasData = ctx.getImageData(0,0,canvasWidth,canvasHeight);
//color 100,100 red
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 0] = 255;
ctx.putImageData(canvasData,0,0);
also note with the above method you would need to repeat that line 3 times once for each component of the color. For example to set red, green, blue, and the alpha you would use
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 0] //red
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 1] //green
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 2] //blue
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 3] //alpha
granted you could have your data in an array, and just loop through that and color as needed.
A: You can edit the image data of the canvas directly. Here is a good example how to do it: http://beej.us/blog/2010/02/html5s-canvas-part-ii-pixel-manipulation/
A: No, there is no single line of code way to change a single pixel to one color. Well, there sort-of is.
As Petteri noted, there is a way to change each pixel directly, which will probably accomplish what you want. I assume what you want is to change one pixel to one color, and the next pixel to another color, etc.
For instance here is a function for desaturating a canvas. What it does is takes every pixel and averages the RGB values to be color-neutral (have no saturation). The result is a grayscale image.
function grayscale() {
var imageData = ctx.getImageData(0,0,can.width, can.height);
var pixels = imageData.data;
var numPixels = pixels.length;
ctx.clearRect(0, 0, can.width, can.height);
for (var i = 0; i < numPixels; i++) {
var average = (pixels[i*4] + pixels[i*4+1] + pixels[i*4+2]) /3;
// set red green and blue pixels to the average value
pixels[i*4] = average;
pixels[i*4+1] = average;
pixels[i*4+2] = average;
}
ctx.putImageData(imageData, 0, 0);
}
As you can see it is iterating over each pixel. It could be easily mofied to have each pixel changed as a one-liner.
Instead of:
pixels[i*4] = average;
pixels[i*4+1] = average;
pixels[i*4+2] = average;
You'd write:
// Take out 3 values starting at i*4 and add the new RGB for that pixel
pixels.splice(i*4,3,REDVALUE,GREENVALUE,BLUEVALUE);
Which would accomplish what you'd want. It's not the most efficient way under the sun, but it would accomplish your goal :)
A: fillStyle="rgb("+a[m];
fillRect(m,o,1,1);
Someone did with that :P
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can I have multiple run methods in a class? If so, how? I need to have 2 run methods in each object I will instantiate.
I meant a run method for threading.
What i need is more like a race of two cars. each car should have a name and a run() method in a class which extends Thread. I will have to call on the two cars in my main to see which will win. The first or the second. I need help in starting my program
A: Thread t1 = new Thread(new Runnable(){public void run(){...}})
Thread t2 = new Thread(new Runnable(){public void run(){....}})
t1.start();
t2.start();
By using inner class you can achieve multiple run methods in a single class.
A: A class can't contain two methods with the same signature. The signature of a method is its name followed by its arguments.
You may thus have run(int) and run(String) and run() in the same class. This is called method overloading. You can't have two run() methods, because you (and the compiler) could not know which one to execute when calling obj.run().
A: What for? I assume you're talking about implementing the runnable interface, so you want two methods with the signature: public void run();?
Having two methods with the same signature makes no sense; how would you distinguish between them when calling the method from elsewhere in your code?
If you want two different things to happen based on a certain condition when run() is invoked, then you need to add a conditional statement at the start of the method:
public void run() {
if (some_condition) {
// code for the first scenario
} else {
// code for the second
}
}
A: Try:
public class Car extends Thread
{
public String name;
public Car(String name)
{
this.name = name;
}
public void run()
{
//your code
}
}
public static void main(String[] args)
{
Thread car1 = new Car("car1's name");
Thread car2 = new Car("car2's name");
car1.start();
car2.start();
}
You can add your logic into Car.run(), but basically that's how I would do that. In your logic determine when it starts and ends. When both threads finish, you can see which one is the winner. You could also add a while loop and have a field in Car that is a boolean type to determine if it's finished or not.
A: As you asked, you want to know if it's possible to have more than one run() method in a class that implements the Runnable interface, or extends the Thread class.
You can just think about the definition of a thread. A thread is a single instructions block, contained inside a process, that's why a thread is called as a lightweight process. Generally, a thread executes only a specific task.
A new thread is created when the main process of a program needs to do multiple operations in background, such as autosaving or grammar check, if the main program is a word processor, for example. This is the concept of multithreading.
Now, if you read the Runnable or Thread API, you can see that the class that extends Thread class or implements the Runnable class, overrides (in case you are extending Thread class) the run() method or implements the abstract method run() (in case you are implementing the Runnable class).
As other users said, you can use the overloading technique. You can implement another run() method in the class, with a different signature, because it's not a legal practice to have multiple methods with the same signature (it generates confusion for the compiler when you have to invoking one of them) and because it's non sense.
But, remember, at the moment of the starting of the thread, using, for example Thread.start(), then the method will invoke always the run() method you defined previously, with the empty signature. It's possible only to invoke another run method, with a different signature as run(String s), in the main run() method of thread.
For example:
public class Thread implements Runnable{
public void run(){
//instructions
Object o = new Object();
run(o);
}
public void run(Object o){
//other instructions
}
}
public class OtherClass{
Thread t = new Thread();
t.start(); //this will invoke the main run() method!
}
A: you can create two classes and call start method(basic idia) look at the example!
//class Second
public class Second extends Thread {
public void run() {
for (int c = 100; c > 0; c--) {
System.out.println(c);
}
}
}
//class Main
public class Main extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
public static void main(String[] args) throws InterruptedException {
Main thread_1 = new Main();
Second thread_2 = new Second();
// Let's fix concurrency problem
// method 1:
thread_1.start();
thread_1.join();
thread_2.start();
thread_2.join();
//method 2:
//or you can use is alive
/* thread_1.start();
while (thread_1.isAlive()){
System.out.print("");
}thread_2.start();*/
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to overwrite the put() method on a python app engine model? In Appengine, I am trying to have a property value computed automatically and stored with the object.
I have a class, Rectangle, and it has a width, height and area. Obviously the area is a function of width and height, but I want it to be a property because I want to use it for sorting. So I try to modify the put() function to sneak the area in when storing the Rectangle like so:
class Rectangle(db.Model):
width = db.IntegerProperty()
height = db.IntegerProperty()
area = db.IntegerProperty()
def put(self, **kwargs):
self.area = self.width * self.height
super(Rectangle, self).put(**kwargs)
This works when I invoke put() on the Area object directly:
re1 = Rectangle(width=10, height=10)
re1.put()
print re1.area # >> 10
But when I use db.put() (e.g. to save a lot of them at once), this breaks.
re2 = Rectangle(width=5, height=5)
db.put(re2)
print re2.area # >> None
What is the proper way to 'sneak in' the computed value?
A: Don't override put - as you observe, it's fragile, and doesn't get invoked if you call db.put instead of the model's put function.
Fortunately, App Engine provides a ComputedProperty which makes your use-case really easy:
class Rectangle(db.Model):
width = db.IntegerProperty()
height = db.IntegerProperty()
@db.ComputedProperty
def area(self):
return self.width * self.height
A: I agree that ComputedProperty is the way to go for the specific scenario described. However, it could still be useful to overload the put function. For instance, we employ the following code to keep track of all of the callers who are issuing datastore writes so that we can easily debug spikes in writes.
from google.appengine.ext import db
_orig_db_put_async = db.put_async
_orig_db_model_put = db.Model.put
def _new_db_put_async(models, *args, **kwargs):
"""Instrumented version of db.put_async (which db.put also calls)."""
retval = _orig_db_put_async(models, *args, **kwargs)
msg = ['query: %s' % _get_caller()]
# 'models' can be either a single model instance, or a list of them.
try:
for model in models:
msg.append(model.__class__.__name__ + '.<db.put>')
except TypeError:
msg.append(models.__class__.__name__ + '.<db.put>')
instance_cache.increment(' -- '.join(msg))
return retval
def _new_db_model_put(self, *args, **kwargs):
"""Like entity.put() but stores put-stats in the instance cache."""
retval = _orig_db_model_put(self, *args, **kwargs)
msg = ['query: %s' % _get_caller()]
msg.append(self.__class__.__name__ + '.<put>')
instance_cache.increment(' -- '.join(msg))
return retval
This code keeps a count of which codepaths are issuing writes in memcache and then occasionally flushes it out to the logs. The log lines look something like this:
3041: activity_summary.py:312 -- UserData.<put>
Where 3041 is the number of times line 312 of activity_summary.py issued a UserData.put().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Nested sequence in XSD I would like to validate this XML:
<meta>
<house>
<big ... />
<little ... />
<big ... />
</house>
<flat>
<red ... />
<red ... />
<yellow ... />
</flat>
</meta>
I wrote that.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="meta">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="house">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name='big' />
<xs:element name='little' />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="flat">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name='red'/>
<xs:element name='yellow'/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
But that does not validate my example.
Without 'house' or 'flat', and only meta, that worked.
Where could be my problem ?
A: Found !
The solution: add a "xs:choice" for each "xs:sequence", like this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="meta">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:choice>
<xs:element name="house">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:choice>
<xs:element name='big' />
<xs:element name='little' />
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="flat">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:choice>
<xs:element name='red'/>
<xs:element name='yellow'/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using one site for multiple domain in PHP I have one site completely working for one client , now I have some more clients want same thing replicated for them , Is there any way , that I can use this site as base site , as I plan to access this site from there domain and providing database for each client.
I am using PHP and MYSQL.
Thanks for any support , I appreciate your point of view also in this process. do I have right approach
I have been told that there will be SEO issues if I use one site for multiple domain. I have no competent person available which can direct me on domain name linking. I have www.xyzuniversity.com and 85% data is fetching from database. now i have to create abcuniversity.com and I want that I just create new database and ready to use and I think I can make multiple sites like this , if I succeed
Thanks
A: You can point multiple domains to the site. You can get the domain name from the server vars ($_SERVER['HTTP_HOST']) and choose you database through that. Make sure you dont have any absolute links.
A: Put the shared code into a shared directory and give each domain it's own database configuration, so the database configuration is not shared.
Then start your application with the different configuration based on the domain, e.g. by server environment variables like the hostname.
If your design does not support a configuration that can be injected into the application, you need to maintain two code-bases, one for each domain, e.g. in source-code control with one branch per domain.
However I suggest that your code is that modular that it supports configuration for the parts that need configuration according to your needs. If it's not yet, think about coming closer to it and make the changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get ScalaCheck's Arbitrary to always generate some special case values? I'd like to have all my properties always be tested with at least a fixed set of special values in addition to some random values. I'd like to define this in my generator specification, not in every test using that generator type. For instance, if I were generating Ints, I'd like my generator to always generate at least 0, 1 and -1 for each test case. Is this possible?
The best I've come up with so far is to make a sized generator where the smallest n sizes correspond to my n special cases. This is problematic at least because all possible sizes are not tested when the max number of tests is configured to be lower than the max size parameter.
A: First of all, there already is a bias in Scalacheck so that 0, 1, -1, Int.MaxValue and Int.MinValue are very likely to be choosen in addition to other Int values. So, if that's your worry, don't worry about it. Likewise, empty strings are likely to be generated.
But, if you want to reproduce this behavior for something else, use Gen.oneOf or Gen.frequency, perhaps in conjunction with Gen.choose. Since oneOf and frequency take Gen as parameter, you can combine special cases with generic generators.
For example:
val myArb: Arbitrary[Int] = Arbitrary(Gen.frequency(
1 -> -1,
1 -> 0,
1 -> 1,
3 -> Arbitrary.arbInt.arbitrary
))
Does pretty much what you asked for, with 50% chance of arbitrary ints (which will come with the bias I spoke of), and 16.6% for each of -1, 0 and 1.
A: I had the same question today & ended up here so thought I'd add my solution which was to generate Props of my special cases prior to using a Gen, like so:
import org.scalacheck.Gen.{alphaChar, const}
import org.scalacheck.Prop.{forAll, passed}
import org.scalacheck.{Gen, Prop}
// evaluate fn first with some initial values, then with some generated ones
def forAllAfter[A](init: A*)(subsequent: Gen[A])(fn: A => Prop): Prop =
init.foldLeft(passed) { case (p, i) => p && forAll(const(i))(fn) } && forAll(subsequent)(fn)
// example of usage
val prop = forAllAfter('a', 'b', 'c')(alphaChar) { c =>
println(c)
passed
}
The forAllAfter function here first creates Props using Gen.const for each value that must be tested then combines them with props created using a generator of subsequent values to test.
If you're using ScalaTest is that you then need to mix the Checkers trait into your test to evaluate the resultant Prop like so:
import org.scalatest.WordSpec
import org.scalatest.prop.Checkers
import org.scalacheck.Gen.{alphaChar, const}
import org.scalacheck.Prop.{forAll, passed}
import org.scalacheck.{Gen, Prop}
class TestExample extends WordSpec with Checkers {
def forAllAfter[A](init: A*)(subsequent: Gen[A])(fn: A => Prop): Prop =
init.foldLeft(passed) { case (p, i) => p && forAll(const(i))(fn) } && forAll(subsequent)(fn)
val prop: Prop = forAllAfter('a', 'b', 'c')(alphaChar) { c =>
println(c)
passed
}
"Test example" should {
"Work correctly" in {
check(prop)
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Double buffering with Panel Double buffering the whole form can be done by setting the value of the "AllPaintingInWmPaint", "UserPaint" and "DoubleBuffer" ControlStyles to "true" (this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true)).
But this can't happen with a System.Windows.Forms.Panel because the class doesn't allow me to do so. I have found one solution: http://bytes.com/topic/c-sharp/answers/267635-double-buffering-panel-control . I have also tried this: Winforms Double Buffering . It's laggy, even when it's used on a small drawing, I have some custom resources that I'm using in the form and other things because of which I won't turn the whole form into one drawing. And the second one seems to cause problems. Are there other ways to do that?
I'm asking this because I don't want the drawing on the panel to flash all the time when the form is being resized. If there is a way to get rid of the flashing without double buffering, I'll be happy to know.
A: I should have posted my solution a long time ago...
Well, here is my solution:
Bitmap buffer = new Bitmap(screenWidth, screenHeight);//set the size of the image
System.Drawing.Graphics gfx = Graphics.FromImage(buffer);//set the graphics to draw on the image
drawStuffWithGraphicsObject(gfx);//draw
pictureBox1.Image = buffer;//set the PictureBox's image to be the buffer
Makes me feel like a complete idiot for finding this solution years after asking this question.
I have tried this with a Panel, but it has proven to be slower when applying the new image. Somewhere I had read, that it is better to use Panel instead of PictureBox. I don't know if I have to add something to the code to speed things up for the Panel, though.
A: Use a PictureBox if you don't need scrolling support, it is double-buffered by default. Getting a double-buffered scrollable panel is easy enough:
using System;
using System.Windows.Forms;
class MyPanel : Panel {
public MyPanel() {
this.DoubleBuffered = true;
this.ResizeRedraw = true;
}
}
The ResizeRedraw assignment suppresses a painting optimization for container controls. You'll need this if you do any painting in the panel. Without it, the painting smears when you resize the panel.
Double-buffering actually makes painting slower. Which can have an effect on controls that are drawn later. The hole they leave before being filled may be visible for a while, also perceived as flicker. You'll find counter-measures against the effect in this answer.
A: If acceptable you can stop refreshing the panel while resizing and enable it again after, this way you get rid of the ugly flickering.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: get cookie value in the textbox using jquery or javascript I want to see cookie value in the textbox.
I have used this
document.getElementsByName('Custom_Field_Custom2')[0].Value=$.cookie('artname',{ path:'/'});
but that cookies value is not displaying in the textbox.
What I need to do?
A: The "value" attribute is lower-case "v", not "Value".
A: value is case sensitive. Try:
document.getElementsByName('Custom_Field_Custom2')[0].value=$.cookie('artname',{ path:'/'});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to install Delphi 7 on Win 7? I am planning to upgrade my OS to Win 7 (32bit or 64bit). I would like to know whether we can install and run Delphi 7 on Win 7 successfully or not.Share your thoughts on installation of 3rd party components as well.
This would help me to take decision regarding OS up-gradation.
A: I am using Delphi 7.0 on Windows 7, 64 bit, without issues. I have previously installed it on Windows 7, 32 bit and used it without issues as well.
Windows will bother you about an incompatibility when you run the installer. You should probably ensure that anybody using Delphi 7 will have full write access to the folders in Program Files that need to be writeable by Delphi 7.
I have my copy installed in Program Files, and I only use it from an account with admin priveleges, so I can write/modify files inside the Delphi installed folders, without problems.
Some people think it's better to install to C:\Delphi7.
Nobody can know for sure about your components, but you should just try them.
A: I'm using Windows 7 64 bit. When installing delphi 7 it prompt for compatibility issue. Just accept it, click run. Then delphi 7 installed succesfully without problem. I'm installed it on X:/app/Delphi7. 3rd party component added without problem, example i'm adding AlphaSkin component without problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Primary address in Address Does anybody know how to make a address primary in VendTable?
I need to make a new field (checkbox) in the Address tab of VendTable (the datasource for Address in VendTable comes from DirpartyAddressRelationship and Address).
Can anyone let me know step by step how to make a address primary?
There seems to be a lot of relations. I am not sure how this is working.
A: I assume you are asking how to set the primary address using code (not through the user interface).
Use the DirParty class:
static void DirPartyTest(Args _args)
{
VendTable v = VendTable::find("10000");
DirParty d = DirParty::constructFromCommon(v);
;
d.getDirPartyAddress().parmIsPrimary(NoYes::Yes);
Dirparty::updateAddressFromParty(d);
}
Using a specific address:
void setPrimary(Address a)
{
DirParty d = DirParty::constructFromCommon(a);
;
d.getDirPartyAddress().parmIsPrimary(NoYes::Yes);
Dirparty::updateAddressFromParty(d);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: main layout settings gone after layout change I change the layout in my App for different reasons like,a settings or about sub-layout.
But when I go back to the main layout, every setting there is gone: no Buttonlistener is set anymore and the EditTextfields do contain the standart text.
How can I change that behaviour? Is there some other function like onConfigurationChanged(), which handles "inside" calls of a layout in an action?
A: Well due to the fact nobody answered yet and i did figured it out, i'll post my Solution as an answer even though I suspect there might be a more elegant way:
Every time you change a layout using setLayout(...) you first have to save your configuration like described here. Then when you change back to the "old" layout you have to get your resources dynamicly and load and set the old settings like:
edit_text_one = (EditText) findViewById(...);
edit_text_one.setText(settings.getString("text","text"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $.getJSON to receive JSON from API URL Hey I've done about as much research as I can and can't figure out my issue, if anyone could help me out.
Basically have a API set up leading to a JSON doc and something seems to be hanging up the URL and this is what I'm working with so far
$(document).ready(function () {
$('#submit').click(function () {
$.getJSON('http://localhost:41387/api/v0/9405503699300197435172',
function (json) {
console.log(json);
}
);
});
});
I'm taking that the request is being made and completed, but I'm not getting a response.
I know it can't be the code because I used a twitter search URL and got back a response.
There are no errors or exceptions being thrown in the server code.
Any help would be appreciated.
A: From reading your question and comments, I think the reason it works when you use JSONP, might have to do with cross-domain restriction set by the browser.
Make sure the page where you run ajax calls and the ajax URL are on the same domain. In this case, they both need to be on "http://localhost" domain name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Hudson: Builds of multi-module maven project fail, then immediately succeed again I have a multi-module project where the top level project serves both as the parent of the individual modules and as the project that declares the modules. Only this top level project is configured in Hudson (including automatic SVN checkout). The simplified layout is as follows:
ProjectRoot\
|
+---kernel\
| |
| +---pom.xml [ArtifactId=MyProject_kernel parent=MyProject]
|
+---model_foo\
| |
| +---pom.xml [ArtifactId=MyProject_model_foo, parent=MyProject]
|
+---pom.xml [ArtifactId=MyProject, parent=none]
Also, model_foo has a dependency on kernel.
Now, Hudson automatically discovers the kernel and model_foo sub projects, and it usually manages to build everything just fine.
However, each time I make a breaking change, such as create a new class in kernel and use it inside model_foo, I get a failing build for model_foo, followed by one that succeeds. The mail notifications are titled
*
*Build failed in Hudson: MyProject » MyProject Model Foo #1545
*Hudson build is back to normal : MyProject » MyProject Model Foo #1546
Why is that? I suspect it might have to do with the fact that the MyProject pom.xml is both the multi-module project and the parent of its modules, but before changing that I would like to know whether it's actually going to help.
I use Hudson 2.1.0.
Update
This is the log of a failed build of the web module (equals model_foo in the diagram above). The build for the MyProject root project had the same build number, and succeeded.
I stripped out the actual compiler errors, which are exactly the same as if the newly introduced class was missing.
Started by upstream project "MyProject" build number 1545
Found mavenVersion 2.0.9 from file jar:file:/home/builder/opt/apache-maven-2.0.9/lib/maven-2.0.9-uber.jar!/META-INF/maven/org.apache.maven/maven-core/pom.properties
$ /home/builder/opt/jdk1.5.0_22//bin/java -Xmx1024m -Xms512m -cp /home/builder/var/hudson/plugins/maven-plugin/WEB-INF/lib/maven-agent-2.1.0.jar:/home/builder/opt/apache-maven-2.0.9/boot/classworlds-1.1.jar hudson.maven.agent.Main /home/builder/opt/apache-maven-2.0.9 /home/builder/opt/apache-tomcat-6.0.24/webapps/hudson/WEB-INF/lib/hudson-remoting-2.1.0.jar /home/builder/var/hudson/plugins/maven-plugin/WEB-INF/lib/maven-interceptor-2.1.0.jar 48555
<===[HUDSON REMOTING CAPACITY]===> channel started
Executing Maven: -N -B -f <http://ciserver:8080/hudson/job/MyProject/com.mycompany.myproject$web/ws/pom.xml> clean deploy -Dworkspace.path=/home/builder/var/hudson/jobs/MyProject/workspace/ -Droot.project.name=MyRoot -e
+ Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building MyProject
[INFO] task-segment: [clean, deploy]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean]
[INFO] Deleting directory <http://ciserver:8080/hudson/job/MyProject/com.mycompany.myproject$web/ws/target>
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Compiling 945 source files to <http://ciserver:8080/hudson/job/MyProject/com.mycompany.myproject$web/ws/target/classes>
[HUDSON] Archiving <http://ciserver:8080/hudson/job/MyProject/com.mycompany.myproject$web/ws/pom.xml> to /home/builder/var/hudson/jobs/MyProject/modules/com.mycompany.myproject$web/builds/2011-09-27_13-32-33/archive/com.mycompany.myproject/web/1.1-SNAPSHOT/pom.xml
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure
{{{compiler failure here}}}
[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.BuildFailureException: Compilation failure
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:579)
{{{stacktrace omitted}}}
Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:516)
{{{stacktrace omitted}}}
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 minute 7 seconds
[INFO] Finished at: Tue Sep 27 13:33:42 CEST 2011 [INFO] Final Memory: 53M/508M
[INFO] ------------------------------------------------------------------------
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Unable to connect to apns from php I am having trouble connecting to the apple apns from my production machine, its a vps hosting.
*
*I asked the hosting technical assistance and they said that they do not block outgoing connections on any port and that the logs show nothing of this problem and they have no idea what might cause this, so no help there.
*This works on my local dev machine and the iPhone gets the notifications.
*extension=php_openssl.dll is enabled in the php.ini file on both machines.
*on both machines telnet gives a black screen and not a response like i saw on some threads here.
The code im using is:
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 10, STREAM_CLIENT_CONNECT, $streamContext);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', $deviceToken) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
fclose($apns);
And the error i get are:
Warning: stream_socket_client(): SSL: crypto enabling timeout in test.php on line 116
Warning: stream_socket_client(): Failed to enable crypto in test.php on line 116
Warning: stream_socket_client(): unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in test.php on line 116
Warning: fwrite() expects parameter 1 to be resource, boolean given in test.php on line 118
Warning: fclose() expects parameter 1 to be resource, boolean given in test.php on line 119
The last 2 errors are a given as the connection fails but the first 3 i can't resolve.
Any help will be appritiated :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery objects and form.serialize Here is my example:
var form= $(".anyclass form");
var sf = form.serialize();
$.post(form[0].action,
Let's suppose that there is only one form in the page that fits the criteria.
Why I need to access the action property using [0]?
Why the .serialize() is done without [0]?
Sorry about this newbie question.
A: I think you want to do it like:
$.post(form.attr('action'));
By the way: you are getting all forms within an element with the class .anyclass. This will return multiple forms (if present). Ýou'll be better of if you gave the form some id and get it that way: $('#myForm').
A: Your form variable returned from $(...) is a jQuery object that potentially includes references to many form elements.
To access the underlying native DOM elements within that object you either need to use array notation (as above) or form.get(0).
As for the differences in usage, .serialize() is a method of the jQuery object, so has to be called on form.
However .action is a DOM attribute, so you need to use the native DOM element to access it, although you could alternatively have used:
form.attr('action')
A: the [0] just gives you the straight DOM Object for the Form,
form === jquery object
form[0] === DOM object
A: That's because .serialize() is a jQuery method that applies for all matched elements.
I haven't looked at the source, but I bet there's something like this:
return this.each(function(i, val){
// do stuff
})
And when you do form[0].action, you're actually returning the first element (the native DOM element) in the set of matched elements, and then accessing it's native property
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error with Directory.Services when on production The following code works fine in Visual Studio Development enviroment on my local machine. However when I move the files to a Windows 2008 R2 IIS 7.5 machine I get the following error:
[DirectoryServicesCOMException (0x80072020): An operations error
occurred. ] _Default.GetFullName(String strLoginName, String&
STR_FIRST_NAME, String& STR_LAST_NAME, String& STR_DISPLAY_NAME,
String& STR_MAIL, String& STR_OFFICE_PHONE, String& STR_ADDRESS) in
c:\AuthTest\Default.aspx.cs:87 _Default.Page_Load(Object sender,
EventArgs e) in c:\AuthTest\Default.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object
o, Object t, EventArgs e) +25 System.Web.UI.Control.LoadRecursive()
+71 System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+3064
I have Windows Authentication enabled on IIS so I'm not sure if I'm missing something else. Both my local machine and the web server are in the same domain.
Here is my code:
using System;
using System.DirectoryServices;
using System.Web.Hosting;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Gets the extracted User Name using a method.
string strUserID = ExtractUserName(User.Identity.Name.ToString());
string STR_FIRST_NAME;
string STR_LAST_NAME;
string STR_DISPLAY_NAME;
string STR_MAIL;
string STR_OFFICE_PHONE;
string STR_ADDRESS;
GetFullName(strUserID, out STR_FIRST_NAME, out STR_LAST_NAME, out STR_DISPLAY_NAME,
out STR_MAIL, out STR_OFFICE_PHONE, out STR_ADDRESS);
lblHello.Text = "Your User ID is: " + strUserID;
TextBox1.Text =
"Your name is: " + STR_FIRST_NAME + " " + STR_LAST_NAME + Environment.NewLine +
"Display Name: " + STR_DISPLAY_NAME + Environment.NewLine +
"Email address: " + STR_MAIL + Environment.NewLine +
"Office Phone: " + STR_OFFICE_PHONE + Environment.NewLine +
"Address: " + STR_ADDRESS;
}
//Retrives User Name from DomainName\\UserName
private static string ExtractUserName(string path)
{
string[] userPath = path.Split(new char[] { '\\' });
return userPath[userPath.Length - 1];
}
public static string GetFullName(string strLoginName,
out string STR_FIRST_NAME,
out string STR_LAST_NAME,
out string STR_DISPLAY_NAME,
out string STR_MAIL,
out string STR_OFFICE_PHONE,
out string STR_ADDRESS)
{
string userName = ExtractUserName(strLoginName);
SearchResult result = null;
using (HostingEnvironment.Impersonate())
{
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(SAMAccountName={0})", userName);
search.PropertiesToLoad.Add("cn");
STR_FIRST_NAME = "";
STR_LAST_NAME = "";
STR_DISPLAY_NAME = "";
STR_MAIL = "";
STR_OFFICE_PHONE = "";
STR_ADDRESS = "";
try
{
result = search.FindOne();
foreach (System.Collections.DictionaryEntry direntry in result.Properties)
{
STR_FIRST_NAME = result.GetDirectoryEntry().Properties["givenName"].Value.ToString();
STR_LAST_NAME = result.GetDirectoryEntry().Properties["SN"].Value.ToString();
STR_DISPLAY_NAME = result.GetDirectoryEntry().Properties["DisplayName"].Value.ToString();
STR_MAIL = result.GetDirectoryEntry().Properties["mail"].Value.ToString();
STR_OFFICE_PHONE = result.GetDirectoryEntry().Properties["telephoneNumber"].Value.ToString();
STR_ADDRESS = result.GetDirectoryEntry().Properties["streetAddress"].Value.ToString();
}
return null;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Again everything works fine on my local machine in the VS Testing enviroment. I'm probably missing some kind of configuration in IIS?
Thanks in Advance.
A: First thing would be to check that the IIS application pool identity has the correct permissions to AD.
Also as a side note here is something to read regarding your catch { throw ex}
http://www.tkachenko.com/blog/archives/000352.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: where is file entry.S in v2.6.39.4? I am studying system call in linux with source code in version 2.6.39.4.
Books said that system call is implementd in entry.S, located in arch/i386/kernel/entry.S,
but I can't find that file in v2.6.39.4.
so which file implement system call in my version? Any difference with old ones?
A: The information in your books seems to be outdated.
You should find what you're looking for in arch/x86/kernel/entry_32.S and arch/x86/kernel/entry_64.S.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Problem with write delegated method I have a problem with adding parameters to EventHandler.
I have a control when user select message and choose to who he want to send it.
I need to handler OnConfirmForwarClosed add in some way variable item.
How can I do it?
private void inboxContextMenu_ItemClick(object sender, Telerik.Windows.RadRoutedEventArgs e)
{
var item = (RadMenuItem)e.Source;
RadWindow.Confirm("Do you want forward this message to item.DataContext.HandlerName ?", OnConfirmForwarClosed);
}
private void OnConfirmForwarClosed(object sender, WindowClosedEventArgs e)
{
if (e.DialogResult == true)
{
//here I need item from caller
}
}
EDIT
I need a result which I can get by this solution:
RadWindow.Confirm("Do you want forward this message to item.DataContext.HandlerName ?",(s,ea)=>
{
if(ea.DialogResult==true)
{
MessageBox.Show((item.DataContext as Handler).HandlerId.ToString());
}
});
A: If i understand your question correctly, you don't want to "lift" the local variable into lambda, such as...
void inboxContextMenu_ItemClick(object sender, Telerik.Windows.RadRoutedEventArgs e) {
var item = (RadMenuItem)e.Source;
RadWindow.Confirm(
"Do you want forward this message to item.DataContext.HandlerName ?",
(sender, e) => {
if (e.DialogResult == true) {
// You can use 'item' here directly.
}
}
);
}
...and instead you want to keep the OnConfirmForwarClosed (presumably to subscribe to events not shown here). If that's correct, then you have couple of options:
1.
You could just arrange your methods differently:
void inboxContextMenu_ItemClick(object sender, Telerik.Windows.RadRoutedEventArgs e) {
var item = (RadMenuItem)e.Source;
RadWindow.Confirm(
"Do you want forward this message to item.DataContext.HandlerName ?",
(sender, e) => OnConfirmForwarClosedImp(sender, e, item)
);
}
void OnConfirmForwarClosedImp(object sender, WindowClosedEventArgs e, RadMenuItem item) {
if (e.DialogResult == true) {
if (item != null) {
// Use 'item'.
}
else {
// OnConfirmForwarClosed was called from somewhere else.
}
}
}
void OnConfirmForwarClosed(object sender, WindowClosedEventArgs e) {
OnConfirmForwarClosedImp(sender, e, null);
}
2.
Set the object field:
void inboxContextMenu_ItemClick(object sender, Telerik.Windows.RadRoutedEventArgs e) {
item = (RadMenuItem)e.Source;
try {
RadWindow.Confirm(
"Do you want forward this message to item.DataContext.HandlerName ?",
OnConfirmForwarClosed
);
}
finally {
item = null;
}
}
RadMenuItem item = (RadMenuItem)e.Source;
void OnConfirmForwarClosed(object sender, WindowClosedEventArgs e) {
if (e.DialogResult == true) {
if (item != null) {
// Use 'this.item'.
}
else {
// OnConfirmForwarClosed was called from somewhere else.
}
}
}
3.
Co-opt one of the existing OnConfirmForwarClosed parameters:
void inboxContextMenu_ItemClick(object sender, Telerik.Windows.RadRoutedEventArgs e) {
var item = (RadMenuItem)e.Source;
RadWindow.Confirm(
"Do you want forward this message to item.DataContext.HandlerName ?",
(sender, e) => OnConfirmForwarClosed(item, e)
);
}
void OnConfirmForwarClosed(object sender, WindowClosedEventArgs e) {
if (e.DialogResult == true) {
var item = sender as RadMenuItem;
if (item != null) {
// Use 'item'.
}
else {
// OnConfirmForwarClosed was called from somewhere else.
}
}
}
Etc, etc...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery hover issue on mouseout I am using the jQuery variable "mouseover" and "mouseout" to show a DIV element when hovering over another.
http://74.54.17.66/~adbuynet/case-studies/ - If you hover over "Call to Action" in the top right, you see a dropdown.
The problem is, that when mousing over the dropdown itself, the dropdown starts acting funky and does not stay open. My jQuery code is:
$("#call-to-action").mouseover(function(e) {
$("#call-to-action-dropdown").show("slide", { direction: "up" }, 200);
e.stopPropagation();
});
$("#call-to-action").mouseout(function(e) {
$("#call-to-action-dropdown").hide("slide", { direction: "up" }, 200);
});
});
What mistake have I made please?
A: Use mouseenter and mouseleave instead of mouseover and mouseout. See http://api.jquery.com/mouseenter/.
(You’ll almost never want to use mouseover/mouseout, and when you do, you’ll know it.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Grails - Pass a link as a parameter I have implemented an email sharing service in my web application. People can click on the email button and access a form with which they can send emails to whom they want.
I would like to set a default subject and body.
In the default body text of the email, I would like to pass the link of the page people want to share. Surely it is possible to do so but I do not manage to.
So far it has been a dead end to try to pass the link in the value argument of my text editor. I cannot think if any other way to do it.
Any suggestion greatly appreciated.
A: You can get the location of the current page using JavaScript with document.URL Then you can just set a hidden field on your form and submit it with your email request. For example:
<html>
<head>
<script type="text/javascript">
function setLocation(urlField) {
urlField.value = document.URL
}
</script>
</head>
<body>
<form id="exampleForm" name="exampleForm" action="#">
<input type="text" id="url" name="url"/>
<input name="submit" value="submit" type="button" onclick="setLocation(this.form.url);" />
</form>
</body>
</html>
A: The same way you pass data to any other fields that you want to populate.
For example your controller returns a model emailShare that contains subject, body and url etc
In your gsp, lets say you have a textarea for the body of your email,
<g:textField name="emailSubject" value="${emailShare.subject}" />
<g:textArea name="emailBody" value="${emailShare.url}" rows="5" cols="40"/>
This will set the url as the default text in the textarea, which can also be further edited to add more text.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find Duplicates using Rank Over Partition The following SQL works in identifying unique phones when there is a disparity in LastDate.
But if duplicate phones have the exact same LastDate it does not work.
Any ideas will be appreciate it.
SELECT * FROM
(
SELECT ID, Phone, [LastDate]
,RANK() OVER (PARTITION BY Phone ORDER BY [LastDate]) AS 'RANK',
COUNT(Phone) OVER (PARTITION BY Phone) AS 'MAXCOUNT'
FROM MyTable
WHERE Groupid = 5
) a
WHERE [RANK] = [MAXCOUNT]
A: Change the RANK for ROW_NUMBER.
SELECT *
FROM ( SELECT ID, Phone, [LastDate],
ROW_NUMBER() OVER (PARTITION BY Phone ORDER BY [LastDate]) AS 'RANK',
COUNT(Phone) OVER (PARTITION BY Phone) AS 'MAXCOUNT'
FROM MyTable
WHERE Groupid = 5) a
WHERE [RANK] = [MAXCOUNT]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Best Practice? Restart Centos service via ssh securely? I have a need to restart a CentOS service remotely via ssh during an automated, unattended process (executing a build on some software from a build server), but am unsure how to best implement security. Help is needed! ;-)
Environment:
Running an ssh login on a remote box, I want to execute on my server something like:
/sbin/service jetty restart.
The ssh call is being made during a maven build process (probably doesn't affect anything, really).
I want the ssh session to login with a user that has practically zero permissions on the server except to execute the above.
I can set up shared key access for the ssh session.
Thanks!
A: Good idea to use an ssh key. You can then use a 'forced command' for that particular key, so it won't be able to run any other commands. See http://www.eng.cam.ac.uk/help/jpmg/ssh/authorized_keys_howto.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ping with php phar i want to use this script to do ping without using the exec(); or the commands that similar to it.
the problem is i get these errors:
Strict Standards: Non-static method Net_Ping::factory() should not be
called statically in C:\xampp\htdocs\test.php on line
3
Strict Standards: Non-static method Net_Ping::_setSystemName() should
not be called statically in C:\xampp\php\PEAR\Net\Ping.php on line 141
Strict Standards: Non-static method Net_Ping::_setPingPath() should
not be called statically in C:\xampp\php\PEAR\Net\Ping.php on line 143
Strict Standards: Non-static method PEAR::isError() should not be
called statically in C:\xampp\htdocs\test.php on line
4
the code on test.php
<?php
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping)) {
echo $ping->getMessage();
} else {
$ping->setArgs(array('count' => 2));
var_dump($ping->ping('example.com'));
}
?>
A: Nothing wrong, the PEAR component is just not fit for E_STRICT. The code you have is okay, but the PEAR code doesn't say the method is static, so PHP will emit an E_STRICT warning. That's not something you can really change, but you can opt to ignore it, by adjusting your error_reporting settings.
<?php
// before PEAR stuff.
$errLevel = error_reporting( E_ALL );
// PEAR stuff.
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping)) {
echo $ping->getMessage();
} else {
$ping->setArgs(array('count' => 2));
$result = $ping->ping('example.com');
}
// restore the original error level.
error_reporting( $errLevel );
var_dump( $result );
A: Here is a ping class I wrote last year when I needed to do this on a system that didn't have PEAR.
Example usage:
$ping = new ping();
if (!$ping->setHost('google.com')) exit('Could not set host: '.$this->getLastErrorStr());
var_dump($ping->send());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Constructor chaining I have following code:
public MapReader(string fName) {
FileName = fName;
}
public MapReader(){
Console.WriteLine("Input valid file name:");
string name = Console.ReadLine();
this(name);
}
Apparently this is Java approach, which is not working in C#. Is there any option which doesn't need added method for initialization?
A: You can't do this in C#. You will have to set the property in the other constructor.
Ideally, you should separate out the dependency on the console.
A: In C# you couldn' use that approach.
Try this:
private void setParam(string name) {
FileName = name;
}
public MapReader(string fName) {
setParam(fName);
}
public MapReader() {
Console.WriteLine("Input valid file name:");
string name = Console.ReadLine();
setParam(name);
}
A: Although I agree with others that having a dependency on the Console is probably not best for this class, this would work:
class MapReader
{
public string FileName { get; private set; }
public MapReader(string fName)
{
FileName = fName;
}
public MapReader() : this(ObtainNameFromConsole())
{
}
private static string ObtainNameFromConsole()
{
Console.WriteLine("Input valid file name:");
return Console.ReadLine();
}
}
A: Maybe something like this?
public MapReader(string fName)
{
FileName = fName;
}
public static MapReader FromConsole()
{
Console.WriteLine("Input valid file name:");
string name = Console.ReadLine();
return new MapReader(name);
}
A: I don't quite like the approach of having a side effecting constructor like that, you could simulate the same thing like this:
public class MapReader
{
private string fileName;
private MapReader(Func<string> fileName)
{
this.fileName = fileName();
}
public MapReader(string fileName) : this(() => fileName)
{
}
public MapReader() : this(() =>
{
Console.WriteLine("Input valid file name:");
return Console.ReadLine();
})
{
}
}
A: You can to do so:
public MapReader(string fName) {
if (fName == null)
{
Console.WriteLine("Input valid file name:");
fName = Console.ReadLine();
}
FileName = fName;
}
public MapReader() : this (null) {}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Suppress "The method does not override the inherited method since it is private to a different package." How can I suppress the following error with the @SuppressWarning annotation?
The method Foo.trololo() does not override the inherited method from Bar since it is private to a different package
So far as I can tell the only way is to blanket the entire method with @SuppressWarning("all") which I would prefer not to do.
For clarification: The naming and scope of both methods is a deliberate choice and the two classes were deliberately put into different packages knowing the methods would not be visible to each other. I am merely looking to declare that I acknowledge what I am doing and would not like to be warned of it.
A: What it means (you probably know this already)
It means that, even though your method has the same name as a (non-private) method in the super class, it doesn't override that method.
Regarding the warning message
This is an Eclipse-specific warning. Nothing in the language spec says that it should produce this warning. It's an "IDE-specific feature" if you so like. Therefore there is no "generic" way of suppressing the message.
(Note for instance that javac does not produce this warning.)
How to disable this warning (in Eclipse)
(I know you are not looking for this, but some other visitor of this page may!)
To disable this warning, you go to
Window -> Preferences -> Java -> Compiler -> Errors / Warnings
and set "Method does not override package visible method" to "Ignore".
A: This warning means that you have a package-private method trololo in Bar, and a trololo method in Foo, which extends Bar, but is not in the same package.
If your goal is to override the Bar.trololo method with Foo.trololo, then the Bar.trololo method must be made protected. If your goal is to have two different methods, it would be better to name the second one tralala to make it much clearer and avoid confusion.
A: If you want to Suppress Warning a specific project, in the Eclipse Package Explorer, right click the project -> Properties -> Java Compiler -> Errors/Warnings then Check "Enable project specific settings" -> Name shadowing and conflicts then set "Method does not override package visible method" to "Ignore". Rebuild the project and warning will go away. Done!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Working with TIFFs (import, export) in Python using numpy I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)
I couldn't find any documentation on PIL methods concerning TIFF. I tried to figure it out, but only got "bad mode" or "file type not supported" errors.
What do I need to use here?
A: You can also use pytiff of which I am the author.
import pytiff
with pytiff.Tiff("filename.tif") as handle:
part = handle[100:200, 200:400]
# multipage tif
with pytiff.Tiff("multipage.tif") as handle:
for page in handle:
part = page[100:200, 200:400]
It's a fairly small module and may not have as many features as other modules, but it supports tiled TIFFs and BigTIFF, so you can read parts of large images.
A: There is a nice package called tifffile which makes working with .tif or .tiff files very easy.
Install package with pip
pip install tifffile
Now, to read .tif/.tiff file in numpy array format:
from tifffile import tifffile
image = tifffile.imread('path/to/your/image')
# type(image) = numpy.ndarray
If you want to save a numpy array as a .tif/.tiff file:
tifffile.imwrite('my_image.tif', my_numpy_data, photometric='rgb')
or
tifffile.imsave('my_image.tif', my_numpy_data)
You can read more about this package here.
A: I use matplotlib for reading TIFF files:
import matplotlib.pyplot as plt
I = plt.imread(tiff_file)
and I will be of type ndarray.
According to the documentation though it is actually PIL that works behind the scenes when handling TIFFs as matplotlib only reads PNGs natively, but this has been working fine for me.
There's also a plt.imsave function for saving.
A: Using cv2
import cv2
image = cv2.imread(tiff_file.tif)
cv2.imshow('tif image',image)
A: You could also use GDAL to do this. I realize that it is a geospatial toolkit, but nothing requires you to have a cartographic product.
Link to precompiled GDAL binaries for windows (assuming windows here)
Link
To access the array:
from osgeo import gdal
dataset = gdal.Open("path/to/dataset.tiff", gdal.GA_ReadOnly)
for x in range(1, dataset.RasterCount + 1):
band = dataset.GetRasterBand(x)
array = band.ReadAsArray()
A: PyLibTiff worked better for me than PIL, which as of January 2023 still doesn't support color images with more than 8 bits per color.
from libtiff import TIFF
tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the current TIFF directory as a numpy array
image = tif.read_image()
# read all images in a TIFF file:
for image in tif.iter_images():
pass
tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)
You can install PyLibTiff with
pip3 install numpy libtiff
The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.
A: First, I downloaded a test TIFF image from this page called a_image.tif. Then I opened with PIL like this:
>>> from PIL import Image
>>> im = Image.open('a_image.tif')
>>> im.show()
This showed the rainbow image. To convert to a numpy array, it's as simple as:
>>> import numpy
>>> imarray = numpy.array(im)
We can see that the size of the image and the shape of the array match up:
>>> imarray.shape
(44, 330)
>>> im.size
(330, 44)
And the array contains uint8 values:
>>> imarray
array([[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
...,
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246]], dtype=uint8)
Once you're done modifying the array, you can turn it back into a PIL image like this:
>>> Image.fromarray(imarray)
<Image.Image image mode=L size=330x44 at 0x2786518>
A: In case of image stacks, I find it easier to use scikit-image to read, and matplotlib to show or save. I have handled 16-bit TIFF image stacks with the following code.
from skimage import io
import matplotlib.pyplot as plt
# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(img,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)
A: if you want save tiff encoding with geoTiff. You can use rasterio package
a simple code:
import rasterio
out = np.random.randint(low=10, high=20, size=(360, 720)).astype('float64')
new_dataset = rasterio.open('test.tiff', 'w', driver='GTiff',
height=out.shape[0], width=out.shape[1],
count=1, dtype=str(out.dtype),
)
new_dataset.write(out, 1)
new_dataset.close()
for more detail about numpy 2 GEOTiff .you can click this: https://gis.stackexchange.com/questions/279953/numpy-array-to-gtiff-using-rasterio-without-source-raster
A: I recommend using the python bindings to OpenImageIO, it's the standard for dealing with various image formats in the vfx world. I've ovten found it more reliable in reading various compression types compared to PIL.
import OpenImageIO as oiio
input = oiio.ImageInput.open ("/path/to/image.tif")
A: Another method of reading tiff files is using tensorflow api
import tensorflow_io as tfio
image = tf.io.read_file(image_path)
tf_image = tfio.experimental.image.decode_tiff(image)
print(tf_image.shape)
Output:
(512, 512, 4)
tensorflow documentation can be found here
For this module to work, a python package called tensorflow-io has to installed.
Athough I couldn't find a way to look at the output tensor (after converting to nd.array), as the output image had 4 channels. I tried to convert using cv2.cvtcolor() with the flag cv2.COLOR_BGRA2BGR after looking at this post but still wasn't able to view the image.
A: no answers to this question did not work for me. so i found another way to view tif/tiff files:
import rasterio
from matplotlib import pyplot as plt
src = rasterio.open("ch4.tif")
plt.imshow(src.read(1), cmap='gray')
the code above will help you to view the tif files. also check below to be sure:
type(src.read(1)) #see that src.read(1) is a numpy array
src.read(1) #prints the matrix
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "133"
}
|
Q: Dropdown Sort MySQL Query with Javascript OnChange? Below is a preview of what I have. What I want to do is when someone changes the drop down to "Cooper" then only Cooper brand tires will show, it will have to update my MySQL query. If they change it back to "All Tire Brands" then it does a quick refresh and shows every one of them.
Is something like this possible? If someone can point me in the right directions I would really appreciate it.
Thanks!
A: $("#selectMenuId").bind("change", function(event) {
var selectedID = event.target.value;
$.post("path/to/your/serverSide.php", {
selectionID: selectedID
}, function(data) {
$("#myContainer").html(data);
});
});
And on serverSide.php
you would want to do something like this
if(isset($_POST["selectionID"])) {
$sql = "SELECT * FROM someTable WHERE category_id = " . $_POST["selectionID"] . ";
// run your query, build your new results, echo them back.
}
The basic id is you are passing the selected value to the serverSide page, running a query against the DB with the (i would assume some sort of category ID) value, build your new resultset and return it. Without knowing how you are building the list currently I wouldn't be able to help further.
Edit
To show a loader you can do something like this?
$("#selectMenuId").bind("change", function(event) {
var selectedID = event.target.value;
var container = $("#myContainer");
container.html("Loading...");
$.post("path/to/your/serverSide.php", {
selectionID: selectedID
}, function(data) {
container.html(data);
});
});
Or you can have a overlay with a loading gif, and just $("#loadingLayer").show()/.hide() for that.
as for the default selection.. you could (using your ServerSide language) have the default view rendered on the page. or you can have it collected via JS the same way you have the rest of your results... just wait for the list to load and trigger a 'change'
$("#selectMenuId").bind("change", function(event) {
var selectedID = event.target.value;
var container = $("#myContainer");
container.html("Loading...");
$.post("path/to/your/serverSide.php", {
selectionID: selectedID
}, function(data) {
container.html(data);
});
}).trigger("change");
Hope this helps!
A: Sure, it's possible.
You'll need to assign a javascript event listener to the popup. When a visitor selects an item from the popup, you'd use an AJAX call to ask a web service on the server which items to display. (Your Javascript framework of choice -- jQuery, Prototype, or others -- will help with this.) Then you'd replace the search result items in the DOM with those that the web service returned.
That's a high-level conceptual view. If you'd like more details, here's an article that's pretty close to what you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS Floating Div's & Alignment I am trying to create a control which contains two listboxes with add/remove buttons to move items from one list to the other. Typically I would do this using a table, but I am trying to follow css standards and use divs.
I have the listboxes aligned perfectly, but I can't figure out how to set up the buttons between them.
This is my html (updated to show rendered html):
<div id="dealsummary-ladderlist">
<form action="/Reporting/DealSummaryComparison" method="post">
<div id="available">
<div><strong>Available</strong></div>
<div id="available-items">
<select id="ItemsToSelect" multiple="multiple" name="ItemsToSelect" size="30">
<option value="16">Item 1</option>
<option value="17">Item 2</option>
<option value="21">Item 3</option>
<option value="22">Item 4</option>
<option value="23">Item 5</option>
<option value="24">Item 6</option>
<option value="25">Item 7</option>
</select>
</div>
</div>
<div id="add-remove">
<div><input type="button" value=">>" /></div>
<div><input type="button" value="<<" /></div>
</div>
<div id="selected">
<div><strong>Selected</strong></div>
<div id="selected-items">
<select id="ItemsToDeselect" multiple="multiple" name="ItemsToDeselect" size="30"></select>
</div>
</div>
<div style="clear:both;"></div>
<br /><br />
<center>
<p>
<input type="submit" value="Generate Report" />
</p>
</center>
</form>
</div>
This is what I have for css:
#add-remove {
/* want to center on page */
float: left;
width: 10%;
}
#add-remove div {
/* want to add even spacing between buttons */
}
#available {
float: left;
width: 45%;
}
#selected {
float: right;
width: 45%;
}
#available #available-items,
#selected #selected-items {
margin: 1em 0 0 0;
}
#available #available-items select,
#selected #selected-items select {
width: 100%;
font-size: 10pt;
}
How would I achieve the centering and even spacing of the arrow buttons using css?
A: If you know the precise width and height of the <div id="add-remove"> element, you could wrap the whole thing in a relatively-positioned <div> and use absolute positioning with negative margins like so:
<div id="relativeWrapper"> <!-- added this -->
<div id="available">
<!-- ... snip ... -->
</div>
<div id="add-remove">
<div><input type="button" value=">>" /></div>
<div><input type="button" value="<<" /></div>
</div>
<div id="selected">
<!-- ... snip ... -->
</div>
<div style="clear:both;"></div>
</div>
<!-- ... etc ... -->
With the CSS:
div#relativeWrapper {
position: relative;
}
div#add-remove {
position: absolute;
top: 50%;
left: 50%;
width: 80px;
margin-left: -40px;
height: 64px;
margin-top: -32px;
}
Setting both top and left to 50% and margin-left to half the value of width and margin-top to half the value of height will horizontally and vertically center an absolutely-positioned element within its relative parent.
Vertical-centering is difficult to achieve; you can use display: inline-block; vertical-align: middle;, but inline-block is not supported by all browsers. Alternatively, using display: table-cell; vertical-align: middle; tends to work.
Incidentally, the <center> element is deprecated. Use <div style="text-align: center;"> or simply <p style="text-align: center;"> instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Displaying an image from SQL Server in asp.net I am need to display an image on my asp.net page, which is stored as an image data type in SQL Server. I am looking at this post, display/retrieve image from sql database in vb.net, however, how can I display that image in a <td> element?
A: <td> tags can't be used to display images unless you put an <img> element inside it. With that said, this is how you display an image in VB.NET from code behind:
Having this type of markup in your aspx page:
<td>
<img src="" runat="server" id="imageFromDB" />
...
You can do this in code behind:
Dim imageBytes() as Byte= ... // You got the image from the db here...
//jpg is used as an example on the line below.
//You need to use the actual type i.e. gif, jpg, png, etc.
//You can do imageFromDB simply because you set runat="server" on the markup
imageFromDB.src = String.Format("data:image/{0};base64,
{1}","jpg",Convert.ToBase64String(imageBytes)
And this will render your image on the page.
I hope I've given you enough information here.
A: Referring to the sample in the answer you mention:
<td><img src="PathToYourHttpHandler?id=ID_OF_YOUR_IMAGE" /></td>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Efficient Way to Create Numpy Arrays from Binary Files I have very large datasets that are stored in binary files on the hard disk. Here is an example of the file structure:
File Header
149 Byte ASCII Header
Record Start
4 Byte Int - Record Timestamp
Sample Start
2 Byte Int - Data Stream 1 Sample
2 Byte Int - Data Stream 2 Sample
2 Byte Int - Data Stream 3 Sample
2 Byte Int - Data Stream 4 Sample
Sample End
There are 122,880 Samples per Record and 713 Records per File. This yields a total size of 700,910,521 Bytes. The sample rate and number of records does vary sometimes so I have to code for detection of the number of each per file.
Currently the code I use to import this data into arrays works like this:
from time import clock
from numpy import zeros , int16 , int32 , hstack , array , savez
from struct import unpack
from os.path import getsize
start_time = clock()
file_size = getsize(input_file)
with open(input_file,'rb') as openfile:
input_data = openfile.read()
header = input_data[:149]
record_size = int(header[23:31])
number_of_records = ( file_size - 149 ) / record_size
sample_rate = ( ( record_size - 4 ) / 4 ) / 2
time_series = zeros(0,dtype=int32)
t_series = zeros(0,dtype=int16)
x_series = zeros(0,dtype=int16)
y_series = zeros(0,dtype=int16)
z_series = zeros(0,dtype=int16)
for record in xrange(number_of_records):
time_stamp = array( unpack( '<l' , input_data[ 149 + (record * record_size) : 149 + (record * record_size) + 4 ] ) , dtype = int32 )
unpacked_record = unpack( '<' + str(sample_rate * 4) + 'h' , input_data[ 149 + (record * record_size) + 4 : 149 + ( (record + 1) * record_size ) ] )
record_t = zeros(sample_rate , dtype=int16)
record_x = zeros(sample_rate , dtype=int16)
record_y = zeros(sample_rate , dtype=int16)
record_z = zeros(sample_rate , dtype=int16)
for sample in xrange(sample_rate):
record_t[sample] = unpacked_record[ ( sample * 4 ) + 0 ]
record_x[sample] = unpacked_record[ ( sample * 4 ) + 1 ]
record_y[sample] = unpacked_record[ ( sample * 4 ) + 2 ]
record_z[sample] = unpacked_record[ ( sample * 4 ) + 3 ]
time_series = hstack ( ( time_series , time_stamp ) )
t_series = hstack ( ( t_series , record_t ) )
x_series = hstack ( ( x_series , record_x ) )
y_series = hstack ( ( y_series , record_y ) )
z_series = hstack ( ( z_series , record_z ) )
savez(output_file, t=t_series , x=x_series ,y=y_series, z=z_series, time=time_series)
end_time = clock()
print 'Total Time',end_time - start_time,'seconds'
This currently takes about 250 seconds per 700 MB file, which to me seems very high. Is there a more efficient way I could do this?
Final Solution
Using the numpy fromfile method with a custom dtype cut the runtime to 9 seconds, 27x faster than the original code above. The final code is below.
from numpy import savez, dtype , fromfile
from os.path import getsize
from time import clock
start_time = clock()
file_size = getsize(input_file)
openfile = open(input_file,'rb')
header = openfile.read(149)
record_size = int(header[23:31])
number_of_records = ( file_size - 149 ) / record_size
sample_rate = ( ( record_size - 4 ) / 4 ) / 2
record_dtype = dtype( [ ( 'timestamp' , '<i4' ) , ( 'samples' , '<i2' , ( sample_rate , 4 ) ) ] )
data = fromfile(openfile , dtype = record_dtype , count = number_of_records )
time_series = data['timestamp']
t_series = data['samples'][:,:,0].ravel()
x_series = data['samples'][:,:,1].ravel()
y_series = data['samples'][:,:,2].ravel()
z_series = data['samples'][:,:,3].ravel()
savez(output_file, t=t_series , x=x_series ,y=y_series, z=z_series, fid=time_series)
end_time = clock()
print 'It took',end_time - start_time,'seconds'
A: Numpy supports mapping binary from data directly into array like objects via numpy.memmap. You might be able to memmap the file and extract the data you need via offsets.
For endianness correctness just use numpy.byteswap on what you have read in. You can use a conditional expression to check the endianness of the host system:
if struct.pack('=f', np.pi) == struct.pack('>f', np.pi):
# Host is big-endian, in-place conversion
arrayName.byteswap(True)
A: One glaring inefficiency is the use of hstack in a loop:
time_series = hstack ( ( time_series , time_stamp ) )
t_series = hstack ( ( t_series , record_t ) )
x_series = hstack ( ( x_series , record_x ) )
y_series = hstack ( ( y_series , record_y ) )
z_series = hstack ( ( z_series , record_z ) )
On every iteration, this allocates a slightly bigger array for each of the series and copies all the data read so far into it. This involves lots of unnecessary copying and can potentially lead to bad memory fragmentation.
I'd accumulate the values of time_stamp in a list and do one hstack at the end, and would do exactly the same for record_t etc.
If that doesn't bring sufficient performance improvements, I'd comment out the body of the loop and would start bringing things back in one a time, to see where exactly the time is spent.
A: Some hints:
*
*Don't use the struct module. Instead, use Numpy's structured data types and fromfile. Check here: http://scipy-lectures.github.com/advanced/advanced_numpy/index.html#example-reading-wav-files
*You can read all of the records at once, by passing in a suitable count= to fromfile.
Something like this (untested, but you get the idea):
import numpy as np
file = open(input_file, 'rb')
header = file.read(149)
# ... parse the header as you did ...
record_dtype = np.dtype([
('timestamp', '<i4'),
('samples', '<i2', (sample_rate, 4))
])
data = np.fromfile(file, dtype=record_dtype, count=number_of_records)
# NB: count can be omitted -- it just reads the whole file then
time_series = data['timestamp']
t_series = data['samples'][:,:,0].ravel()
x_series = data['samples'][:,:,1].ravel()
y_series = data['samples'][:,:,2].ravel()
z_series = data['samples'][:,:,3].ravel()
A: I have got satisfactory results with a similar problem (multi-resolution multi-channel binary data files) by using array, and struct.unpack. In my problem, I wanted continuous data for each channel, but the file had an interval oriented structure, instead of a channel oriented structure.
The "secret" is to read the whole file first, and only then distribute the known-sized slices to the desired containers (on the code below, self.channel_content[channel]['recording'] is an object of type array):
f = open(somefilename, 'rb')
fullsamples = array('h')
fullsamples.fromfile(f, os.path.getsize(wholefilename)/2 - f.tell())
position = 0
for rec in xrange(int(self.header['nrecs'])):
for channel in self.channel_labels:
samples = int(self.channel_content[channel]['nsamples'])
self.channel_content[channel]['recording'].extend(fullsamples[position:position+samples])
position += samples
Of course, I cannot state this is better or faster than other answers provided, but at least is something you might evaluate.
Hope it helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: extern pointer problem in c++ I have a header file that has a number of declarations like this:
extern ID3D10Device* device;
I can't make these static because of a problem with multiple translation units, and I can't have them as normal pointers for a similar reason. However when I try to build the program I get unresolved external symbol linker errors. I'm assuming that this is because I'm attempting to use the pointers without defining them first. This is the problem however, as the way you initialise these DirectX objects is by passing the address of the pointers as parameters into specialist methods. - I may be wrong but I am assuming this is the problem as the compiler / linker / whatever can't see the definitions.
All I'm trying to do is have these pointers (for the graphics device, depth buffer etc) visible to multiple classes. How can this be achieved?
A: You need the pointers to be defined in some translation unit. The linker is complaining because it seems you haven't done that anywhere. You should declare them at file scope as
ID3D10Device* device = NULL;
in the source file where you call the DirectX function that initializes them. Just make sure the declaration is only made in one source file, then the extern statement should be placed in the associated header file which is included by all translation units that need to use these pointers.
A: When you externally define a variable like this, the compiler is not reserving any memory for that variable until it sees a definition inside a code module itself. So if you are going to be passing these pointers by-reference to a function for initializing their values, they must be defined in a code module somewhere.
You only need to define them in a single code module ... then place the extern declarations inside a header file you include in the rest of your code modules that require access to the pointer variables. That shouldn't create any linker errors due to duplicate definitions.
A:
I can't make these static because of a problem with multiple translation units
If you need a different variable in different TU (translation units), make it static: this way the variable will be specific to each TU.
A declaration of a variable is also definition unless the extern is used.
You must have one (and only one) definition of a variable in the program.
To have a global variable:
*
*Declare it with the extern keyword in some header file.
*Include this header in every TU that needs to use the variable. Never declare the variable directly, never bypass the header inclusion.
*Define the variable: a declaration without the extern keyword will define the variable in one TU. You need to include the header file in the same TU to guaranty consistency between the extern declaration and the definition.
A:
the way you initialise these DirectX objects is by passing the address
of the pointers as parameters into specialist methods
To solve this part of the problem, you could do something like this (in a .cpp file):
ID3D10Device* device;
struct Foo {
Foo(ID3D10Device **pdevice) { specialist_method(pdevice); }
};
Foo f(&device);
Beware of the "static initialization order fiasco", though -- it's safe to use device from main, or code called from main, because it will definitely be initialized before that code executes. It's not necessarily safe to use it from other initializers executed before main, because the order of initialization of statics in different translation units is unspecified (within a TU, they're initialized in order of either declaration or definition, I forget which). So device might still be a null pointer in that code. Likewise, specialist_method can't necessarily rely on other statics having been initialized.
There are extra tricks you can use if you need to enforce initialization orders, I'd guess that all the common ones are on SO already in other questions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: System.Web.HttpException: Response is not available in this context error Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Response is not available in this context.
Source Error:
Line 10: public void Download(string filename)
Line 11: {
Line 12: Response.ContentType = "application/exe";
Line 13: Response.AppendHeader("Content-Disposition", filename);
Line 14: Response.TransmitFile(Server.MapPath("~/Resources/bb.exe"));
I am having this method inside a class, i call this method when I click a button
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class Common: System.Web.UI.Page
{
}
Where am I going wrong
A: You just can't use Response object of the Page like you're doing, because this object represents response which had been sent already, so you cannot modify it or use TransmitFile with it.
You need to create your own handler to write file to server output. Refer to IHttpHandler documentation (http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx)
A: I'm not sure How,
But a broken connection string in my Web.config file - caused the same issue.
A: When using the response object from an aspx page, its codebehind class or a
user control, the response object is directly available because all these
derive from the page object.
When using the response object in your own class, the object is not
available, but you can access it:
HttpContext.Current.Response. -> something
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7569568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.