Friday, 30 August 2013

OpenGL ES 2.0 Scene Lighting iOS

OpenGL ES 2.0 Scene Lighting iOS

I have been looking online and cannot find an example of scene lighting.
Scene lighting meaning there is a light on the wall and all objects which
pass this light get lighted appropriately on the faces which face the
light. Can anyone provide me with an example of such? Or some good reading
on how to do such. I would like to get to the point of using multiple
lights and shadows and possibly lights such as fire which flicker? Is this
possible?
My code below is shading my character but as he rotates (the model view
matrix is rotating), the faces are not changing any lighting.
Vertex Shader precision highp float;
attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord;
uniform mat4 u_mvMatrix;
uniform mat4 u_mvpMatrix;
varying lowp vec2 v_texCoord;
varying vec3 v_ecNormal;
varying vec4 v_position;
void main()
{
vec4 mcPosition = a_position;
vec3 mcNormal = a_normal;
vec3 ecNormal = vec3(u_mvMatrix * vec4(mcNormal, 0.0));
v_ecNormal = ecNormal;
v_position = a_position;
v_texCoord = vec2(a_texCoord.x, 1.0 - a_texCoord.y);
gl_Position = u_mvpMatrix * mcPosition;
}
Frag Shader
precision highp float;
uniform sampler2D u_texture;
varying lowp vec2 v_texCoord;
struct DirectionalLight {
vec3 position;
vec3 halfplane;
vec4 ambientColor;
vec4 diffuseColor;
vec4 specularColor;
};
struct Material {
vec4 ambientFactor;
vec4 diffuseFactor;
vec4 specularFactor;
float shininess;
};
uniform DirectionalLight u_directionalLight;
uniform Material u_material;
varying vec3 v_ecNormal;
varying vec4 v_position;
void main()
{
//gl_FragColor = colorVarying * texture2D(texture, texCoordOut);
// normalize
vec3 ecNormal = v_ecNormal / length(v_ecNormal);
vec3 lightPosition = u_directionalLight.position;
vec3 lightDirection;
lightDirection.x = v_position.x - lightPosition.x;
lightDirection.y = v_position.y - lightPosition.y;
lightDirection.z = v_position.z - lightPosition.z;
float ecNormalDotLightDirection = max(0.0, dot(ecNormal,
lightDirection));
float ecNormalDotLightHalfplane = max(0.0, dot(ecNormal,
u_directionalLight.halfplane));
// calc ambient light
vec4 ambientLight = u_directionalLight.ambientColor *
u_material.ambientFactor;
// calc diffuse light
vec4 diffuseLight = ecNormalDotLightDirection *
u_directionalLight.diffuseColor * u_material.diffuseFactor;
// calc specular light
vec4 specularLight = vec4(0.0);
if (ecNormalDotLightHalfplane > 0.0) {
specularLight = pow(ecNormalDotLightHalfplane,
u_material.shininess) * u_directionalLight.specularColor *
u_material.specularFactor;
}
vec4 light = ambientLight + diffuseLight + specularLight;
gl_FragColor = light * texture2D(u_texture, v_texCoord);
}

Thursday, 29 August 2013

Java OutOfMemoryError in reading a large text file

Java OutOfMemoryError in reading a large text file

I'm new to Java and working on reading very large files, need some help to
understand the problem and solve it. We have got some legacy code which
have to be optimized to make it run properly.The file size can vary from
10mb to 10gb only. only trouble start when file starting beyond 800mb
size.
InputStream inFileReader = channelSFtp.get(path); // file reading from ssh.
byte[] localbuffer = new byte[2048];
ByteArrayOutputStream bArrStream = new ByteArrayOutputStream();
int i = 0;
while (-1 != (i = inFileReader.read(buffer))) {
bArrStream.write(localbuffer, 0, i);
}
byte[] data = bArrStream.toByteArray();
inFileReader.close();
bos.close();
We are getting the error
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2271)
at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:113)
at
java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:140)
Any help would be appreciated?

Wednesday, 28 August 2013

Only one command line in PROJ.4

Only one command line in PROJ.4

I would like to know if there are a way to write only one command line to
obtain the expected results. I explain:
When you write this :
$ proj +proj=utm +zone=13 +ellps=WGS84 -f %12.6f
If you want to recieved the output data:
500000.000000 4427757.218739
You must to write in another line with the input data:
-105 40
Is it possible to write concatenated command line as this stile?:
$ proj +proj=utm +zone=13 +ellps=WGS84 -f %12.6f | -105 40
Thank you

