I just noticed something concerning for-loop performance that seems to fly in the face of the recommendations given by the Google Android team. Look at the following code:
package com.jackcholt;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loopTest();
finish();
}
private void loopTest() {
final long loopCount = 1228800;
final int[] image = new int[8 * 320 * 480];
long start = System.currentTimeMillis();
for (int i = 0; i < (8 * 320 * 480); i++) {
image[i] = i;
}
for (int i = 0; i < (8 * 320 * 480); i++) {
image[i] = i;
}
Log.i("loopTest", "Elapsed time (recompute loop limit): " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < 1228800; i++) {
image[i] = i;
}
for (int i = 0; i < 1228800; i++) {
image[i] = i;
}
Log.i("loopTest", "Elapsed time (literal loop limit): " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < loopCount; i++) {
image[i] = i;
}
for (int i = 0; i < loopCount; i++) {
image[i] = i;
}
Log.i("loopTest", "Elapsed time (precompute loop limit): " + (System.currentTimeMillis() - start));
}
}
When I run this code I get the following output in logcat:
I/loopTest( 726): Elapsed time (recompute loop limit): 759
I/loopTest( 726): Elapsed time (literal loop limit): 755
I/loopTest( 726): Elapsed time (precompute loop limit): 1317
As you can see the code that seems to recompute the loop limit value on every iteration of the loop compares very well to the code that uses a literal value for the loop limit. However, the code that uses a variable which contains the precomputed value for the loop limit is significantly slower than either of the others. I'm not surprised that accessing a variable should be slower that using a literal but why does code that looks like it should be using two multiply instructions on every iteration of the loop so comparable in performance to a literal?
Could it be that because literals are the only thing being multiplied, the Java compiler is optimizing out the multiplication and using a precomputed literal?
I'm creating my generic DataContext using only the connectionString in the ctor. I have no issues in retrieving the table using DataContext.GetTable().
However, I need to also be able to retrieve entities of inline table functions. The dbml designer generates
public IQueryable<testFunctionResult> testFunction()
{
return this.CreateMethodCallQuery<testFunctionResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
}
The question is how do I get the MethodInfo.GetCurrentMethod() when the DataContext has no method called "testFunction", i.e.typeof(DataContext).GetMethod("testFunction") returns null?
What I'm trying to achieve is something like:
public class UnitofWork<T>
{
public UnitofWork(string connectionString)
{
this.DataContext = new DataContext(connectionString);
}
public UnitofWork(IQueryable<T> tableEntity)
{
_tableEntity = tableEntity;
}
public IQueryable<T> TableEntity
{
get
{
if (DataContext == null)
return _tableEntity;
var metaType = DataContext.Mapping.GetMetaType(typeof (T));
if (metaType.IsEntity)
_tableEntity = DataContext.GetTable<T>();
else
{
var s = typeof(T).Name;
string methodName = s.Substring(0, s.IndexOf("Result")) + "()"; // the designer automatically affixes "Result" to the type name
// Make a method from methodName
// _tableEntity = DataContext.CreateMethodCallQuery(DataContext, method, new object[]{});
}
return _tableEntity;
}
set { _tableEntity = value; }
}
)
Thanks in advance for any insight
Jeremy
I would like to create a windows xp guest from the windows xp upgrade cd I have, along with one of a few full versions I have around. However, when I reach the stage in the installer where I am prompted to insert a full version cd, the installer can't find it, i.e.:
Setup could not read the CD you inserted, or the CD is not a valid Windows CD..
Is there a work-around for this?, my Googling didn't uncover anything.
I've tried various combinations of mounting .iso files and specifying disks, such as:
$sudo virt-install --accelerate --connect qemu:///system -n xpsp1 -r 2048
--disk ./vm/winxp_sp1.iso,device=cdrom --disk ./vm/windows.qcow2,size=12
--vnc --noautoconsole --os-type windows --os-variant winxp --vcpus 2 -c /dev/cdrom
--check-cpu
If I try to specify multiple cdrom drives, I receive an error:
virt-install --accelerate --connect qemu:///system -n xpsp1 -r 2048
--disk ./vm/winxp_sp1.iso,device=cdrom --disk /dev/cdrom,device=cdrom
--disk ./vm/windows.qcow2,size=12 --vnc --noautoconsole --os-type windows
--os-variant winxp --vcpus 2 --check-cpu
Starting install...
ERROR IDE CDROM must use 'hdc', but target in use.
I want to make a setup like this:
cable modem <-cable- wireless router 1 <-wireless- wireless router 2 in another room <-cables- PCs in another room
Basically, I want to extend my network access across the house and then have a bunch of network jacks available for my office PCs.
Right now, I have a cable modem going to a wireless router in one room and a PC with a wireless PCI card in it in the office on the other side of the house. I use internet connection sharing with the other PCs in the office. The problem is that ICS is flaky, especially when I switch to VPN on the Windows box to access files at work. I picked up a wireless USB adapter that I thought I could share among the PCs I work on but I'm not very happy with it so I'm going to return it (NDISwrapper support for it is poor).
Is this possible? My wireless experience so far has been pretty straightforward so I have no idea what kind of hardware is available. I've looked at network extenders but those just look like repeaters for signal strength. I want wired network jacks in my office.
The default installation of OpenBSD is a little spartan. Is there a guide somewhere that shows how to set up a nicer desktop environment? I don't need a lot of bells and whistles but that window manager is straight out of 1995.
We have an ASP.NET web application which is mapped to a folder on an apache hosted php site using ProxyPass.ProxyPassReverse.
A couple of problems being encountered.
cookies are being lost which breaks the site navigation, this can be overcome by setting the asp app as cookieless.
Forms authentication is used on the ASP site, this is also broken withe the proxypass in place, suspect this is cookie related also.
ASP site works ok when run from a domain/ip address.
Use of a separate domain / sub-domain is not an option duew to client requirements.
I'm in the common situation where the one of the linux servers I use for storing backups is filling up. I'm wondering what tools are available for doing this.
Ideally, what I would like is something that keeps nightlies for the previous month, weeklies for the 2nd to 5th preceding months and retains monthlies (well, every 3rd week) for an indefinite period. Everything that falls outside of that would be deleted after the backups are run.
I could write a script to do this, but I feel like there must be a standard tool for this task.
The default behavior for 'less' is to clear the screen after quitting. This behavior stopped when I started using:
export TERM=xterm
Now 'less' leaves the last page I viewed on the screen, and I want to re-enable the default behavior of clearing the screen.
Googling this problem I found that people use the following command in their ~/.screenrc:
altscreen on
I'm not sure if this is a mac-issue but I don't have this command available.
I'm using bash shell on Mac terminal.
Thanks!
We have an ASP.NET web application which is mapped to a folder on an apache hosted php site using ProxyPass.ProxyPassReverse.
A couple of problems being encountered.
cookies are being lost which breaks the site navigation, this can be overcome by setting the asp app as cookieless.
Forms authentication is used on the ASP site, this is also broken withe the proxypass in place, suspect this is cookie related also.
ASP site works ok when run from a domain/ip address.
Use of a separate domain / sub-domain is not an option duew to client requirements.
I’m trying to log in to a Juniper VPN with Network Connect from a headless Linux client. I followed the instructions and used the script from http://mad-scientist.us/juniper.html. When running the script with --nogui switch the command that gets finally executed is $HOME/.juniper_networks/network_connect/ncsvc -h HOST -u USER -r REALM -f $HOME/.vpn.default.crt. I get asked for the password, a line “Connecting to…” is printed but then the programm silently stops. When adding -L 5 (most verbose logging) to the command line, these are the last messages printed to the log:
dsclient.info state: kStateCacheCleaner (dsclient.cpp:280)
dsclient.info --> POST /dana-na/cc/ccupdate.cgi (authenticate.cpp:162)
http_connection.para Entering state_start_connection (http_connection.cpp:282)
http_connection.para Entering state_continue_connection (http_connection.cpp:299)
http_connection.para Entering state_ssl_connect (http_connection.cpp:468)
dsssl.para SSL connect ssl=0x833e568/sd=4 connection using cipher RC4-MD5 (DSSSLSock.cpp:656)
http_connection.para Returning DSHTTP_COMPLETE from state_ssl_connect (http_connection.cpp:476)
DSHttp.debug state_reading_response_body - copying 0 buffered bytes (http_requester.cpp:800)
DSHttp.debug state_reading_response_body - recv'd 0 bytes data (http_requester.cpp:833)
dsclient.info <-- 200 (authenticate.cpp:194)
dsclient.error state host checker failed, error 10 (dsclient.cpp:282)
ncapp.error Failed to authenticate with IVE. Error 10 (ncsvc.cpp:197)
dsncuiapi.para DsNcUiApi::~DsNcUiApi (dsncuiapi.cpp:72)
What does host checker failed mean? How can I find out what it tried to check and what failed? The HostChecker Configuration Guide mentions that a $HOME/.juniper_networks/tncc.jar gets installed on Linux, but my installation contains no such file. From that I concluded that HostChecker is disabled for my VPN on Linux? Are the POST to /dana-na/cc/ccupdate.cgi and “host checker failed” connected or independent? By running the connection over a SSL proxy I found out that the POST data is status=NOTOK (Funny side note: the client of the oh-so-secure VPN does not validate the server’s SSL certificate, so is wide open to MITM attacks…). So it seems that it’s the client that closes the connection and not the server.
I have an ASP.NET GridView which has columns that look like this:
| Foo | Bar | Total1 | Total2 | Total3 |
Is it possible to create a header on two rows that looks like this?
| | Totals |
| Foo | Bar | 1 | 2 | 3 |
The data in each row will remain unchanged as this is just to pretty up the header and decrease the horizontal space that the grid takes up.
The entire GridView is sortable in case that matters. I don't intend for the added "Totals" spanning column to have any sort functionality.
Edit:
Based on one of the articles given below, I created a class which inherits from GridView and adds the second header row in.
namespace CustomControls
{
public class TwoHeadedGridView : GridView
{
protected Table InnerTable
{
get
{
if (this.HasControls())
{
return (Table)this.Controls[0];
}
return null;
}
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
this.CreateSecondHeader();
}
private void CreateSecondHeader()
{
GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = this.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
this.InnerTable.Rows.AddAt(0, row);
}
}
}
In case you are new to ASP.NET like I am, I should also point out that you need to:
1) Register your class by adding a line like this to your web form:
<%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%>
2) Change asp:GridView in your previous markup to foo:TwoHeadedGridView. Don't forget the closing tag.
Another edit:
You can also do this without creating a custom class.
Simply add an event handler for the DataBound event of your grid like this:
protected void gvOrganisms_DataBound(object sender, EventArgs e)
{
GridView grid = sender as GridView;
if (grid != null)
{
GridViewRow row = new GridViewRow(0, -1,
DataControlRowType.Header, DataControlRowState.Normal);
TableCell left = new TableHeaderCell();
left.ColumnSpan = 3;
row.Cells.Add(left);
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = grid.Columns.Count - 3;
totals.Text = "Totals";
row.Cells.Add(totals);
Table t = grid.Controls[0] as Table;
if (t != null)
{
t.Rows.AddAt(0, row);
}
}
}
The advantage of the custom control is that you can see the extra header row on the design view of your web form. The event handler method is a bit simpler, though.
I need to do some work with this library and I'm finding the documentation at http://apodeline.free.fr/DOC/libjpeg/libjpeg.html to be deficient (incomplete function signatures, etc). Does anyone know of some other sides or have some example code illustrating common tasks?
[Edit]
I also found this question with an example, but any others would be helpful.
I generated a lower triangular matrix, and I want to complete the matrix using the values in the lower triangular matrix to form a square matrix, symmetrical around the diagonal zeros.
lower_triangle = numpy.array([
[0,0,0,0],
[1,0,0,0],
[2,3,0,0],
[4,5,6,0]])
I want to generate the following complete matrix, maintaining the zero diagonal:
complete_matrix = numpy.array([
[0, 1, 2, 4],
[1, 0, 3, 5],
[2, 3, 0, 6],
[4, 5, 6, 0]])
Thanks.
i am using a m2m and a through table, and when i was trying to save, my error was:
Cannot set values on a ManyToManyField which specifies an intermediary model
so, i've modified my code, so that when i save the form, to insert data into the 'through' table too.But now, i'm having another error.
(i've bolded the lines where i think i am wrong)
i have in models.py:
class Classroom(models.Model):
user = models.ForeignKey(User, related_name = 'classroom_creator')
classname = models.CharField(max_length=140, unique = True)
date = models.DateTimeField(auto_now=True)
open_class = models.BooleanField(default=True)
members = models.ManyToManyField(User,related_name="list of invited members", through = 'Membership')
class Membership(models.Model):
accept = models.BooleanField(User)
date = models.DateTimeField(auto_now = True)
classroom = models.ForeignKey(Classroom, related_name = 'classroom_membership')
member = models.ForeignKey(User, related_name = 'user_membership')
and in
def save_classroom(request):
if request.method == 'POST':
form = ClassroomForm(request.POST, request.FILES, user = request.user)
**classroom_instance = Classroom
member_instance = Membership**
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.user = request.user
r = Relations.objects.filter(initiated_by = request.user)
membership = Membership.objects.create(**classroom = classroom_instance, member = member_instance,date=datetime.datetime.now())**
new_obj.save()
form.save_m2m()
return HttpResponseRedirect('/classroom/classroom_view/{{user}}/')
else:
form = ClassroomForm(user = request.user)
return render_to_response('classroom/classroom_form.html', {
'form': form,
},
context_instance=RequestContext(request))
but i don't seem to initialise okay the classroom_instance and menber_instance.My error os:
Cannot assign "": "Membership.classroom" must be a "Classroom" instance.
Thanks!
I'm developing an application for Office. It originally targeted .net 3.5, but I decided to upgrade to .net 4 because of some WPF issues that I've run into.
When I switched all the projects in my solution and rebuilt, I got an error saying to include System.Xaml. I did that and rebuilt, and VS2010 told me to include another reference, so I did. This happened a couple more times, and finally it asked me to include Microsoft.Office.Tools.Common.v9.0, and when I did I got this error:
Microsoft.Office.Tools.CustomTaskPaneCollection exists in both Microsoft.Office.Tools.Common.v9.0.dll and Microsoft.Office.Tools.Common.dll
I have both Microsoft.Office.Tools.Common.v9.0 and Microsoft.Office.Tools.Common referenced in my project, but the problem is that if I remove either, I get an error. Am I doing something wrong? Is it odd that I would need both references? I find it strange that CustomTaskPaneCollection would be defined in two different binaries.
If I remove Microsoft.Office.Tools.Common, the error that I get is "Cannot find the interop type that matches the embedded interop type 'Microsoft.Office.Tools.IAddInExtension'. Are you missing an assembly reference?"
hello,
i'm trying to build a mini reply system, based on the user's posts on a mini blog.
Every post has a link named reply. if one presses reply, the reply form appears, and one edits the reply, and submits the form.The problem is that i don't know how to take the id of the post i want to reply to. In the view, if i use as a parameter one number (as an id of the blog post),it inserts the reply to the database.
But how can i do it by not hardcoding?
The view is:
def save_reply(request):
if request.method == 'POST':
form = ReplyForm(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.creator = request.user
new_post = New(1) #it works only hardcoded
new_obj.reply_to = new_post
new_obj.save()
return HttpResponseRedirect('.')
else:
form = ReplyForm()
return render_to_response('replies/replies.html', {
'form': form,
},
context_instance=RequestContext(request))
i have in forms.py:
class ReplyForm(ModelForm):
class Meta:
model = Reply
fields = ['reply']
and in models:
class Reply(models.Model):
reply_to = models.ForeignKey(New)
creator = models.ForeignKey(User)
reply = models.CharField(max_length=140,blank=False)
objects = NewManager()
mentioning that New is the micro blog class
thanks
How would you filter a list in Sharepoint (WSS 3.0) by a current user's profile property. For example, I have a list with a Department column and I want to filter the list based on the current user's department (which would be a user profile's property).
Any idea's on how to do this?
heyy there
i want to parse a text,let's name it 'post', and 'urlize' some strings if they contain a particular character, in a particular position.
my 'pseudocode' trial would look like that:
def urlize(post)
for string in post
if string icontains ('#')
url=(r'^searchn/$',
searchn,
name='news_searchn'),
then apply url to the string
return urlize(post)
i want the function to return to me the post with the urlized strings, where necessary (just like twitter does).
i don't understand: how can i parse a text, and search for certain strings?
is there ok to make a function especially for 'urlizing' some strings? The function should return the entire post, no matter if it has such kind of strings.
is there another way Django offers?
Thank you
i have a miniblog application, with a class named New(refering to a new post), having a foreign key to an user(who has posted the entry).
above i have a method that displays all the posts from all the users.
I'd like to show to the logged in user, only his posts
How can i do it?
Thanks in advance!
def paginate(request):
paginator = New.objects.all()
return render_to_response('news/newform.html', {
'object_list': paginator,
},
context_instance=RequestContext(request))
I'm starting work on some simulations using MPI and want to do the programming in Python/scipy. The scipy site lists a number of mpi libraries, but I was hoping to get feedback on quality, ease of use, etc from anyone who has used one.
hello there,
i have a mini comunity where each user can search and find another user profile.
Userprofile is a class model, indexed differently compared to user model class (user id is not equal to userprofile id)
But i cannot see a user profile by typing in the url the corresponding id. I only see the profile of the currently logged in user.
Why is that?
I'd also want to have in my url the username (a primary key of the user table also) and NOT the id (a number).
The guilty part of the code is:
what can i replace that request.user with so that it wil actually display the user i searched for, and not the currently logged in?
def profile_view(request, id):
u = UserProfile.objects.get(pk=id)
cv = UserProfile.objects.filter(created_by = request.user)
blog = New.objects.filter(created_by = request.user)
return render_to_response('profile/publicProfile.html', {
'u':u,
'cv':cv,
'blog':blog,
},
context_instance=RequestContext(request))
in urls (of the accounts app):
url(r'^profile_view/(?P<id>\d+)/$',
profile_view,
name='profile_view'),
and in template:
<h3>Recent Entries:</h3>
{% load pagination_tags %}
{% autopaginate list 10 %}
{% paginate %}
{% for object in list %}
<li>{{ object.post }} <br />
Voted: {{ vote.count }} times.<br />
{% for reply in object.reply_set.all %}
{{ reply.reply }} <br />
{% endfor %}
<a href=''> {{ object.created_by }}</a> <br />
{{object.date}} <br />
<a href = "/vote/save_vote/{{object.id}}/">Vote this</a>
<a href="/replies/save_reply/{{object.id}}/">Comment</a> </li>
{% endfor %}
thanks in advance!
I have a classroom application,and a follow relation. Users can follow each other and can create classrooms.When a user creates a classroom, he can invite only the people that are following him.
The Classroom model is a m2m to User table.
i have in models. py:
class Classroom(models.Model):
creator = models.ForeignKey(User)
classname = models.CharField(max_length=140, unique = True)
date = models.DateTimeField(auto_now=True)
open_class = models.BooleanField(default=True)
members = models.ManyToManyField(User,related_name="list of invited members")
and in models.py of the follow application:
class Relations(models.Model):
initiated_by = models.ForeignKey(User, editable=False)
date_initiated = models.DateTimeField(auto_now=True, editable = False)
follow = models.ForeignKey(User, editable = False, related_name = "follow")
date_follow = models.DateTimeField(auto_now=True, editable = False)
and in views.py of the classroom app:
def save_classroom(request, username):
if request.method == 'POST':
u = User.objects.get(username=username)
form = ClassroomForm(request.POST, request.FILES)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.creator = request.user
r = Relations.objects.filter(initiated_by = request.user)
# new_obj.members =
new_obj.save()
return HttpResponseRedirect('.')
else:
form = ClassroomForm()
return render_to_response('classroom/classroom_form.html', {
'form': form,
},
context_instance=RequestContext(request))
i'm using a ModelForm for the classroom form, and the default view, taking in consideration my many to many relation with User table, in the field Members, is a list of all Users in my database.
But i only want in that list the users that are in a follow relationship with the logged in user - the one who creates the classroom.
How can i do that?
Thanks!
i am trying to build a virtual comunity, and i have a profile page, and a personal page. In the profile page, one can see only the posts of one user(the user whos profile is checked), in the personal page one can see his posts, plus all the posts he has subscribed to (just like in Facebook)
it's a little confusing for me how i can link to the profile of one user, i mean when anybody clicks on a username, it should link to his personal profile page.
for example, if someone searches name "abc", the rsult would be "abc",and link to his profile.
How can i pass to one function the username or id of a linked user?
i mean, showing the profile of the logged in user who is checking his profile is quite easy.But how about another user profile, if one wants to access it?
thanks a lot!
hello,
i have an application that loads different documents to the server, and allows users to read documents' content.
i am uploading the documents to the server, and then i try to read the courses by id, like:
def view_course(request,id):
u = Courses.objects.get(pk=id)
etc
But i don't find anywhere : how can i actually read the content of a /.doc/.pdf/.txt and display it on a web page?
thanks in advance!