Should CPU usage be so low while memory usage is high on heavy mysql server?

Should CPU usage be so low while memory usage is high on heavy mysql server?

I'm using ubuntu server 12.04 x64. The server receives a lot of requests
to mysql through apache web server (it's light interface). From mysql
stats I see there is approx 250 queries / second from 8 AM - 9PM. At night
server is practically not used. RAM is mostly used by mysql (according to
mysqloptimizer maximum MySQL ram usage is 25GB). Top confirms it - mysql
uses about 77% of RAM.
The database size is about 20GB. One table that is under heaviest fire has
about 1-2 mln records (mainly id fields from few tables plus some
smallints counters).
I attached image ilustrating parts that are interesting for me(the second
memory images shows memory behavior after server restart).
While watching munin I came up with few questions:
Why in memory useage apps memory practically never falls? Shouldn't it
decrease e.g. at night when there's no traffic on the server?
Wouldn't it be better to somehow tweak it make more memory space for cache?
Why CPU usage is so low while RAM is full?
Level of inactive memory is also rising and it worries me a little.
Those questions came up because occasionally the traffic rises
significantly for short time and in those moments server is not answering
to a lot of requests. But at those moments RAM/CPU or even disk latency is
not rising to much, maybe a little. Those traffic rises are unavoidable
but I'm not sure whether replacing the server with stringer one will do it
or maybe only put more RAM (as CPU usage is minimal)?
If this question is unanswerable - sorry.
EDIT: # # The MySQL database server configuration file. # # You can copy
this to one of: # - "/etc/mysql/my.cnf" to set global options, # -
"~/.my.cnf" to set user-specific options. # # One can use all long options
that the program supports. # Run program with --help to get a list of
available options and with # --print-defaults to see which it would
actually understand and use. # # For explanations see #
http://dev.mysql.com/doc/mysql/en/server-system-variables.html
# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
# Here is entries for some specific programs
# The following values assume you have at least 32M ram
# This was formally known as [safe_mysqld]. Both versions are currently
parsed.
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address = 127.0.0.1
#
# * Fine Tuning
#
key_buffer = 64M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 64
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover = BACKUP
max_connections = 400
table_cache = 6000
#thread_concurrency = 10
#
# * Query Cache Configuration
#
query_cache_limit = 1M
query_cache_size = 32M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file = /var/log/mysql/mysql.log
#general_log = 1
#
# Error logging goes to syslog due to
/etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# Here you can see queries with especially long duration
slow_query_log = 0
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 20
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
#server-id = 1
#log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 10
max_binlog_size = 100M
#binlog_do_db = include_database_name
#binlog_ignore_db = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem
innodb_file_per_table
innodb_flush_method=O_DIRECT
innodb_log_file_size = 512M
innodb_buffer_pool_size = 24G
bulk_insert_buffer_size = 256M
innodb_open_files = 6000
innodb_flush_log_at_trx_commit = 2
innodb_lock_wait_timeout = 50
innodb_file_io_threads = 4
thread_cache_size = 64
thread_concurrency = 12
query_cache_size = 64M
query_cache_limit = 2M
max_sp_recursion_depth = 50
thread_stack = 384K
tmp_table_size = 64M
max_heap_table_size = 64M
key_buffer_size = 32M
event_scheduler = ON
lower_case_table_names = 1
[mysqldump]
quick
quote-names
max_allowed_packet = 16M
[mysql]
#no-auto-rehash # faster start of mysql but no tab completition
[isamchk]
key_buffer = 16M
#
# * IMPORTANT: Additional settings that can override those from this file!
# The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

override the src of an html img via css

override the src of an html img via css

I have this image tag:
<img src="http://placehold.it/200x200"/>
I need to replace the image via css (because I can't edit the html),so I
use this css:
img {
content: url('http://lorempixel.com/200/200');
}
it's working well on chrome but not working in firefox and ie,any idea why?

Tuesday, 27 August 2013

Django IntegrityError: (1048, "Column 'user_id' cannot be null")

Django IntegrityError: (1048, "Column 'user_id' cannot be null")

This is my models.py
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
class Meta:
db_table = 'CfitUser'
def __str__(self):
return "%s's profile" % self.user
@receiver(post_save, sender=User)
def create_cfituser(sender, instance, created, **kwargs):
if created:
Cfituser.objects.get_or_create(user=instance)
This is my views.py
@api_view(['GET', 'POST'])
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username =
serializer.data['socialid'])
cfituser = Cfituser.objects.get(user = user)
cfituser.accesstoken = serializer.data['accesstoken']
cfituser.socialid = serializer.data['socialid']
cfituser.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
Whenever there is a HTTP Post request, my database tables are filled in as
expected but this error keeps popping up. I've tried almost every solution
available on SO but I'm stuck with this.
I have tried user = models.OneToOneField(User, null = True) but this leads
to two entries in my database table, one with user_id = NULL and one with
user_id = actualvalue.
Any suggestions on how to fix this?

Converting website with profiles to web application project

Converting website with profiles to web application project

I'm trying to convert an existing website to a Web Application Project and
I'm having big problems getting the profiles to work.
An example of codebehind in website project is
register-with-role-and-profile.ascx.cs
// Add the newly created user to the default Role.
Roles.AddUserToRole(CreateUserWizard1.UserName, wsatDefaultRole);
// Create an empty Profile for the newly created user
ProfileCommon p =
(ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);
// Populate some Profile properties. Values are located in web.config
file
p.Company.Company =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeName")).Text;
p.Company.Address =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeAddress")).Text;
p.Company.City =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeCity")).Text;
p.Company.State =
((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ddlStates")).SelectedValue;
p.Company.PostalCode =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeZip")).Text;
p.Company.Phone =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbContactPhone")).Text;
p.Company.Fax =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbContactFax")).Text;
p.Preferences.Newsletter =
((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ddlNewsletter")).SelectedValue;
// Save profile - must be done since we explicitly created it
p.Save();
web.config
<profile defaultProvider="MyCMSTableProfileProvider"
automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="MyCMSTableProfileProvider" applicationName="MyCMS"
connectionStringName="dbMyCMSConnectionString"
table="aspnet_CustomProfile"
type="CustomProfile.SqlTableProfileProvider"/>
<add name="MyCMSStoredProcedureProfileProvider"
applicationName="MyCMS"
connectionStringName="dbMyCMSConnectionString"
type="CustomProfile.SqlStoredProcedureProfileProvider"
setProcedure="sp_wsat_SetCustomProfileData"
readProcedure="sp_wsat_GetCustomProfileData"/>
</providers>
<properties>
<group name="Personal">
<add name="FirstName" type="String" defaultValue="[null]"
customProviderData="FirstName;nvarchar"/>
<add name="LastName" type="String" defaultValue="[null]"
customProviderData="LastName;nvarchar"/>
<add name="Gender" type="String" defaultValue="[null]"
customProviderData="Gender;nvarchar"/>
<add name="BirthDate" type="DateTime" defaultValue="[null]"
customProviderData="BirthDate;datetime"/>
<add name="Occupation" type="String" defaultValue="[null]"
customProviderData="Occupation;nvarchar"/>
<add name="Website" type="String" defaultValue="[null]"
customProviderData="PersonalWebsite;nvarchar"/>
</group>
<group name="Address">
<add name="Country" type="String" defaultValue="[null]"
customProviderData="Country;nvarchar"/>
<add name="Address" type="String" defaultValue="[null]"
customProviderData="Address;nvarchar"/>
<add name="AptNumber" type="String" defaultValue="[null]"
customProviderData="AptNumber;nvarchar"/>
<add name="City" type="String" defaultValue="[null]"
customProviderData="City;nvarchar"/>
<add name="State" type="String" defaultValue="[null]"
customProviderData="State;nvarchar"/>
<add name="PostalCode" type="String" defaultValue="[null]"
customProviderData="PostalCode;nvarchar"/>
</group>
<group name="Contacts">
<add name="DayPhone" type="String" defaultValue="[null]"
customProviderData="DayPhone;nvarchar"/>
<add name="DayPhoneExt" type="String" defaultValue="[null]"
customProviderData="DayPhoneExt;nvarchar"/>
<add name="EveningPhone" type="String" defaultValue="[null]"
customProviderData="EveningPhone;nvarchar"/>
<add name="EveningPhoneExt" type="String"
defaultValue="[null]"
customProviderData="EveningPhoneExt;nvarchar"/>
<add name="CellPhone" type="String" defaultValue="[null]"
customProviderData="CellPhone;nvarchar"/>
<add name="Fax" type="String" defaultValue="[null]"
customProviderData="Fax;nvarchar"/>
</group>
<group name="Company">
<add name="Company" type="String" defaultValue="[null]"
customProviderData="Company;nvarchar"/>
<add name="Address" type="String" defaultValue="[null]"
customProviderData="Address2;nvarchar"/>
<add name="City" type="String" defaultValue="[null]"
customProviderData="City2;nvarchar"/>
<add name="State" type="String" defaultValue="[null]"
customProviderData="State2;nvarchar"/>
<add name="PostalCode" type="String" defaultValue="[null]"
customProviderData="PostalCode2;nvarchar"/>
<add name="Phone" type="String" defaultValue="[null]"
customProviderData="Phone2;nvarchar"/>
<add name="Fax" type="String" defaultValue="[null]"
customProviderData="Fax2;nvarchar"/>
<add name="Website" type="String" defaultValue="[null]"
customProviderData="Website2;nvarchar"/>
</group>
<group name="Preferences">
<add name="Culture" type="String" defaultValue="en-US"
customProviderData="Culture;nvarchar"/>
<add name="Newsletter" type="String" defaultValue="[null]"
customProviderData="Newsletter;nvarchar"/>
</group>
</properties>
</profile>
but this gives error The type or namespace name 'ProfileCommon' could not
be found (are you missing a using directive or an assembly reference?)
Using this example I created 2 new classes
ProfileInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AlchemyRacing.controls
{
[Serializable]
public class Personal
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public DateTime BirthDate { get; set; }
public string Occupation { get; set; }
public string Website { get; set; }
}
[Serializable]
public class Address
{
public string Country { get; set; }
public string Address1 { get; set; }
public string AptNumber { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
[Serializable]
public class Contacts
{
public string DayPhone { get; set; }
public string DayPhoneExt { get; set; }
public string EveningPhone { get; set; }
public string EveningPhoneExt { get; set; }
public string CellPhone { get; set; }
public string Fax { get; set; }
}
[Serializable]
public class Company
{
public string CompanyName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string Website { get; set; }
}
[Serializable]
public class Preferences
{
public string Culture { get; set; }
public string Newsletter { get; set; }
}
[Serializable]
public class ProfileInfo
{
public Personal Personal { get; set; }
public Address Address { get; set; }
public Contacts Contacts { get; set; }
public Company Company { get; set; }
public Preferences Preferences { get; set; }
}
}
ProfileInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Profile;
namespace AlchemyRacing.controls
{
public class wProfile : ProfileBase
{
public ProfileInfo ProfileInfo
{
get { return (ProfileInfo)GetPropertyValue("ProfileInfo"); }
}
public static wProfile GetProfile()
{
return (wProfile)HttpContext.Current.Profile;
}
public static wProfile GetProfile(string userName)
{
return (wProfile)Create(userName);
}
}
}
and then amended register-with-role-and-profile.ascx.cs to
// add newly created user to default Role specified above
if (Roles.RoleExists(wsatDefaultRole))
{
// Add the newly created user to the default Role.
Roles.AddUserToRole(CreateUserWizard1.UserName, wsatDefaultRole);
// Create an empty Profile for the newly created user
wProfile p = wProfile.GetProfile(Membership.GetUser().UserName);
//ProfileCommon p =
(ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);
// Populate some Profile properties. Values are located in web.config
file
p.ProfileInfo.Company.CompanyName =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeName")).Text;
p.ProfileInfo.Company.Address =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeAddress")).Text;
p.ProfileInfo.Company.City =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeCity")).Text;
p.ProfileInfo.Company.State =
((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ddlStates")).SelectedValue;
p.ProfileInfo.Company.PostalCode =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbOfficeZip")).Text;
p.ProfileInfo.Company.Phone =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbContactPhone")).Text;
p.ProfileInfo.Company.Fax =
((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txbContactFax")).Text;
p.ProfileInfo.Preferences.Newsletter =
((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ddlNewsletter")).SelectedValue;
// Save profile - must be done since we explicitly created it
p.Save();
}
This build and runs okay but the following line always gives a null exception
wProfile p = wProfile.GetProfile(Membership.GetUser().UserName);
I'm not sure what is wrong? I've also tried the example in the bottom of
this link with no success
EDIT:
I have read lots of links and tried several of the solutions but my
expertise is this area is not great. I guess I'm asking for a bit of help
with syntax to get it running, I'll prob offer a bounty once I can.