How to expense $(a+b)^\alpha$ into multinomial with $\alpha \in \mathbb{R}$?
As we all know, the binomial expension is as follows $$ (a+b)^2 = a^2 +2ab
+b^2. $$ When the power number is a real number, not a integral, how to
expense $(a+b)^\alpha$ into multinomial with $\alpha \in \mathbb{R}$?
Monday, 30 September 2013
What offers better protection=?iso-8859-1?Q?=3F_=96_gaming.stackexchange.com?=
What offers better protection? – gaming.stackexchange.com
I crafted an iron chestplate and enchanted it with Projectile Protection
III, using a book that I found in a mine shaft. Once I found diamonds, I
crafted a diamond chestplate without thinking. I then …
I crafted an iron chestplate and enchanted it with Projectile Protection
III, using a book that I found in a mine shaft. Once I found diamonds, I
crafted a diamond chestplate without thinking. I then …
JPA - Could not locate named parameter
JPA - Could not locate named parameter
I try to delete rows from a table that lived more than a given time in
days. The start of a row is a timestamp.
EntityManager em = ...
long interval = ... // long value read from a properties file
String template = "DELETE FROM %s WHERE currentTimestamp - start >
:interval";
String jpql = String.format(template , MyClass.class.getCanonicalName());
Query q = em.createQuery(jpql);
q.setParameter("interval", TimeUnit.DAYS.toMillis(interval));
q.executeUpdate();
MyClass.java
@Entity
@Table(name = "ROWS")
public class MyClass implements Serializable {
private static final long serialVersionUID = 6070604872038740340L;
puyblic MyClass() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
However, I get the following exception :
org.hibernate.QueryParameterException: could not locate named parameter
[interval]
What am I doing wrong ?
I try to delete rows from a table that lived more than a given time in
days. The start of a row is a timestamp.
EntityManager em = ...
long interval = ... // long value read from a properties file
String template = "DELETE FROM %s WHERE currentTimestamp - start >
:interval";
String jpql = String.format(template , MyClass.class.getCanonicalName());
Query q = em.createQuery(jpql);
q.setParameter("interval", TimeUnit.DAYS.toMillis(interval));
q.executeUpdate();
MyClass.java
@Entity
@Table(name = "ROWS")
public class MyClass implements Serializable {
private static final long serialVersionUID = 6070604872038740340L;
puyblic MyClass() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
However, I get the following exception :
org.hibernate.QueryParameterException: could not locate named parameter
[interval]
What am I doing wrong ?
my website page body content doesn't display correctly in some browsers
my website page body content doesn't display correctly in some browsers
my website page (HTML web site) body content doesn't display correctly in
some browsers.
i's using chrome and it's working fine. but my friends machine, it's not
working. he also use chrome.
thank you very much
my website page (HTML web site) body content doesn't display correctly in
some browsers.
i's using chrome and it's working fine. but my friends machine, it's not
working. he also use chrome.
thank you very much
Sunday, 29 September 2013
Does anyone have any idea how to run an interpolation search on a linked list in C++?
Does anyone have any idea how to run an interpolation search on a linked
list in C++?
int List::interpolationSearch(int id){
Node low = head;
Node mid;
Node high = tail;
}
I don't have any code, I just have absolutely no idea how I would do this
with the exception of assigning a few temporary nodes to the head and the
tail in order to set the the search range into which I would run the
interpolation. Basically this is all I've been able to come up with by
observing the interpolation search used with arrays. With those three
things in mind, I'm searching for an id, but here's where the problem
comes in. How do I know where to tell the method where to start searching.
I've seen the code for an array but I can't figure out how to do it here.
list in C++?
int List::interpolationSearch(int id){
Node low = head;
Node mid;
Node high = tail;
}
I don't have any code, I just have absolutely no idea how I would do this
with the exception of assigning a few temporary nodes to the head and the
tail in order to set the the search range into which I would run the
interpolation. Basically this is all I've been able to come up with by
observing the interpolation search used with arrays. With those three
things in mind, I'm searching for an id, but here's where the problem
comes in. How do I know where to tell the method where to start searching.
I've seen the code for an array but I can't figure out how to do it here.
Disable right click menu on click
Disable right click menu on click
I am trying to build a minesweeper game with php and jquery. This means I
want the user to be able to right-click elements to mark areas as a
potential bomb or a questionmark. Now I have the right click event and the
code works, however if I don't alert anything I get the menu with inspect
element etc. I've tried throwing in some return false's but they haven't
helped. How can I stop the menu appearing on right-click?
$('.overlay').mousedown(function(event) {
switch (event.which) {
case 1:
//left click code
break;
case 3:
theID = event.target.id;
if ($('#'+theID).is(":visible") &&
$('.bomb_'+theID).css("visibility") == "hidden"
&& $('.mystery_'+theID).css("visibility") == "hidden"){
$('#'+theID).css("background", "none");
$('.bomb_'+theID).css("visibility", "visible");
alert("x");
}else if($('.bomb_'+theID).is(":visible")){
$('.bomb_'+theID).css("visibility", "hidden");
$('.mystery_'+theID).css("visibility", "visible");
alert("y");
}else{
$('.mystery_'+theID).css("visibility", "hidden");
$('#'+theID).css("background", "#fff");
alert("z");
}
break;
}
});
Have tried to add event.preventDefault(); under the mousedown function but
this doesn't change anything. Also tried it under case 3:.
I am trying to build a minesweeper game with php and jquery. This means I
want the user to be able to right-click elements to mark areas as a
potential bomb or a questionmark. Now I have the right click event and the
code works, however if I don't alert anything I get the menu with inspect
element etc. I've tried throwing in some return false's but they haven't
helped. How can I stop the menu appearing on right-click?
$('.overlay').mousedown(function(event) {
switch (event.which) {
case 1:
//left click code
break;
case 3:
theID = event.target.id;
if ($('#'+theID).is(":visible") &&
$('.bomb_'+theID).css("visibility") == "hidden"
&& $('.mystery_'+theID).css("visibility") == "hidden"){
$('#'+theID).css("background", "none");
$('.bomb_'+theID).css("visibility", "visible");
alert("x");
}else if($('.bomb_'+theID).is(":visible")){
$('.bomb_'+theID).css("visibility", "hidden");
$('.mystery_'+theID).css("visibility", "visible");
alert("y");
}else{
$('.mystery_'+theID).css("visibility", "hidden");
$('#'+theID).css("background", "#fff");
alert("z");
}
break;
}
});
Have tried to add event.preventDefault(); under the mousedown function but
this doesn't change anything. Also tried it under case 3:.
Access Jquery UI using primefaces
Access Jquery UI using primefaces
I am building a JSF application and want to convert a simple h:link to
look like a button using jquery ui button widget. I am using JSF2 and
primefaces 3.5.
I manually added the jquery-ui.js and have the following xhtml:
<h:link styleClass="linkGr"
outcome="#{listadoUsuario.verUser(user.username)}">ver</h:link>
<script>$(".linkGr").button({icons: {primary: "ui-icon-pencil"},text:
false});</script>
Having this in a page works fine, but in other pages, I see the following
error:
TypeError: Object function (f,h,e){var
g=f.split(".")[0],j;f=f.split(".")[1];j=g+"-"+f;if(!e){e=h;h=b.Widget}b.expr[":"][j]=function(k){return
!!b.data(k,f)};b[g]=b[g]||{};b[g][f]=function(k,l){if(arguments.length){this._createWidget(k,l)}};var
i=new
h();i.options=b.extend(true,{},i.options);b[g][f].prototype=b.extend(true,i,{namespace:g,widgetName:f,widgetEventPrefix:b[g][f].prototype.widgetEventPrefix||f,widgetBaseClass:j},e);b.widget.bridge(f,b[g][f])}
has no method 'extend'
I noted that this happens in pages where primefaces adds the
jquery-plugins.js.
I tried not including the jquery-ui javascript manually since I see the
jquery-plugins adds the button widget, but the problem is when adding
jquery-plugins (not including jquery-ui.js) I cannot see how to convert
the link to a button. The function button is not available in $. Can
somebody guide me on how to use primefaces included button method?
Thanks in advance!
I am building a JSF application and want to convert a simple h:link to
look like a button using jquery ui button widget. I am using JSF2 and
primefaces 3.5.
I manually added the jquery-ui.js and have the following xhtml:
<h:link styleClass="linkGr"
outcome="#{listadoUsuario.verUser(user.username)}">ver</h:link>
<script>$(".linkGr").button({icons: {primary: "ui-icon-pencil"},text:
false});</script>
Having this in a page works fine, but in other pages, I see the following
error:
TypeError: Object function (f,h,e){var
g=f.split(".")[0],j;f=f.split(".")[1];j=g+"-"+f;if(!e){e=h;h=b.Widget}b.expr[":"][j]=function(k){return
!!b.data(k,f)};b[g]=b[g]||{};b[g][f]=function(k,l){if(arguments.length){this._createWidget(k,l)}};var
i=new
h();i.options=b.extend(true,{},i.options);b[g][f].prototype=b.extend(true,i,{namespace:g,widgetName:f,widgetEventPrefix:b[g][f].prototype.widgetEventPrefix||f,widgetBaseClass:j},e);b.widget.bridge(f,b[g][f])}
has no method 'extend'
I noted that this happens in pages where primefaces adds the
jquery-plugins.js.
I tried not including the jquery-ui javascript manually since I see the
jquery-plugins adds the button widget, but the problem is when adding
jquery-plugins (not including jquery-ui.js) I cannot see how to convert
the link to a button. The function button is not available in $. Can
somebody guide me on how to use primefaces included button method?
Thanks in advance!
How to show Listview detail in Edit Text on button Click
How to show Listview detail in Edit Text on button Click
How I get contact no detail in textview with checkbox with it, soo that
when I click on check box and add it on button it shows the Contact number
detail in Editbox. Plz clearify with the proper tutorial
How I get contact no detail in textview with checkbox with it, soo that
when I click on check box and add it on button it shows the Contact number
detail in Editbox. Plz clearify with the proper tutorial
Saturday, 28 September 2013
Install Spring through maven
Install Spring through maven
I am new in using maven, I am having a java class as follow:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DecoupledDataReaderClient {
private IReader reader = null;
private ApplicationContext ctx = null;
public DecoupledDataReaderClient() {
ctx = new ClassPathXmlApplicationContext("basics-reader-beans.xml");
}
private String fetchData() {
reader = (IReader) ctx.getBean("reader");
return reader.read();
}
public static void main(String[] args) {
DecoupledDataReaderClient client = new DecoupledDataReaderClient();
System.out.println("Example 1.3: Got data: " + client.fetchData());
}
}
I am having an ant built file as follow:
<target name="init">
<artifact:dependencies pathId="dependency.classpath">
<dependency
groupId="org.springframework"
artifactId="spring-context"
version="3.2.1.RELEASE"
/>
</artifact:dependencies>
</target>
<target name="compile" depends="init">
<mkdir dir="classes"/>
<javac srcdir="${src}" destdir="${dest}" includeantruntime="false">
</javac>
</target>
<target name="jar" depends="compile">
<mkdir dir="${build}"/>
<jar destfile="${jar}" basedir="${dest}">
<manifest>
<attribute name="Main-Class"
value="src.DecoupledDataReaderClient"/>
</manifest>
</jar>
</target>
<target name="run" depends="jar">
<java jar="${jar}" fork="true"/>
</target>
When I run the ant built file I get the error:
error: package org.springframework.context does not exist
error: package org.springframework.context.support does not exist
Is there anything else I have to include in my ant file to make it run?
I am new in using maven, I am having a java class as follow:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DecoupledDataReaderClient {
private IReader reader = null;
private ApplicationContext ctx = null;
public DecoupledDataReaderClient() {
ctx = new ClassPathXmlApplicationContext("basics-reader-beans.xml");
}
private String fetchData() {
reader = (IReader) ctx.getBean("reader");
return reader.read();
}
public static void main(String[] args) {
DecoupledDataReaderClient client = new DecoupledDataReaderClient();
System.out.println("Example 1.3: Got data: " + client.fetchData());
}
}
I am having an ant built file as follow:
<target name="init">
<artifact:dependencies pathId="dependency.classpath">
<dependency
groupId="org.springframework"
artifactId="spring-context"
version="3.2.1.RELEASE"
/>
</artifact:dependencies>
</target>
<target name="compile" depends="init">
<mkdir dir="classes"/>
<javac srcdir="${src}" destdir="${dest}" includeantruntime="false">
</javac>
</target>
<target name="jar" depends="compile">
<mkdir dir="${build}"/>
<jar destfile="${jar}" basedir="${dest}">
<manifest>
<attribute name="Main-Class"
value="src.DecoupledDataReaderClient"/>
</manifest>
</jar>
</target>
<target name="run" depends="jar">
<java jar="${jar}" fork="true"/>
</target>
When I run the ant built file I get the error:
error: package org.springframework.context does not exist
error: package org.springframework.context.support does not exist
Is there anything else I have to include in my ant file to make it run?
jquery json getting all the parts of an object
jquery json getting all the parts of an object
I have a json file set up with some objects like so:
{
"everfi_commons":{
"info" : {
"projTotal" : "everfi_Commons",
"company" : "Everfi",
"name" : "Commons",
"type" : "ipad",
"description" : "this product, bla bla bla bla bla",
"folder": "everfi_commons",
"thumbProjName": "COMMONS",
"thumbDescription" : "bla bla bla bla bla"
},
"images" : {
"image_1" : "image one url",
"image_2" : "image two url",
"image_3" : "image three url",
"image_4" : "image four url"
}
},
"project_two":{
"info" : {
"projTotal" : "project_two",
"company" : "Everfi",
"name" : "Commons",
"type" : "html5",
"description" : "this product, bla bla bla bla bla",
"folder": "project_two",
"thumbProjName": "COMPANY 2",
"thumbDescription" : "bla bla bla bla bla"
},
"images" : {
"image_1" : "image one url",
"image_2" : "image two url",
"image_3" : "image three url",
"image_4" : "image four url",
"image_5" : "image five url"
}
}
}
I know how to access very specific parts of the objects, but what I'm
wondering is, if there is a way to get into everfi_commons.images and then
get all of the image urls no matter how many are listed and put them into
a div?
Thanks for any help I can get!
I have a json file set up with some objects like so:
{
"everfi_commons":{
"info" : {
"projTotal" : "everfi_Commons",
"company" : "Everfi",
"name" : "Commons",
"type" : "ipad",
"description" : "this product, bla bla bla bla bla",
"folder": "everfi_commons",
"thumbProjName": "COMMONS",
"thumbDescription" : "bla bla bla bla bla"
},
"images" : {
"image_1" : "image one url",
"image_2" : "image two url",
"image_3" : "image three url",
"image_4" : "image four url"
}
},
"project_two":{
"info" : {
"projTotal" : "project_two",
"company" : "Everfi",
"name" : "Commons",
"type" : "html5",
"description" : "this product, bla bla bla bla bla",
"folder": "project_two",
"thumbProjName": "COMPANY 2",
"thumbDescription" : "bla bla bla bla bla"
},
"images" : {
"image_1" : "image one url",
"image_2" : "image two url",
"image_3" : "image three url",
"image_4" : "image four url",
"image_5" : "image five url"
}
}
}
I know how to access very specific parts of the objects, but what I'm
wondering is, if there is a way to get into everfi_commons.images and then
get all of the image urls no matter how many are listed and put them into
a div?
Thanks for any help I can get!
Background and foreground apps using audio
Background and foreground apps using audio
I did some preliminary test and have a good idea the answer is no. But
just need to confirm: Can a background and foreground app share audio
playback device? (The background app will be mine. The foreground app will
be from third party)
I did some preliminary test and have a good idea the answer is no. But
just need to confirm: Can a background and foreground app share audio
playback device? (The background app will be mine. The foreground app will
be from third party)
Function with multiple if or with a "big" return?
Function with multiple if or with a "big" return?
I would like to know if one of this two solution is better than the other :
Version 1:
bool myFunction()
{
if (A)
return false;
if (B)
return false;
if (C)
return false;
if (D)
return false;
return true;
}
Version 2 :
bool myFunction()
{
return (!A && !B && !C && !D);
}
I guessed that version 2 may be a bit less efficient as we may have to
calculate the whole boolean expression to know if it's true or false. In
the first version, if A is false, it returns false, without calculating B,
C or D. But I find second version much more readable.
So what is the best way to do that ?
Thank you.
I would like to know if one of this two solution is better than the other :
Version 1:
bool myFunction()
{
if (A)
return false;
if (B)
return false;
if (C)
return false;
if (D)
return false;
return true;
}
Version 2 :
bool myFunction()
{
return (!A && !B && !C && !D);
}
I guessed that version 2 may be a bit less efficient as we may have to
calculate the whole boolean expression to know if it's true or false. In
the first version, if A is false, it returns false, without calculating B,
C or D. But I find second version much more readable.
So what is the best way to do that ?
Thank you.
Friday, 27 September 2013
FullCalendar no refetch events
FullCalendar no refetch events
I have worked with fullcalendar smoothly for a while, now I feel the need
to implement some changes. I need to filter the events, this has been
helpful http://jsfiddle.net/QMyFu/337/, but I can not reset the filters
and redisplay all events,
javascript code:
$('#boton').click(function(){
$("#calendar").fullCalendar( 'refetchEvents' );
});
html code:
<button id="boton">Reload</button>
here I made a fiddle http://jsfiddle.net/pablop22/eT26Q/2/
any suggestions are welcome
Pablo
I have worked with fullcalendar smoothly for a while, now I feel the need
to implement some changes. I need to filter the events, this has been
helpful http://jsfiddle.net/QMyFu/337/, but I can not reset the filters
and redisplay all events,
javascript code:
$('#boton').click(function(){
$("#calendar").fullCalendar( 'refetchEvents' );
});
html code:
<button id="boton">Reload</button>
here I made a fiddle http://jsfiddle.net/pablop22/eT26Q/2/
any suggestions are welcome
Pablo
Where Does Direct3D11 Allocate Resource Objects?
Where Does Direct3D11 Allocate Resource Objects?
I've been reading up on Direct3D11 a lot (including right here on stack
overflow!) and in all my research I haven't been able to conclusively
answer this question:
When a Resource object (i.e. a Buffer or a Texture object) is created, for
example with pDevice->CreateBuffer(), where is it stored? On system RAM or
on the GPU's Video-RAM? Or am I entirely misunderstanding the fundamental
nature of what a Resource object is?
Obviously whatever data you populate the resource with (such as vertex and
index arrays) is stored wherever you - the programmer - placed it, but
once you map that data to the Resource where is it copied? (I'm assuming
that, since Resources have to be mapped and unmapped for read/write
protection the mapped data is in fact copied, perhaps to VRAM). Moreover,
where is the Resource object itself instantiated?
Thanks in advance for any and all help!
I've been reading up on Direct3D11 a lot (including right here on stack
overflow!) and in all my research I haven't been able to conclusively
answer this question:
When a Resource object (i.e. a Buffer or a Texture object) is created, for
example with pDevice->CreateBuffer(), where is it stored? On system RAM or
on the GPU's Video-RAM? Or am I entirely misunderstanding the fundamental
nature of what a Resource object is?
Obviously whatever data you populate the resource with (such as vertex and
index arrays) is stored wherever you - the programmer - placed it, but
once you map that data to the Resource where is it copied? (I'm assuming
that, since Resources have to be mapped and unmapped for read/write
protection the mapped data is in fact copied, perhaps to VRAM). Moreover,
where is the Resource object itself instantiated?
Thanks in advance for any and all help!
binding value of text box to an object's property on canvas
binding value of text box to an object's property on canvas
I will appreciate it if experts could give me direction on following
scenario?
Consider a set of entries or we can just focus on one edit box for sake of
simplicity which its input has to be bound to a canvas. let's say user has
to be able to modify the angle of a line in the edit box using keyboard
while this edit box having two arrows (up/down arrow to increase or
decrease a value in the edit box) so mouse would be another option to
change the value and also losing focus should be the third element of
affecting line on canvas. this works almost but my major challenge here is
that sometimes user might remove the value from text box and re-enter a
new value. this is affecting line (or arc or any object) to disappear. how
can this issue be addressed and resolved?
Any advice will be appreciated.
Thanks.
I will appreciate it if experts could give me direction on following
scenario?
Consider a set of entries or we can just focus on one edit box for sake of
simplicity which its input has to be bound to a canvas. let's say user has
to be able to modify the angle of a line in the edit box using keyboard
while this edit box having two arrows (up/down arrow to increase or
decrease a value in the edit box) so mouse would be another option to
change the value and also losing focus should be the third element of
affecting line on canvas. this works almost but my major challenge here is
that sometimes user might remove the value from text box and re-enter a
new value. this is affecting line (or arc or any object) to disappear. how
can this issue be addressed and resolved?
Any advice will be appreciated.
Thanks.
NameError on "recursive StructuredProperty" in GAE ndb
NameError on "recursive StructuredProperty" in GAE ndb
I've modeled a data structure in GAE using ndb that is "recursive" in that
I want it to store an instance of the same structured type within it.
Conceptually,
class Person(ndb.Model):
name = ndb.StringProperty()
friend = ndb.StructuredProperty(Person)
I'm getting the following error:
Traceback (most recent call last):
File "C:\Program Files
(x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line
239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files
(x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line
298, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "C:\Program Files
(x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line
84, in LoadObject
obj = __import__(path[0])
File "C:\Users\Rusty\Documents\GitHub\AutoAddDrop\autoadddrop.py", line
2, in <module>
import models
File "C:\Users\Rusty\Documents\GitHub\AutoAddDrop\models.py", line 100,
in <module>
class Bid(ndb.Model):
File "C:\Users\Rusty\Documents\GitHub\AutoAddDrop\models.py", line 123,
in Bid
outbid_by = ndb.StructuredProperty(Bid) #Winning Bid
NameError: name 'Bid' is not defined
Here's the class in models.py:
class Bid(ndb.Model):
user_id = ndb.StringProperty()
league_id = ndb.StringProperty()
sport = ndb.StringProperty()
bid_amount = ndb.IntegerProperty()
timestamp = ndb.DateTimeProperty()
status = ndb.StringProperty()
target_player_id = ndb.StringProperty()
target_player_name = ndb.StringProperty()
target_player_team = ndb.StringProperty()
target_player_position = ndb.StringProperty()
add_player_id = ndb.StringProperty()
add_player_name = ndb.StringProperty()
add_player_team = ndb.StringProperty()
add_player_position = ndb.StringProperty()
drop_player_id = ndb.StringProperty()
drop_player_name = ndb.StringProperty()
drop_player_team = ndb.StringProperty()
drop_player_position = ndb.StringProperty()
bid_type = ndb.StringProperty()
bid_direction = ndb.StringProperty()
target_value = ndb.FloatProperty()
transaction_timestamp = ndb.DateTimeProperty()
outbid_by = ndb.StructuredProperty(Bid) #Winning Bid
outbid_by_key = ndb.KeyProperty(Bid) #key of winning bid
cbs_add_transaction = ndb.JsonProperty()
transaction_reason = ndb.StringProperty()
I've modeled a data structure in GAE using ndb that is "recursive" in that
I want it to store an instance of the same structured type within it.
Conceptually,
class Person(ndb.Model):
name = ndb.StringProperty()
friend = ndb.StructuredProperty(Person)
I'm getting the following error:
Traceback (most recent call last):
File "C:\Program Files
(x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line
239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files
(x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line
298, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "C:\Program Files
(x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line
84, in LoadObject
obj = __import__(path[0])
File "C:\Users\Rusty\Documents\GitHub\AutoAddDrop\autoadddrop.py", line
2, in <module>
import models
File "C:\Users\Rusty\Documents\GitHub\AutoAddDrop\models.py", line 100,
in <module>
class Bid(ndb.Model):
File "C:\Users\Rusty\Documents\GitHub\AutoAddDrop\models.py", line 123,
in Bid
outbid_by = ndb.StructuredProperty(Bid) #Winning Bid
NameError: name 'Bid' is not defined
Here's the class in models.py:
class Bid(ndb.Model):
user_id = ndb.StringProperty()
league_id = ndb.StringProperty()
sport = ndb.StringProperty()
bid_amount = ndb.IntegerProperty()
timestamp = ndb.DateTimeProperty()
status = ndb.StringProperty()
target_player_id = ndb.StringProperty()
target_player_name = ndb.StringProperty()
target_player_team = ndb.StringProperty()
target_player_position = ndb.StringProperty()
add_player_id = ndb.StringProperty()
add_player_name = ndb.StringProperty()
add_player_team = ndb.StringProperty()
add_player_position = ndb.StringProperty()
drop_player_id = ndb.StringProperty()
drop_player_name = ndb.StringProperty()
drop_player_team = ndb.StringProperty()
drop_player_position = ndb.StringProperty()
bid_type = ndb.StringProperty()
bid_direction = ndb.StringProperty()
target_value = ndb.FloatProperty()
transaction_timestamp = ndb.DateTimeProperty()
outbid_by = ndb.StructuredProperty(Bid) #Winning Bid
outbid_by_key = ndb.KeyProperty(Bid) #key of winning bid
cbs_add_transaction = ndb.JsonProperty()
transaction_reason = ndb.StringProperty()
Magento IWD Onepage Checkout and SagePay Issue
Magento IWD Onepage Checkout and SagePay Issue
We have a site developed in Magento with the SagePay Payment Gateway
Integration. With the default Magento Checkout, the Payment is working
fine. But as soon as we turn on the IWD Onepage Checkout extension, we are
not getting any response from the Sagepay server. Instead we are getting
the following error. "Payment has failed, please reload checkout page and
try again. Your card has not been charged."
We really appreciate your help to solve this problem.
Thank you.
We have a site developed in Magento with the SagePay Payment Gateway
Integration. With the default Magento Checkout, the Payment is working
fine. But as soon as we turn on the IWD Onepage Checkout extension, we are
not getting any response from the Sagepay server. Instead we are getting
the following error. "Payment has failed, please reload checkout page and
try again. Your card has not been charged."
We really appreciate your help to solve this problem.
Thank you.
Thursday, 26 September 2013
automatically open gmail from my website using a form and php
automatically open gmail from my website using a form and php
is it possible to open gmail directly from my website using php?
let say my username and password for my gmail is on my sql database then i
have a form ready
<form id="gaia_loginform"
action="https://www.google.com/a/telexperience.com/LoginAction2?service=mail"
method="post" onsubmit="return(gaia_onLoginSubmit());">
<div id="gaia_loginbox">
<table class="form-noindent" cellspacing="3" cellpadding="5" width="100%"
border="0">
<tbody><tr>
<td valign="top" style="text-align:center" nowrap="nowrap"
bgcolor="e8e8e8">
<input type="hidden" name="ltmpl" value="default">
<input type="hidden" name="ltmplcache" value="2">
<div class="loginBox">
<table id="gaia_table" align="center" border="0" cellpadding="1"
cellspacing="0">
<tbody><tr>
<td class="smallfont" colspan="2" align="center">
Sign in to your account at
<h2>
Telexperience</h2>
</td>
</tr>
<tr>
<td colspan="2" align="center">
</td>
</tr>
<tr id="email-row">
<td nowrap="nowrap">
<div align="right">
<span class="gaia le lbl">
Username:
</span>
</div>
</td>
<td>
<input type="hidden" name="continue" id="continue"
value="https://mail.google.com/a/telexperience.com/">
<input type="hidden" name="service" id="service" value="mail">
<input type="hidden" name="rm" id="rm" value="false">
<input type="hidden" name="dsh" id="dsh" value="7026183628507023366">
<input type="hidden" name="ltmpl" id="ltmpl" value="default">
<input type="hidden" name="ss" id="ss" value="1">
<input type="hidden" name="timeStmp" id="timeStmp" value="">
<input type="hidden" name="secTok" id="secTok" value="">
<input type="hidden" name="GALX" value="jcN_8U_OyMA">
<input type="text" name="Email" id="Email" size="18" value=""
class="gaia le val">
</td>
</tr>
<tr>
<td></td>
<td align="right" style="color: #444444; font-size: 75%; overflow:
hidden;" dir="ltr">
@telexperience.com
</td>
<td></td>
</tr>
<tr>
<td></td>
<td align="left">
</td>
</tr>
<tr id="password-row" class="enabled">
<td align="right" nowrap="nowrap">
<span class="gaia le lbl">
Password:
</span>
</td>
<td>
<input type="password" name="Passwd" id="Passwd" size="18" class="gaia
le val">
</td>
</tr>
<tr>
<td> </td>
<td align="left">
</td>
</tr>
<tr id="rememberme-row" class="enabled">
<td align="right" valign="top">
<input type="checkbox" name="PersistentCookie" id="PersistentCookie"
value="yes">
<input type="hidden" name="rmShown" value="1">
</td>
<td>
<label for="PersistentCookie" id="PersistentCookieLabel" class="gaia le
rem">
Stay signed in
</label>
</td>
</tr>
<tr>
<td>
</td>
<td align="left">
<input type="submit" class="gaia le button" name="signIn" id="signIn"
value="Sign in">
</td>
</tr>
<tr id="ga-fprow">
<td colspan="2" height="33.0" class="gaia le fpwd" align="center"
valign="bottom">
<a id="link-forgot-passwd"
href="https://www.google.com/accounts/recovery" target="_top">
Can't access your account?
</a>
</td>
</tr>
</tbody></table>
</div>
</td>
</tr>
</tbody></table>
</div>
<input type="hidden" name="asts" id="asts" value="">
then it will auto send the form to gmail when i run the php page, it will
get the username and password from the database and open my gmail
automatically,, will that be possible or is there any code for this
already?
the reason why i want this is that i would want my users to be able to
open their gmails without them knowing the password, they would have to go
to a link that i provided to be able to open the gmails assigned to them.
is it possible to open gmail directly from my website using php?
let say my username and password for my gmail is on my sql database then i
have a form ready
<form id="gaia_loginform"
action="https://www.google.com/a/telexperience.com/LoginAction2?service=mail"
method="post" onsubmit="return(gaia_onLoginSubmit());">
<div id="gaia_loginbox">
<table class="form-noindent" cellspacing="3" cellpadding="5" width="100%"
border="0">
<tbody><tr>
<td valign="top" style="text-align:center" nowrap="nowrap"
bgcolor="e8e8e8">
<input type="hidden" name="ltmpl" value="default">
<input type="hidden" name="ltmplcache" value="2">
<div class="loginBox">
<table id="gaia_table" align="center" border="0" cellpadding="1"
cellspacing="0">
<tbody><tr>
<td class="smallfont" colspan="2" align="center">
Sign in to your account at
<h2>
Telexperience</h2>
</td>
</tr>
<tr>
<td colspan="2" align="center">
</td>
</tr>
<tr id="email-row">
<td nowrap="nowrap">
<div align="right">
<span class="gaia le lbl">
Username:
</span>
</div>
</td>
<td>
<input type="hidden" name="continue" id="continue"
value="https://mail.google.com/a/telexperience.com/">
<input type="hidden" name="service" id="service" value="mail">
<input type="hidden" name="rm" id="rm" value="false">
<input type="hidden" name="dsh" id="dsh" value="7026183628507023366">
<input type="hidden" name="ltmpl" id="ltmpl" value="default">
<input type="hidden" name="ss" id="ss" value="1">
<input type="hidden" name="timeStmp" id="timeStmp" value="">
<input type="hidden" name="secTok" id="secTok" value="">
<input type="hidden" name="GALX" value="jcN_8U_OyMA">
<input type="text" name="Email" id="Email" size="18" value=""
class="gaia le val">
</td>
</tr>
<tr>
<td></td>
<td align="right" style="color: #444444; font-size: 75%; overflow:
hidden;" dir="ltr">
@telexperience.com
</td>
<td></td>
</tr>
<tr>
<td></td>
<td align="left">
</td>
</tr>
<tr id="password-row" class="enabled">
<td align="right" nowrap="nowrap">
<span class="gaia le lbl">
Password:
</span>
</td>
<td>
<input type="password" name="Passwd" id="Passwd" size="18" class="gaia
le val">
</td>
</tr>
<tr>
<td> </td>
<td align="left">
</td>
</tr>
<tr id="rememberme-row" class="enabled">
<td align="right" valign="top">
<input type="checkbox" name="PersistentCookie" id="PersistentCookie"
value="yes">
<input type="hidden" name="rmShown" value="1">
</td>
<td>
<label for="PersistentCookie" id="PersistentCookieLabel" class="gaia le
rem">
Stay signed in
</label>
</td>
</tr>
<tr>
<td>
</td>
<td align="left">
<input type="submit" class="gaia le button" name="signIn" id="signIn"
value="Sign in">
</td>
</tr>
<tr id="ga-fprow">
<td colspan="2" height="33.0" class="gaia le fpwd" align="center"
valign="bottom">
<a id="link-forgot-passwd"
href="https://www.google.com/accounts/recovery" target="_top">
Can't access your account?
</a>
</td>
</tr>
</tbody></table>
</div>
</td>
</tr>
</tbody></table>
</div>
<input type="hidden" name="asts" id="asts" value="">
then it will auto send the form to gmail when i run the php page, it will
get the username and password from the database and open my gmail
automatically,, will that be possible or is there any code for this
already?
the reason why i want this is that i would want my users to be able to
open their gmails without them knowing the password, they would have to go
to a link that i provided to be able to open the gmails assigned to them.
Wednesday, 25 September 2013
Programming languages without static properties/methods?
Programming languages without static properties/methods?
Well I wonder if there are OO programming languages that do not have
statics in their language construct(either static keyword or anything
equivalent to declare something as static), therefore eliminating the
presence of static properties/methods. Statics are not really OOP, they
are procedural code in disguise and usually are considered bad smells in
OO software.
If a language has powerful dependency injection support while does not
support statics/globals, it will enforce way better OO practices. I
personally think in Java and C# statics should be removed from language
core by their next releases. But until then, I'd like to know if there
already exist programming languages that already eliminate the presence of
static bad smell?
Well I wonder if there are OO programming languages that do not have
statics in their language construct(either static keyword or anything
equivalent to declare something as static), therefore eliminating the
presence of static properties/methods. Statics are not really OOP, they
are procedural code in disguise and usually are considered bad smells in
OO software.
If a language has powerful dependency injection support while does not
support statics/globals, it will enforce way better OO practices. I
personally think in Java and C# statics should be removed from language
core by their next releases. But until then, I'd like to know if there
already exist programming languages that already eliminate the presence of
static bad smell?
Thursday, 19 September 2013
QSorting an array of doubles
QSorting an array of doubles
I'm new to using qsort, and I'm attempting to qsort a predefined array of
doubles, unfortunately the result I receive is all 0's after the array has
been sorted using qsort. I'm completely lost, and any advice would be
greatly appreciated. Here is the code I am using to sort this array of
doubles.
static int compare (const void * a, const void * b){
if (*(const double*)a > *(const double*)b) return 1;
else if (*(const double*)a < *(const double*)b) return -1;
else return 0;
}
double stuff[] = {255, 1, 5, 39.0};
qsort(stuff, 4, sizeof(double), compare);
int i;
for(i = 0; i < 4; i++){
printf("%d %s", stuff[i], " ");
}
I'm new to using qsort, and I'm attempting to qsort a predefined array of
doubles, unfortunately the result I receive is all 0's after the array has
been sorted using qsort. I'm completely lost, and any advice would be
greatly appreciated. Here is the code I am using to sort this array of
doubles.
static int compare (const void * a, const void * b){
if (*(const double*)a > *(const double*)b) return 1;
else if (*(const double*)a < *(const double*)b) return -1;
else return 0;
}
double stuff[] = {255, 1, 5, 39.0};
qsort(stuff, 4, sizeof(double), compare);
int i;
for(i = 0; i < 4; i++){
printf("%d %s", stuff[i], " ");
}
Free and easy HTML to PDF for ASP.Net
Free and easy HTML to PDF for ASP.Net
i have a few html-tables which I wanna have 1:1 in PDF saved as a
export-function in my asp.net website.
it must be free to use, without watermark
or buy-able for max of 10
I found a few html-to-pdf which was very very nice but very expansive...
i have a few html-tables which I wanna have 1:1 in PDF saved as a
export-function in my asp.net website.
it must be free to use, without watermark
or buy-able for max of 10
I found a few html-to-pdf which was very very nice but very expansive...
How can I restructure HTML to remove nested spans using JavaScript?
How can I restructure HTML to remove nested spans using JavaScript?
I need to use JavaScript to reformat input HTML so that the resulting
output HTML is always a sequence of <p> nodes containing only one or more
<span> nodes and each <span> node should contain exactly one #text node.
To provide an example, I'd like to convert HTML which looks like this:
<p style="color:red">This is line #1</p>
<p style="color:blue"><span style="color:yellow"><span
style="color:red">This is</span> line #2</span></p>
To HTML which looks like this:
<p style="color:red"><span style="color:red">This is line #1</span></p>
<p style="color:red"><span style="color:red">This is</span><span
style="color:yellow"> line #2</span></p>
Additional, somewhat tangential information:
The text is within a TinyMCE editor. The HTML needs to conform to this
pattern to make the application more usable and to provide a PDF output
engine with usable HTML (wkhtmltopdf has line height issues if the HTMl
gets too complex and nested spans cause editing in TinyMCE to be
non-intuitive)
jQuery is not available. Prototype.JS is available in the parent window
but not directly in this document. I'm capable of reformatting jQuery code
to pure JavaScript myself but can't actually use jQuery in this instance
:-(
Yes, I have existing code. The logic is clearly so horribly wrong that
it's not worth sharing right now. I'm working to improve it right now and
will share it if I can get it even reasonably close so it would be useful
I really do know what I'm doing! I've just been staring at this code too
long and so the proper algorithm to use is evading me right now...
I need to use JavaScript to reformat input HTML so that the resulting
output HTML is always a sequence of <p> nodes containing only one or more
<span> nodes and each <span> node should contain exactly one #text node.
To provide an example, I'd like to convert HTML which looks like this:
<p style="color:red">This is line #1</p>
<p style="color:blue"><span style="color:yellow"><span
style="color:red">This is</span> line #2</span></p>
To HTML which looks like this:
<p style="color:red"><span style="color:red">This is line #1</span></p>
<p style="color:red"><span style="color:red">This is</span><span
style="color:yellow"> line #2</span></p>
Additional, somewhat tangential information:
The text is within a TinyMCE editor. The HTML needs to conform to this
pattern to make the application more usable and to provide a PDF output
engine with usable HTML (wkhtmltopdf has line height issues if the HTMl
gets too complex and nested spans cause editing in TinyMCE to be
non-intuitive)
jQuery is not available. Prototype.JS is available in the parent window
but not directly in this document. I'm capable of reformatting jQuery code
to pure JavaScript myself but can't actually use jQuery in this instance
:-(
Yes, I have existing code. The logic is clearly so horribly wrong that
it's not worth sharing right now. I'm working to improve it right now and
will share it if I can get it even reasonably close so it would be useful
I really do know what I'm doing! I've just been staring at this code too
long and so the proper algorithm to use is evading me right now...
Visual C , Arrays as field variables
Visual C , Arrays as field variables
I'm writing a program for opinion poles and I use the class 'Person',
class Person
{ protected: //field variables
int a; //just an example without importance
...
int answer[Nquestions]; //Nquestions is a constant. answer = {0,2}.
public: //constructor + methods
};
The compiler doesn't accept the array. 'Mixed types non supported', it
says. Is there a workaround of this problem?
Thanks and regards
Uwe
I'm writing a program for opinion poles and I use the class 'Person',
class Person
{ protected: //field variables
int a; //just an example without importance
...
int answer[Nquestions]; //Nquestions is a constant. answer = {0,2}.
public: //constructor + methods
};
The compiler doesn't accept the array. 'Mixed types non supported', it
says. Is there a workaround of this problem?
Thanks and regards
Uwe
How to create a CouchDB View to join documents based on multiple, non-unique fields
How to create a CouchDB View to join documents based on multiple,
non-unique fields
I have a database with documents in the following forms:
{"Type" : "A", "Date": "2013-09-19", "Week" : "A", "Day" : "Mon"}
{"Type" : "B", "Week" : "A", "Day" : "Mon", "Class" : "xyz"}
How do I create a view that will list all the classes (from doc.Type =
"B") for a specific date (from doc.Type = "A")? Essentially it means
matching the "Week" and "Day" fields. I have found examples (mostly based
on Christopher Lenz's solution) but these are matching based on just one
field being matched, which is unique in one of the document types.
non-unique fields
I have a database with documents in the following forms:
{"Type" : "A", "Date": "2013-09-19", "Week" : "A", "Day" : "Mon"}
{"Type" : "B", "Week" : "A", "Day" : "Mon", "Class" : "xyz"}
How do I create a view that will list all the classes (from doc.Type =
"B") for a specific date (from doc.Type = "A")? Essentially it means
matching the "Week" and "Day" fields. I have found examples (mostly based
on Christopher Lenz's solution) but these are matching based on just one
field being matched, which is unique in one of the document types.
Joining 2 Database Tables Getting A Sum Value Output
Joining 2 Database Tables Getting A Sum Value Output
I am wanting to group values together based on which user it assigned to.
Here are the tables:
TABLE1 ID, COMPANY_ID, OPPORTUNITY, DATE_CREATE
TABLE2 ID, ASSIGNED_BY_ID
The two fields that link the two tables together are: TABLE1 > COMPANY_ID
and TABLE2 > ID
Basically I need to do a statement similar to this:
SELECT SUM(OPPORTUNITY) AS total FROM table1 WHERE DATE_CREATE BETWEEN
'$fromdate' AND '$todate' AND ASSIGNED_BY_ID=1 FROM table2
I know I have to join the two tables together where COMPANY_ID from table1
= ID from table2
But I have no idea how to impliment this in the statement.
Any help would be appreciated.
Thanks, Andy
I am wanting to group values together based on which user it assigned to.
Here are the tables:
TABLE1 ID, COMPANY_ID, OPPORTUNITY, DATE_CREATE
TABLE2 ID, ASSIGNED_BY_ID
The two fields that link the two tables together are: TABLE1 > COMPANY_ID
and TABLE2 > ID
Basically I need to do a statement similar to this:
SELECT SUM(OPPORTUNITY) AS total FROM table1 WHERE DATE_CREATE BETWEEN
'$fromdate' AND '$todate' AND ASSIGNED_BY_ID=1 FROM table2
I know I have to join the two tables together where COMPANY_ID from table1
= ID from table2
But I have no idea how to impliment this in the statement.
Any help would be appreciated.
Thanks, Andy
to get the next character in the string
to get the next character in the string
please help me find the code for getting the next character in the string
for example input string = "abcd" output string = "bcde"
I can able to iterate only one character at the time.
thanks in advance
please help me find the code for getting the next character in the string
for example input string = "abcd" output string = "bcde"
I can able to iterate only one character at the time.
thanks in advance
Wednesday, 18 September 2013
Not able to import git android project in Eclipse
Not able to import git android project in Eclipse
I tried several times to import this git repos into my eclipse and run it
as android application, but no success.
Can someone please suggest me how to import it in correct manner.
I tried several times to import this git repos into my eclipse and run it
as android application, but no success.
Can someone please suggest me how to import it in correct manner.
Dynamic expand UITextView on ios 7
Dynamic expand UITextView on ios 7
I am using this code
CGRect frame = self.mytext.frame;
frame.size.height = self.mytext.contentSize.height;
self.mytext.frame = frame;
but now in ios 7 it doesn`t work. Can anyone knows why or have the same
problem?
I am using this code
CGRect frame = self.mytext.frame;
frame.size.height = self.mytext.contentSize.height;
self.mytext.frame = frame;
but now in ios 7 it doesn`t work. Can anyone knows why or have the same
problem?
Create success message on php form submit
Create success message on php form submit
I'm trying to make a php mail form display a success message upon a
successful submit. I'm new to php and I'm not sure how to make this work.
As it sits now, after submit, the site just reloads at the top of the
page. I'd like it to refresh at the contact div and display a success
message.
Contact div html:
<div class="contact-wrapper" >
<div class="contact">
<div class="contact-left" id="contact">
<?php
if (isset($_REQUEST['email'])) {
echo "Thank you for your message.";
}
$mail_form = include('php/mail_form.php'); ?>
</div> <!-- end div contact -->
Contact from PHP:
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("idc615@gmail.com", "Subject: $subject",
$message, "From: $email" );
header("location: index.php");
}
}
?>
I'm trying to make a php mail form display a success message upon a
successful submit. I'm new to php and I'm not sure how to make this work.
As it sits now, after submit, the site just reloads at the top of the
page. I'd like it to refresh at the contact div and display a success
message.
Contact div html:
<div class="contact-wrapper" >
<div class="contact">
<div class="contact-left" id="contact">
<?php
if (isset($_REQUEST['email'])) {
echo "Thank you for your message.";
}
$mail_form = include('php/mail_form.php'); ?>
</div> <!-- end div contact -->
Contact from PHP:
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("idc615@gmail.com", "Subject: $subject",
$message, "From: $email" );
header("location: index.php");
}
}
?>
dividing two variables in javascript
dividing two variables in javascript
ok, so I am trying to make a midpoint calculator in JavaScript for fun and
to practice with the language, The formula is pretty simple, it is just x1
+ x2 / 2 and y1 + y2 / 2, I want the user to be able to define the x and y
coordinates, and this is what I have come up with:
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excelent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var comma = (",");
var exclam = ("!");
var two = (2)
var x1x2 = (x1 + x2 / two);
var y1y2 = (y2 + y2 / two );
alert(midText + x1x2 + comma + y1y2 + exclam);
for some reason, this is not calculating correctly and turning in wrong
answers, go ahead and try it out. it may be some weird misstype from me, I
am fairly new to javascript, only having worked with the language for an
hour or two. any help would be very much appreciated! thanks in advance!
ok, so I am trying to make a midpoint calculator in JavaScript for fun and
to practice with the language, The formula is pretty simple, it is just x1
+ x2 / 2 and y1 + y2 / 2, I want the user to be able to define the x and y
coordinates, and this is what I have come up with:
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excelent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var comma = (",");
var exclam = ("!");
var two = (2)
var x1x2 = (x1 + x2 / two);
var y1y2 = (y2 + y2 / two );
alert(midText + x1x2 + comma + y1y2 + exclam);
for some reason, this is not calculating correctly and turning in wrong
answers, go ahead and try it out. it may be some weird misstype from me, I
am fairly new to javascript, only having worked with the language for an
hour or two. any help would be very much appreciated! thanks in advance!
how to position column names vertically in datagridview in vb.net
how to position column names vertically in datagridview in vb.net
I appologise in advance if my question may appear silly to you but I have
a problem with positioning column names in a dataGridview vertically. I'm
populating DataGridView using flowing code:
Dim StrQwery As String = "SELECT * FROM employees WHERE employee_id =
(select MAX(employee_id) FROM employees AND registered = 'UNREGISTERED';
Dim smd As MySqlCommand
smd = New MySqlCommand(StrQwery, myconn)
smd.CommandType = CommandType.Text
Dim da As New MySqlDataAdapter(smd)
Dim cb As New MySqlCommandBuilder(da)
Dim ds As New DataSet()
da.Fill(ds)
GridView1.DataSource = ds.Tables(0)
If n = 1 Then
If Not Page.IsPostBack Then
GridView1.DataBind()
End If
Else
GridView1.DataBind()
End If
everything works perfectly except that I need to position account
attributes like name, position, ID number etc not horizontally but
vertically. Something like this:
|NAME | John |
|SURNAME | Philips|
|POSITION| Manager|
and I can't find a way how to do it. Can anyone give me a hint in my
problem please?
many thanks in advance.
I appologise in advance if my question may appear silly to you but I have
a problem with positioning column names in a dataGridview vertically. I'm
populating DataGridView using flowing code:
Dim StrQwery As String = "SELECT * FROM employees WHERE employee_id =
(select MAX(employee_id) FROM employees AND registered = 'UNREGISTERED';
Dim smd As MySqlCommand
smd = New MySqlCommand(StrQwery, myconn)
smd.CommandType = CommandType.Text
Dim da As New MySqlDataAdapter(smd)
Dim cb As New MySqlCommandBuilder(da)
Dim ds As New DataSet()
da.Fill(ds)
GridView1.DataSource = ds.Tables(0)
If n = 1 Then
If Not Page.IsPostBack Then
GridView1.DataBind()
End If
Else
GridView1.DataBind()
End If
everything works perfectly except that I need to position account
attributes like name, position, ID number etc not horizontally but
vertically. Something like this:
|NAME | John |
|SURNAME | Philips|
|POSITION| Manager|
and I can't find a way how to do it. Can anyone give me a hint in my
problem please?
many thanks in advance.
Setting up web payment using paypal
Setting up web payment using paypal
I'm working on a project and they have are planning to add a feature web
payment. I'm glad to say that our client is a technical person and told me
to use the paypal. This is my first time integrating a web payment. I've
read some docs in developers.paypal and i'm planning to use the paypal
express checkout.
Furthermore I'll be developing this using only client side (Angularjs), is
it right decision for me to use paypal express checkout? Will I encounter
some security issue here since its client side? The main idea is upon
successful payment I have to sync an http request that will trigger that
the user has paid.
Sample idea
.success(function(){
$http.post(...)
});
I'm working on a project and they have are planning to add a feature web
payment. I'm glad to say that our client is a technical person and told me
to use the paypal. This is my first time integrating a web payment. I've
read some docs in developers.paypal and i'm planning to use the paypal
express checkout.
Furthermore I'll be developing this using only client side (Angularjs), is
it right decision for me to use paypal express checkout? Will I encounter
some security issue here since its client side? The main idea is upon
successful payment I have to sync an http request that will trigger that
the user has paid.
Sample idea
.success(function(){
$http.post(...)
});
android receives updates from MSSQL database
android receives updates from MSSQL database
I create a native Android app for a university (Java). This app should
show some data (exams, grades etc.) and implements a chat. All this data
is stored on a MSSQL-Server. I am downloading this data via JSON.
My current problem is the chat and update function. Does anyone know how
to realise a Java webservice where the clients can register and the
webservice is checking on the database, if there is an update and/or new
message.
Thanks in advance
I create a native Android app for a university (Java). This app should
show some data (exams, grades etc.) and implements a chat. All this data
is stored on a MSSQL-Server. I am downloading this data via JSON.
My current problem is the chat and update function. Does anyone know how
to realise a Java webservice where the clients can register and the
webservice is checking on the database, if there is an update and/or new
message.
Thanks in advance
Tuesday, 17 September 2013
mysql query on left join where multiple value
mysql query on left join where multiple value
Here is my sql data fiddler http://sqlfiddle.com/#!2/63178/1 wats wrong in
my query please help.
SELECT DISTINCT curr.id,curr.curr_tittle, curr.curr_desc
FROM wp_curriculum curr LEFT JOIN (SELECT DISTINCT * FROM
wp_curriculum_topic WHERE curr_topic IN (4,12)) AS A ON A.curr_id =
curr.id ORDER BY A.id
Here is my sql data fiddler http://sqlfiddle.com/#!2/63178/1 wats wrong in
my query please help.
SELECT DISTINCT curr.id,curr.curr_tittle, curr.curr_desc
FROM wp_curriculum curr LEFT JOIN (SELECT DISTINCT * FROM
wp_curriculum_topic WHERE curr_topic IN (4,12)) AS A ON A.curr_id =
curr.id ORDER BY A.id
Application is being killed while on background
Application is being killed while on background
My application always ends at some point while on background. I have read
that when the cpu usage of the application is low, the application is
being killed automatically. I already included a partial wake lock on my
onCreate method in my application using this code:
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
Then on pause:
protected void onPause()
{
super.onPause();
onBackground = true;
wakeLock.acquire();
Log.w("OnPause", "OnPause");
}
I really don't know how to prevent my application being killed. I also
tried using full wake lock but it is deprecated. Any ideas on how will I
keep my application alive on background? I never want my application to be
killed while on background. Thanks!
My application always ends at some point while on background. I have read
that when the cpu usage of the application is low, the application is
being killed automatically. I already included a partial wake lock on my
onCreate method in my application using this code:
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
Then on pause:
protected void onPause()
{
super.onPause();
onBackground = true;
wakeLock.acquire();
Log.w("OnPause", "OnPause");
}
I really don't know how to prevent my application being killed. I also
tried using full wake lock but it is deprecated. Any ideas on how will I
keep my application alive on background? I never want my application to be
killed while on background. Thanks!
C# - Failing at tranfering data between froms
C# - Failing at tranfering data between froms
I am new to C# and already starting to have some troubles. I have googled
for some hours how to get this done but my program refuses to obey his
master.
My MainForm has a ListBox. Form2 uses a Open File Dialog and should return
the file path to the ListBox in MainForm
This is the code I have in Form2
public void BrowseFileDialog_FileOk(object sender, CancelEventArgs e)
{
string path = BrowseFileDialog.FileName;
MainForm frm = new MainForm();
frm.AppListAdd(path);
}
This is the MainForm
public void AppListAdd (string path)
{
AppList.Items.Add(path);
}
Note: AppList = ListBox
I don't get any error, yet the ListBox remains empty. Thanks for any help.
I am new to C# and already starting to have some troubles. I have googled
for some hours how to get this done but my program refuses to obey his
master.
My MainForm has a ListBox. Form2 uses a Open File Dialog and should return
the file path to the ListBox in MainForm
This is the code I have in Form2
public void BrowseFileDialog_FileOk(object sender, CancelEventArgs e)
{
string path = BrowseFileDialog.FileName;
MainForm frm = new MainForm();
frm.AppListAdd(path);
}
This is the MainForm
public void AppListAdd (string path)
{
AppList.Items.Add(path);
}
Note: AppList = ListBox
I don't get any error, yet the ListBox remains empty. Thanks for any help.
SQL JOIN in 2 tables values and get many values from one column
SQL JOIN in 2 tables values and get many values from one column
I Have two tables as follows:
Antibiotics Patient
id Name id Name AntibioticA AntibioticB AntibioticC
1 A 1 John 1 2 3
2 b 2 Jim 4 2 1
3 c
4 d
I have the following question: What query I must use in order to take a
result like the one below:
John A B C (in case id=1)
Jim D B A (in case id=2)
My main problem is that I cannot search many values in the same column.I
used JOIN command but it allows me to join only one value of Antibiotics
so I take only the first one.
I Have two tables as follows:
Antibiotics Patient
id Name id Name AntibioticA AntibioticB AntibioticC
1 A 1 John 1 2 3
2 b 2 Jim 4 2 1
3 c
4 d
I have the following question: What query I must use in order to take a
result like the one below:
John A B C (in case id=1)
Jim D B A (in case id=2)
My main problem is that I cannot search many values in the same column.I
used JOIN command but it allows me to join only one value of Antibiotics
so I take only the first one.
get the host by address returning no host found in C
get the host by address returning no host found in C
What am I doing wrong, when I pass an IP address, or any IP, it always
fails in the no host found block. Any assistance would be greatly
appreciated.
#include <stdio.h>
#include "unp.h"
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char** argv)
{
struct hostent *he;
struct in_addr **addr_list;
int shouldContinueFlag=0;
int numIpElements = sizeof(he->h_addr_list) / sizeof(he->h_addr_list[0]);
int len = strlen(argv[1]);
struct in_addr ip;
he = gethostbyname(argv[1]);
inet_aton(argv[1], &ip);
char *ip = argv[1];
he= gethostbyaddr((const void *)&ip,len,AF_INET);
if(he!=NULL)
{
printf("%s \n", he->h_name);
shouldContinueFlag=0; printf("The hostname mapped to the IP
address you passed is: \n");
}
else
{
printf("no host name associated with the IP address %s",
argv[1]); //CODE IS ALWAYS IN THIS LOOP!
}
}
What am I doing wrong, when I pass an IP address, or any IP, it always
fails in the no host found block. Any assistance would be greatly
appreciated.
#include <stdio.h>
#include "unp.h"
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char** argv)
{
struct hostent *he;
struct in_addr **addr_list;
int shouldContinueFlag=0;
int numIpElements = sizeof(he->h_addr_list) / sizeof(he->h_addr_list[0]);
int len = strlen(argv[1]);
struct in_addr ip;
he = gethostbyname(argv[1]);
inet_aton(argv[1], &ip);
char *ip = argv[1];
he= gethostbyaddr((const void *)&ip,len,AF_INET);
if(he!=NULL)
{
printf("%s \n", he->h_name);
shouldContinueFlag=0; printf("The hostname mapped to the IP
address you passed is: \n");
}
else
{
printf("no host name associated with the IP address %s",
argv[1]); //CODE IS ALWAYS IN THIS LOOP!
}
}
Rails : ActionView::TemplateError (flag after width)
Rails : ActionView::TemplateError (flag after width)
ActionView::TemplateError (flag after width) on line #3 of
vendor/plugins/exception_notification/views/exception_notifier/_environment.rhtml:
1: <% max = @request.env.keys.max { |a,b| a.length <=> b.length } -%>
2: <% @request.env.keys.sort.each do |key| -%>
3: * <%= "%*-s: %s" % [max.length, key,
filter_sensitive_post_data_from_env(key, @request.env[key].to_s.strip)] %>
4: <% end -%>
5:
6: * Process: <%= $$ %>
what? what does this error mean exactly, how does one fix it?
ActionView::TemplateError (flag after width) on line #3 of
vendor/plugins/exception_notification/views/exception_notifier/_environment.rhtml:
1: <% max = @request.env.keys.max { |a,b| a.length <=> b.length } -%>
2: <% @request.env.keys.sort.each do |key| -%>
3: * <%= "%*-s: %s" % [max.length, key,
filter_sensitive_post_data_from_env(key, @request.env[key].to_s.strip)] %>
4: <% end -%>
5:
6: * Process: <%= $$ %>
what? what does this error mean exactly, how does one fix it?
Sunday, 15 September 2013
Odd result of compiling a C code
Odd result of compiling a C code
I just compiled this source :
#include <stdio.h>
int main()
{
char card_name[0];
puts ("Please enter : ");
scanf("%s", card_name);
int val = 0;
switch(card_name[0]) {
case 'A':
val = 10;
printf("Hello");
break;
case 'B':
val = 20;
break;
default:
val = 0;
}
return 0;
}
I don't know why , But when you enter some words that starts with 'A' you
got this result : The card value is : 11 Why eleven ?
I just compiled this source :
#include <stdio.h>
int main()
{
char card_name[0];
puts ("Please enter : ");
scanf("%s", card_name);
int val = 0;
switch(card_name[0]) {
case 'A':
val = 10;
printf("Hello");
break;
case 'B':
val = 20;
break;
default:
val = 0;
}
return 0;
}
I don't know why , But when you enter some words that starts with 'A' you
got this result : The card value is : 11 Why eleven ?
oracle sql select the table and cumulative calculate the score by the date
oracle sql select the table and cumulative calculate the score by the date
http://i.stack.imgur.com/IDMWU.jpg
here is the table 1 that had some kind of gpa score
one person had some score in several terms
is it possible using select statement to group the term and calculate the
score
http://i.stack.imgur.com/Zkrqu.jpg
1001 201009 (3+1.5)/2=2.25
1001 201101 (3+1.5+2+1)/4=1.875
1001 201109 (3+1.5+2+1+2)/5=1.9
etc....
i am using apex to make a report,it seems it create the table by select
statement
is it possible select the table like that ?
http://i.stack.imgur.com/IDMWU.jpg
here is the table 1 that had some kind of gpa score
one person had some score in several terms
is it possible using select statement to group the term and calculate the
score
http://i.stack.imgur.com/Zkrqu.jpg
1001 201009 (3+1.5)/2=2.25
1001 201101 (3+1.5+2+1)/4=1.875
1001 201109 (3+1.5+2+1+2)/5=1.9
etc....
i am using apex to make a report,it seems it create the table by select
statement
is it possible select the table like that ?
Regex ubdesireably removing substring
Regex ubdesireably removing substring
I'm trying to extract void <init>(java.lang.String) and java.io.File
getOutputMediaFileUri(int) from the string below (and strings like it).
specialinvoke $r1.<java.io.File: void
<init>(java.lang.String)>($r16)@<com.jpgextractor.PicViewerActivity:
java.io.File getOutputMediaFileUri(int)>
Currently, I'm matching to the regex:
/.*<.* (\S+ .*)>.*<.* (\S+ .*)>.*/
Which works, except for instead of void <init>(java.lang.String) I just
get void (java.lang.String).
I'm a bit mistified where <init> has gone off too...I've tried several
different ways to coax it back, but so far no luck.
Thanks folks!
I'm trying to extract void <init>(java.lang.String) and java.io.File
getOutputMediaFileUri(int) from the string below (and strings like it).
specialinvoke $r1.<java.io.File: void
<init>(java.lang.String)>($r16)@<com.jpgextractor.PicViewerActivity:
java.io.File getOutputMediaFileUri(int)>
Currently, I'm matching to the regex:
/.*<.* (\S+ .*)>.*<.* (\S+ .*)>.*/
Which works, except for instead of void <init>(java.lang.String) I just
get void (java.lang.String).
I'm a bit mistified where <init> has gone off too...I've tried several
different ways to coax it back, but so far no luck.
Thanks folks!
Count the number of unique words and occurrence of each word in this program?
Count the number of unique words and occurrence of each word in this program?
CSCI-15 Assignment #2, String processing. (60 points) Due 9/23/13
You MAY NOT use C++ string objects for anything in this program.
Write a C++ program that reads lines of text from a file using the
ifstream getline() method, tokenizes the lines into words ("tokens") using
strtok(), and keeps statistics on the data in the file. Your input and
output file names will be supplied to your program on the command line,
which you will access using argc and argv[].
You need to count the total number of words, the number of unique words,
the count of each individual word, and the number of lines. Also, remember
and print the longest and shortest words in the file. If there is a tie
for longest or shortest word, you may resolve the tie in any consistent
manner (e.g., use either the first one or the last one found, but use the
same method for both longest and shortest). You may assume the lines
comprise words (contiguous lower-case letters [a-z]) separated by spaces,
terminated with a period. You may ignore the possibility of other
punctuation marks, including possessives or contractions, like in "Jim's
house". Lines before the last one in the file will have a newline ('\n')
after the period. In your data files, omit the '\n' on the last line. You
may assume that the lines will be no longer than 100 characters, the
individual words will be no longer than 15 letters and there will be no
more than 100 unique words in the file.
Read the lines from the input file, and echo-print them to the output
file. After reaching end-of-file on the input file (or reading a line of
length zero, which you should treat as the end of the input data), print
the words with their occurrence counts, one word/count pair per line, and
the collected statistics to the output file. You will also need to create
other test files of your own. Also, your program must work correctly with
an EMPTY input file – which has NO statistics.
Test file looks like this (exactly 4 lines, with NO NEWLINE on the last
line):
the quick brown fox jumps over the lazy dog.
now is the time for all good men to come to the aid of their party.
all i want for christmas is my two front teeth.
the quick brown fox jumps over a lazy dog.
Copy and paste this into a small file for one of your tests.
Hints:
Use a 2-dimensional array of char, 100 rows by 16 columns (why not 15?),
to hold the unique words, and a 1-dimensional array of ints with 100
elements to hold the associated counts. For each word, scan through the
occupied lines in the array for a match (use strcmp()), and if you find a
match, increment the associated count, otherwise (you got past the last
word), add the word to the table and set its count to 1.
The separate longest word and the shortest word need to be saved off in
their own C-strings. (Why can't you just keep a pointer to them in the
tokenized data?)
Remember – put NO NEWLINE at the end of the last line, or your test for
end-of-file might not work correctly. (This may cause the program to read
a zero-length line before seeing end-of-file.)
This is not a long program – no more than about 2 pages of code
Here is what I have so far:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<cstring>
using namespace std;
void totalwordCount(ifstream &inputFile)
{
char words[100][16]; // Holds the unique words.
char *token;
int totalCount = 0; // Counts the total number of words.
// Read every word in the file.
while(inputFile >> words[99])
{
totalCount++; // Increment the total number of words.
// Tokenize each word and remove spaces, periods, and newlines.
token = strtok(words[99], " .\n");
while(token != NULL)
{
token = strtok(NULL, " .\n");
}
}
cout << "Total number of words in file: " << totalCount << endl;
}
void uniquewordCount(ifstream &inputFile)
{
char words[100][16]; // Holds the unique words
int counter[100];
char *tok = "0";
int uniqueCount = 0; // Counts the total number of unique words
while(!inputFile.eof())
{
uniqueCount++;
tok = strtok(words[99], " .\n");
while(tok != NULL)
{
tok = strtok(NULL, " .\n");
inputFile >> words[99];
if(strcmp(tok, words[99]) == 0)
{
counter[99]++;
}
else
{
words[99][15] += 1;
}
uniqueCount++;
}
}
cout << counter[99] << endl;
}
int main(int argc, char *argv[])
{
ifstream inputFile;
char inFile[12] = "string1.txt";
char outFile[16] = "word result.txt";
// Get the name of the file from the user.
cout << "Enter the name of the file: ";
cin >> inFile;
// Open the input file.
inputFile.open(inFile);
// If successfully opened, process the data.
if(inputFile)
{
while(!inputFile.eof())
{
totalwordCount(inputFile);
uniquewordCount(inputFile);
}
}
return 0;
}
I already took care of how to count the total number of words in the file
in the totalwordCount() function, but in the uniquewordCount() function, I
am having trouble counting the total number of unique words and counting
the number of occurrences of each word. Is there anything that I need to
change in the uniquewordCount() function?
CSCI-15 Assignment #2, String processing. (60 points) Due 9/23/13
You MAY NOT use C++ string objects for anything in this program.
Write a C++ program that reads lines of text from a file using the
ifstream getline() method, tokenizes the lines into words ("tokens") using
strtok(), and keeps statistics on the data in the file. Your input and
output file names will be supplied to your program on the command line,
which you will access using argc and argv[].
You need to count the total number of words, the number of unique words,
the count of each individual word, and the number of lines. Also, remember
and print the longest and shortest words in the file. If there is a tie
for longest or shortest word, you may resolve the tie in any consistent
manner (e.g., use either the first one or the last one found, but use the
same method for both longest and shortest). You may assume the lines
comprise words (contiguous lower-case letters [a-z]) separated by spaces,
terminated with a period. You may ignore the possibility of other
punctuation marks, including possessives or contractions, like in "Jim's
house". Lines before the last one in the file will have a newline ('\n')
after the period. In your data files, omit the '\n' on the last line. You
may assume that the lines will be no longer than 100 characters, the
individual words will be no longer than 15 letters and there will be no
more than 100 unique words in the file.
Read the lines from the input file, and echo-print them to the output
file. After reaching end-of-file on the input file (or reading a line of
length zero, which you should treat as the end of the input data), print
the words with their occurrence counts, one word/count pair per line, and
the collected statistics to the output file. You will also need to create
other test files of your own. Also, your program must work correctly with
an EMPTY input file – which has NO statistics.
Test file looks like this (exactly 4 lines, with NO NEWLINE on the last
line):
the quick brown fox jumps over the lazy dog.
now is the time for all good men to come to the aid of their party.
all i want for christmas is my two front teeth.
the quick brown fox jumps over a lazy dog.
Copy and paste this into a small file for one of your tests.
Hints:
Use a 2-dimensional array of char, 100 rows by 16 columns (why not 15?),
to hold the unique words, and a 1-dimensional array of ints with 100
elements to hold the associated counts. For each word, scan through the
occupied lines in the array for a match (use strcmp()), and if you find a
match, increment the associated count, otherwise (you got past the last
word), add the word to the table and set its count to 1.
The separate longest word and the shortest word need to be saved off in
their own C-strings. (Why can't you just keep a pointer to them in the
tokenized data?)
Remember – put NO NEWLINE at the end of the last line, or your test for
end-of-file might not work correctly. (This may cause the program to read
a zero-length line before seeing end-of-file.)
This is not a long program – no more than about 2 pages of code
Here is what I have so far:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<cstring>
using namespace std;
void totalwordCount(ifstream &inputFile)
{
char words[100][16]; // Holds the unique words.
char *token;
int totalCount = 0; // Counts the total number of words.
// Read every word in the file.
while(inputFile >> words[99])
{
totalCount++; // Increment the total number of words.
// Tokenize each word and remove spaces, periods, and newlines.
token = strtok(words[99], " .\n");
while(token != NULL)
{
token = strtok(NULL, " .\n");
}
}
cout << "Total number of words in file: " << totalCount << endl;
}
void uniquewordCount(ifstream &inputFile)
{
char words[100][16]; // Holds the unique words
int counter[100];
char *tok = "0";
int uniqueCount = 0; // Counts the total number of unique words
while(!inputFile.eof())
{
uniqueCount++;
tok = strtok(words[99], " .\n");
while(tok != NULL)
{
tok = strtok(NULL, " .\n");
inputFile >> words[99];
if(strcmp(tok, words[99]) == 0)
{
counter[99]++;
}
else
{
words[99][15] += 1;
}
uniqueCount++;
}
}
cout << counter[99] << endl;
}
int main(int argc, char *argv[])
{
ifstream inputFile;
char inFile[12] = "string1.txt";
char outFile[16] = "word result.txt";
// Get the name of the file from the user.
cout << "Enter the name of the file: ";
cin >> inFile;
// Open the input file.
inputFile.open(inFile);
// If successfully opened, process the data.
if(inputFile)
{
while(!inputFile.eof())
{
totalwordCount(inputFile);
uniquewordCount(inputFile);
}
}
return 0;
}
I already took care of how to count the total number of words in the file
in the totalwordCount() function, but in the uniquewordCount() function, I
am having trouble counting the total number of unique words and counting
the number of occurrences of each word. Is there anything that I need to
change in the uniquewordCount() function?
What is required to build up a basic sqlite database server on my laptop
What is required to build up a basic sqlite database server on my laptop
Thank you for the time reading this.
I am planning on creating an Android app that is communicating with my own
SQLite database server\webpage that is located on my private laptop. I
have no previous knowledge/experience with PHP nor hosting a webpage in
this case. My question is what is required to make the most basic online
database server so I could easily and very basically request and fetch
SQLite queries within the Android app from the database that is on my
laptop. Are there any programs I have to own? Also my first intentions is
for it to work on my local network(My Wifi at home), and then make it
global.
Any help is appreciated, Thanks.
Thank you for the time reading this.
I am planning on creating an Android app that is communicating with my own
SQLite database server\webpage that is located on my private laptop. I
have no previous knowledge/experience with PHP nor hosting a webpage in
this case. My question is what is required to make the most basic online
database server so I could easily and very basically request and fetch
SQLite queries within the Android app from the database that is on my
laptop. Are there any programs I have to own? Also my first intentions is
for it to work on my local network(My Wifi at home), and then make it
global.
Any help is appreciated, Thanks.
Soundcloud api - tracks info - replace file
Soundcloud api - tracks info - replace file
A simple question about the soundcloud API, but I can't fnd this info, and
can't make the test by myself since I don't have a pro account: If a user
update (replace) a file, how could I know it? Is the id replaced? Or the
date changed? Thanks
A simple question about the soundcloud API, but I can't fnd this info, and
can't make the test by myself since I don't have a pro account: If a user
update (replace) a file, how could I know it? Is the id replaced? Or the
date changed? Thanks
basic_string of unsigned char Value Type
basic_string of unsigned char Value Type
So, string comes with the value type of char. I want a string of value
type unsigned char. Why i want such a thing is because i am currently
writing a program which converts large input of hexadecimal to decimal,
and i am using strings to calculate the result. But the range of char,
which is -128 to 127 is too small, unsigned char with range 0 to 255 would
work perfectly instead. Consider this code:
#include<iostream>
using namespace std;
int main()
{
typedef basic_string<unsigned char> u_string;
u_string x= "Hello!";
return 0;
}
But when i try to compile, it shows 2 errors, one is _invalid conversion
from const char* to unsigned const char*_ and the other is initializing
argument 1 of std::basic_string<_CharT, _Traits,
_Alloc>::basic_string...(it goes on)
EDIT: "Why does the problem "converts large input of hexadecimal to
decimal" require initializing a u_string with a string literal?" While
calculating, each time i shift to the left of the hexadecimal number, i
multiply by 16. At most the result is going to be 16x9=144, which
surpasses the limit of 127, and it makes it negative value.
So, what should i do?
So, string comes with the value type of char. I want a string of value
type unsigned char. Why i want such a thing is because i am currently
writing a program which converts large input of hexadecimal to decimal,
and i am using strings to calculate the result. But the range of char,
which is -128 to 127 is too small, unsigned char with range 0 to 255 would
work perfectly instead. Consider this code:
#include<iostream>
using namespace std;
int main()
{
typedef basic_string<unsigned char> u_string;
u_string x= "Hello!";
return 0;
}
But when i try to compile, it shows 2 errors, one is _invalid conversion
from const char* to unsigned const char*_ and the other is initializing
argument 1 of std::basic_string<_CharT, _Traits,
_Alloc>::basic_string...(it goes on)
EDIT: "Why does the problem "converts large input of hexadecimal to
decimal" require initializing a u_string with a string literal?" While
calculating, each time i shift to the left of the hexadecimal number, i
multiply by 16. At most the result is going to be 16x9=144, which
surpasses the limit of 127, and it makes it negative value.
So, what should i do?
Reading WebGLRenderTarget pixel data in Three.js
Reading WebGLRenderTarget pixel data in Three.js
I have created a sculptable terrain with height displacements using GLSL
shaders in Three.js. It's done via two THREE.WebGLRenderTargets to
accumulate the sculpted heights in a fragment shader. The vertices of the
mesh are then displaced with this texture via vertex texture fetching in a
vertex shader.
However, I need the updated terrain to be a collision for a CPU-based
rigid body system. How do I get the updated height data from a
THREE.WebGLRenderTarget?
I have created a sculptable terrain with height displacements using GLSL
shaders in Three.js. It's done via two THREE.WebGLRenderTargets to
accumulate the sculpted heights in a fragment shader. The vertices of the
mesh are then displaced with this texture via vertex texture fetching in a
vertex shader.
However, I need the updated terrain to be a collision for a CPU-based
rigid body system. How do I get the updated height data from a
THREE.WebGLRenderTarget?
Saturday, 14 September 2013
Use java to perform binary shifts
Use java to perform binary shifts
I have to take a binary data in java and perform shifts on it. For e.g.
11110000 when I right shift it by 2 , i.e. 11110000>>00111100
The problem is that, I don't know how to store such a data in Java, as the
byte type converts it to decimal format. I need to use the bit at position
6 and XOR it with some other value.
I just need to know how I can achieve the ability to store binary data and
perform the required shifts.
I have to take a binary data in java and perform shifts on it. For e.g.
11110000 when I right shift it by 2 , i.e. 11110000>>00111100
The problem is that, I don't know how to store such a data in Java, as the
byte type converts it to decimal format. I need to use the bit at position
6 and XOR it with some other value.
I just need to know how I can achieve the ability to store binary data and
perform the required shifts.
what is wrong with my method for avg?
what is wrong with my method for avg?
Yes, I know there are a lot of methods here. It's part of the assignment.
In this code everything works as intended except that when numbers are
entered that equal sum<=100, the "average" output is wrong. For example:
if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average
9.25.... the average should be 12.3333. Now, if i enter in 8, 10, 99 the
output is count 3 sum 117 and average 39 which is correct. Why is it
working for sum>100 but not sum<=100??? I don't get it. What am I missing?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter
variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the
sentinel value
* of 0 that the user had to enter to exit the input loop in the
overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ",
Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) +
", Sum = " + sum + ", Average = " + average);
}
}
}
Yes, I know there are a lot of methods here. It's part of the assignment.
In this code everything works as intended except that when numbers are
entered that equal sum<=100, the "average" output is wrong. For example:
if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average
9.25.... the average should be 12.3333. Now, if i enter in 8, 10, 99 the
output is count 3 sum 117 and average 39 which is correct. Why is it
working for sum>100 but not sum<=100??? I don't get it. What am I missing?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter
variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the
sentinel value
* of 0 that the user had to enter to exit the input loop in the
overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ",
Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) +
", Sum = " + sum + ", Average = " + average);
}
}
}
mac upgrading native php with homebrew, not getting it to work
mac upgrading native php with homebrew, not getting it to work
I tried to update the native php of my mba from 5.3.X to 5.4.X I did this:
brew tap homebrew/dupes brew tap josegonzalez/homebrew-php brew update
brew install php54
This installs php 5.4 on /usr/local/cellar/php54 now when doing which php,
it gives me /usr/bin/php
I tried to add this to ~/.bashrc : export PATH=/usr/local/cellar/php54:$PATH
Now when i re-open terminal and type which php it still tells me php is
located in /usr/bin/php
Is there a good way to fix this issue?
I tried to update the native php of my mba from 5.3.X to 5.4.X I did this:
brew tap homebrew/dupes brew tap josegonzalez/homebrew-php brew update
brew install php54
This installs php 5.4 on /usr/local/cellar/php54 now when doing which php,
it gives me /usr/bin/php
I tried to add this to ~/.bashrc : export PATH=/usr/local/cellar/php54:$PATH
Now when i re-open terminal and type which php it still tells me php is
located in /usr/bin/php
Is there a good way to fix this issue?
line break is not counted in character count
line break is not counted in character count
I have a following code that counts the number of characters in a file
using awk.
but it doesn't count the line breaks as it is counted in $ wc file
file:abc
12345
12345
12345
12345
12345
awk command:
$ awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)c++}END{print "total chars:"c}' abc
This gives me o/p as
Total char:25
but if i run same abc file as wc abc it gives me o/p as 30 characters
I have a following code that counts the number of characters in a file
using awk.
but it doesn't count the line breaks as it is counted in $ wc file
file:abc
12345
12345
12345
12345
12345
awk command:
$ awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)c++}END{print "total chars:"c}' abc
This gives me o/p as
Total char:25
but if i run same abc file as wc abc it gives me o/p as 30 characters
setting Min-Height based on percent
setting Min-Height based on percent
is there a way to set min-height based on percent in css ?
i cant set the height based on percent, but when I have used both height
and min-height, I cant, I'm looking for a way to control min height
becuase my content is based on percent and the height of it changed,
I cant set the height to auto, because I need height to be 100% and min
height is also based on percent,
is there a way to set min-height based on percent in css ?
i cant set the height based on percent, but when I have used both height
and min-height, I cant, I'm looking for a way to control min height
becuase my content is based on percent and the height of it changed,
I cant set the height to auto, because I need height to be 100% and min
height is also based on percent,
Game of Life Segmentation Fault in C
Game of Life Segmentation Fault in C
Im new to C, linux etc my code compiles and runs but as soon as I enter my
first user inputs I get a segmentation fault. If someone could point out
what is wrong with my code that would be very help helpful I think it is
either in the 'calculate()' or 'main()' because I tried to allocate memory
using 'malloc()' in both of those places.
#include <stdio.h>
#include <stdlib.h>
#define LIFE_YES 'X'
#define LIFE_NO 'O'
int HEIGHT, WIDTH;
typedef int **TableType;
void printTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
if (table[height][width] == LIFE_YES) {
printf("X");
}
else {
printf("-");
}
}
printf("\n");
}
printf("\n");
}
void clearTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
table[height][width] = LIFE_NO;
}
}
}
void askUser(TableType tableA) {
int i;
int n;
int height, width;
printf("Enter the amount of initial organisms: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter dimensions (x y) where organism %d will live: ",
i + 1);
scanf("%d %d", &height, &width);
tableA[height][width] = LIFE_YES;
}
printTable(tableA);
printf("Generation 0");
}
int getNeighborValue(TableType table, int row, int col) {
if (row < 0 || row >= HEIGHT || col < 0 || col >= WIDTH ||
table[row][col] != LIFE_YES ) {
return 0;
}
else {
return 1;
}
}
int getNeighborCount(TableType table, int row, int col) {
int neighbor = 0;
neighbor += getNeighborValue(table, row - 1, col - 1);
neighbor += getNeighborValue(table, row - 1, col);
neighbor += getNeighborValue(table, row - 1, col + 1);
neighbor += getNeighborValue(table, row, col - 1);
neighbor += getNeighborValue(table, row, col + 1);
neighbor += getNeighborValue(table, row + 1, col - 1);
neighbor += getNeighborValue(table, row + 1, col);
neighbor += getNeighborValue(table, row + 1, col + 1);
return neighbor;
}
void calculate(TableType tableA) {
TableType tableB;
int neighbor, height, width, i;
tableB= malloc(HEIGHT * sizeof(int*));
for (i = 0; i < HEIGHT; i++) {
tableB[i] = malloc(WIDTH * sizeof(int));
}
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
neighbor = getNeighborCount(tableA, height, width);
if (neighbor==3) {
tableB[height][width] = LIFE_YES;
}
else if (neighbor == 2 && tableA[height][width] == LIFE_YES) {
tableB[height][width] = LIFE_YES;
}
else {
tableB[height][width] = LIFE_NO;
}
}
}
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
tableA[height][width] = tableB[height][width];
}
}
free(tableB);
}
/* test data
void loadTestData(TableType table) {
table[3][4] = LIFE_YES;
table[3][5] = LIFE_YES;
table[3][6] = LIFE_YES;
table[10][4] = LIFE_YES;
table[10][5] = LIFE_YES;
table[10][6] = LIFE_YES;
table[11][6] = LIFE_YES;
table[12][5] = LIFE_YES;
}
*/
int main(void) {
int i;
char end;
int generation = 0;
printf("Enter the amount of rows and columns you want in the grid: ");
scanf("%i %i\n", &HEIGHT, &WIDTH);
TableType table = malloc(HEIGHT * sizeof(int*));
for (i = 0; i < HEIGHT; i++) {
table[i] = malloc(WIDTH * sizeof(int));
}
clearTable(table);
askUser(table);
/*loadTestData(table);*/
printTable(table);
while (end != 'q') {
calculate(table);
printTable(table);
printf("Generation %d\n", ++generation);
printf("Press q to quit or 1 to continue: ");
scanf(" %c", &end);
}
return 0;
}
Im new to C, linux etc my code compiles and runs but as soon as I enter my
first user inputs I get a segmentation fault. If someone could point out
what is wrong with my code that would be very help helpful I think it is
either in the 'calculate()' or 'main()' because I tried to allocate memory
using 'malloc()' in both of those places.
#include <stdio.h>
#include <stdlib.h>
#define LIFE_YES 'X'
#define LIFE_NO 'O'
int HEIGHT, WIDTH;
typedef int **TableType;
void printTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
if (table[height][width] == LIFE_YES) {
printf("X");
}
else {
printf("-");
}
}
printf("\n");
}
printf("\n");
}
void clearTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
table[height][width] = LIFE_NO;
}
}
}
void askUser(TableType tableA) {
int i;
int n;
int height, width;
printf("Enter the amount of initial organisms: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter dimensions (x y) where organism %d will live: ",
i + 1);
scanf("%d %d", &height, &width);
tableA[height][width] = LIFE_YES;
}
printTable(tableA);
printf("Generation 0");
}
int getNeighborValue(TableType table, int row, int col) {
if (row < 0 || row >= HEIGHT || col < 0 || col >= WIDTH ||
table[row][col] != LIFE_YES ) {
return 0;
}
else {
return 1;
}
}
int getNeighborCount(TableType table, int row, int col) {
int neighbor = 0;
neighbor += getNeighborValue(table, row - 1, col - 1);
neighbor += getNeighborValue(table, row - 1, col);
neighbor += getNeighborValue(table, row - 1, col + 1);
neighbor += getNeighborValue(table, row, col - 1);
neighbor += getNeighborValue(table, row, col + 1);
neighbor += getNeighborValue(table, row + 1, col - 1);
neighbor += getNeighborValue(table, row + 1, col);
neighbor += getNeighborValue(table, row + 1, col + 1);
return neighbor;
}
void calculate(TableType tableA) {
TableType tableB;
int neighbor, height, width, i;
tableB= malloc(HEIGHT * sizeof(int*));
for (i = 0; i < HEIGHT; i++) {
tableB[i] = malloc(WIDTH * sizeof(int));
}
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
neighbor = getNeighborCount(tableA, height, width);
if (neighbor==3) {
tableB[height][width] = LIFE_YES;
}
else if (neighbor == 2 && tableA[height][width] == LIFE_YES) {
tableB[height][width] = LIFE_YES;
}
else {
tableB[height][width] = LIFE_NO;
}
}
}
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
tableA[height][width] = tableB[height][width];
}
}
free(tableB);
}
/* test data
void loadTestData(TableType table) {
table[3][4] = LIFE_YES;
table[3][5] = LIFE_YES;
table[3][6] = LIFE_YES;
table[10][4] = LIFE_YES;
table[10][5] = LIFE_YES;
table[10][6] = LIFE_YES;
table[11][6] = LIFE_YES;
table[12][5] = LIFE_YES;
}
*/
int main(void) {
int i;
char end;
int generation = 0;
printf("Enter the amount of rows and columns you want in the grid: ");
scanf("%i %i\n", &HEIGHT, &WIDTH);
TableType table = malloc(HEIGHT * sizeof(int*));
for (i = 0; i < HEIGHT; i++) {
table[i] = malloc(WIDTH * sizeof(int));
}
clearTable(table);
askUser(table);
/*loadTestData(table);*/
printTable(table);
while (end != 'q') {
calculate(table);
printTable(table);
printf("Generation %d\n", ++generation);
printf("Press q to quit or 1 to continue: ");
scanf(" %c", &end);
}
return 0;
}
python & gtk3 - cairo_context.rectangle method is missing
python & gtk3 - cairo_context.rectangle method is missing
My code looks like
from gi.repository import PangoCairo
from gi.repository import Gtk
class Column(Gtk.DrawingArea):
getContext = lambda self:
PangoCairo.create_context(self.get_window().cairo_create())
...
cr = self.getContext()
cr.draw_rectangle(0, 0, w, h)
And I get this error:
AttributeError: 'Context' object has no attribute 'draw_rectangle'
The method was called rectangle in PyGTK (both cairo.Context and
pango.Context)
But I searched in gtk3 C documentations and it seems It should be
draw_rectangle
And none of them exist in Python
My code looks like
from gi.repository import PangoCairo
from gi.repository import Gtk
class Column(Gtk.DrawingArea):
getContext = lambda self:
PangoCairo.create_context(self.get_window().cairo_create())
...
cr = self.getContext()
cr.draw_rectangle(0, 0, w, h)
And I get this error:
AttributeError: 'Context' object has no attribute 'draw_rectangle'
The method was called rectangle in PyGTK (both cairo.Context and
pango.Context)
But I searched in gtk3 C documentations and it seems It should be
draw_rectangle
And none of them exist in Python
Friday, 13 September 2013
how can i pass input parameter with single quote in Stored Procedure
how can i pass input parameter with single quote in Stored Procedure
i have a stored procedure with one input parameter, i'm passing the below
string but it's not working??
String :-
'girl', 'playing'
i have a stored procedure with one input parameter, i'm passing the below
string but it's not working??
String :-
'girl', 'playing'
round off digits in apache poi ss workbook
round off digits in apache poi ss workbook
I am trying to round off the decimal number with precisaion value 2, but
it is not working, let me know the problem in my below code:
CellStyle cs = wb.createCellStyle();
DataFormat df = wb.createDataFormat();
cs.setDataFormat(df.getFormat("0.0"));
for (int i=14;i<rows;i++)
{
Cell y= wb.getSheetAt(0).getRow(i).getCell((short)
colValue);
if (y.getCellType() == Cell.CELL_TYPE_STRING) {
} else if (y.getCellType() == Cell.CELL_TYPE_NUMERIC) {
float d=(float) y.getNumericCellValue();
y.setCellStyle(cs);
}
}
I am trying to round off the decimal number with precisaion value 2, but
it is not working, let me know the problem in my below code:
CellStyle cs = wb.createCellStyle();
DataFormat df = wb.createDataFormat();
cs.setDataFormat(df.getFormat("0.0"));
for (int i=14;i<rows;i++)
{
Cell y= wb.getSheetAt(0).getRow(i).getCell((short)
colValue);
if (y.getCellType() == Cell.CELL_TYPE_STRING) {
} else if (y.getCellType() == Cell.CELL_TYPE_NUMERIC) {
float d=(float) y.getNumericCellValue();
y.setCellStyle(cs);
}
}
Jquery Mobile swipe events in Android 4.2.2 not working
Jquery Mobile swipe events in Android 4.2.2 not working
I have written a mobile web application that uses the JQuery mobile
swipeleft and swiperight events but these are not working on a Samsung
Galaxy S4 running Android 4.2.2. Running the web application in either the
standard web browser or in Chrome has the same issue: the swipe events are
not detected.
The following is how I am trying to detect the events which works fine in
other devices I have tested it on, even Android devices (but not Android
4.2.2):
$('#showImage').on("swipeleft", function (event) {
if (currentScale != initialScale) return;
if (currentPage < maxPage) {
++currentPage;
img.src = document.getElementById("page" + zeroPad(currentPage, 2) +
"url").value;
}
});
$('#showImage').on("swiperight", function (event) {
if (currentScale != initialScale) return;
if (currentPage > 1) {
--currentPage;
img.src = document.getElementById("page" + zeroPad(currentPage, 2) +
"url").value;
}
});
Is there anything I can do, code-wise, to capture these events in Android
4.2.2?
I have written a mobile web application that uses the JQuery mobile
swipeleft and swiperight events but these are not working on a Samsung
Galaxy S4 running Android 4.2.2. Running the web application in either the
standard web browser or in Chrome has the same issue: the swipe events are
not detected.
The following is how I am trying to detect the events which works fine in
other devices I have tested it on, even Android devices (but not Android
4.2.2):
$('#showImage').on("swipeleft", function (event) {
if (currentScale != initialScale) return;
if (currentPage < maxPage) {
++currentPage;
img.src = document.getElementById("page" + zeroPad(currentPage, 2) +
"url").value;
}
});
$('#showImage').on("swiperight", function (event) {
if (currentScale != initialScale) return;
if (currentPage > 1) {
--currentPage;
img.src = document.getElementById("page" + zeroPad(currentPage, 2) +
"url").value;
}
});
Is there anything I can do, code-wise, to capture these events in Android
4.2.2?
how do I handle arguments in main?
how do I handle arguments in main?
#include <stdio.h>
int main(int n){
int n;
printf("%d/n",n);
return 0;
}
I wounder how argument in main works and ask for suggestions on what I do
wrong with this code.
#include <stdio.h>
int main(int n){
int n;
printf("%d/n",n);
return 0;
}
I wounder how argument in main works and ask for suggestions on what I do
wrong with this code.
android can we programatically enable/disable usb debugging?
android can we programatically enable/disable usb debugging?
Is there any why to on usb debugging on/off with code?i have searched the
same but do not find
the valid answer.
Is there any why to on usb debugging on/off with code?i have searched the
same but do not find
the valid answer.
Thursday, 12 September 2013
Encryption failed in Sipdroid Voip calls in android
Encryption failed in Sipdroid Voip calls in android
As I working on an app where I need to integrate VOIP calls in it.
After going through internet I found Sipdroid source code for free VoIP
calls & it is open source code too. As I integrated the following code it
is working good. But I want to encrypt and decrypt the data conversation
before sending and after receiving respectively. As I am not getting any
idea of integrating encryption and decryption in Sipdroid code, can anyone
help me with this. As I am struggling a lot with the following issue any
small help will me appreciated.
As I working on an app where I need to integrate VOIP calls in it.
After going through internet I found Sipdroid source code for free VoIP
calls & it is open source code too. As I integrated the following code it
is working good. But I want to encrypt and decrypt the data conversation
before sending and after receiving respectively. As I am not getting any
idea of integrating encryption and decryption in Sipdroid code, can anyone
help me with this. As I am struggling a lot with the following issue any
small help will me appreciated.
Sed Regex for remove deprecated functions
Sed Regex for remove deprecated functions
I want to remove many deprecated functions in my hundreds php codes.
The pattern of this function usage are :
$foo->someFoo($someObject->deprecatedFunctions($v['data_index']));
What i want to do is format those line to :
$foo->someFoo($v['data_index']);
How to solve this problem with sed.
Thank you in advance !
I want to remove many deprecated functions in my hundreds php codes.
The pattern of this function usage are :
$foo->someFoo($someObject->deprecatedFunctions($v['data_index']));
What i want to do is format those line to :
$foo->someFoo($v['data_index']);
How to solve this problem with sed.
Thank you in advance !
Rails 3, adding joins to default_scope for association of current_user
Rails 3, adding joins to default_scope for association of current_user
In my app i have a schema of Users and Tickets, each User can be
subscribed to many Tickets and viceversa.
For each ticket i fetch from the database, i want to display if
current_user is subscribed or not to the ticket itself.
An example of my query is as follows:
@tickets = current_user.tickets.limit(10).order('created_at DESC')
Can i do it using a default_scope with a join in Ticket model?, i need it
to return an additional field with a simple true or false, or nil.
Thank you.
In my app i have a schema of Users and Tickets, each User can be
subscribed to many Tickets and viceversa.
For each ticket i fetch from the database, i want to display if
current_user is subscribed or not to the ticket itself.
An example of my query is as follows:
@tickets = current_user.tickets.limit(10).order('created_at DESC')
Can i do it using a default_scope with a join in Ticket model?, i need it
to return an additional field with a simple true or false, or nil.
Thank you.
Spnego keytab test gives a java security exception
Spnego keytab test gives a java security exception
I cannot get the following program running:
import java.net.URL;
import net.sourceforge.spnego.SpnegoHttpURLConnection;
public class HelloKeytab {
public static void main(final String[] args) throws Exception {
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.auth.login.config", "login.conf");
SpnegoHttpURLConnection spnego = null;
try {
spnego = new SpnegoHttpURLConnection("spnego-client");
spnego.connect(new
URL("http://as1.test.local/hello_spnego.jsp"));
System.out.println("HTTP Status Code: "
+ spnego.getResponseCode());
System.out.println("HTTP Status Message: "
+ spnego.getResponseMessage());
} finally {
if (null != spnego) {
spnego.disconnect();
}
}
}
}
I installed JDK7 and set the JAVA_HOME environment variable as an
Administrator. I am working on a Windows XP machine as a regular domain
user while compiling and running.
I have the spnego-r7.jar in the same directory as the HelloKeytab.java and
I compiled with:
javac -cp .;spnego-r7.jar HelloKeytab.java
which succesfully creates the class.
When I run the program with:
java -cp .;spengo-r7.jar HelloKeytab
I get the following error:
Exception in thread "main" java.lang.SecurityException: Configuration Error:
Line 2: expected [controlFlag]
at com.sun.security.auth.login.ConfigFile.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
Source)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
Sou
rce)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javax.security.auth.login.Configuration$3.run(Unknown Source)
at javax.security.auth.login.Configuration$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at
javax.security.auth.login.Configuration.getConfiguration(Unknown
Sour
ce)
at javax.security.auth.login.LoginContext$1.run(Unknown Source)
at javax.security.auth.login.LoginContext$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.init(Unknown Source)
at javax.security.auth.login.LoginContext.<init>(Unknown Source)
at
net.sourceforge.spnego.SpnegoHttpURLConnection.<init>(SpnegoHttpURLCo
nnection.java:206)
at HelloKeytab.main(HelloKeytab.java:15)
Caused by: java.io.IOException: Configuration Error:
Line 2: expected [controlFlag]
at com.sun.security.auth.login.ConfigFile.match(Unknown Source)
at com.sun.security.auth.login.ConfigFile.parseLoginEntry(Unknown
Source
)
at com.sun.security.auth.login.ConfigFile.readConfig(Unknown Source)
at com.sun.security.auth.login.ConfigFile.init(Unknown Source)
at com.sun.security.auth.login.ConfigFile.init(Unknown Source)
... 17 more
The spnego-r7.jar can be found here:
http://sourceforge.net/projects/spnego/files/
What is wrong that I am getting this error?
I cannot get the following program running:
import java.net.URL;
import net.sourceforge.spnego.SpnegoHttpURLConnection;
public class HelloKeytab {
public static void main(final String[] args) throws Exception {
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.auth.login.config", "login.conf");
SpnegoHttpURLConnection spnego = null;
try {
spnego = new SpnegoHttpURLConnection("spnego-client");
spnego.connect(new
URL("http://as1.test.local/hello_spnego.jsp"));
System.out.println("HTTP Status Code: "
+ spnego.getResponseCode());
System.out.println("HTTP Status Message: "
+ spnego.getResponseMessage());
} finally {
if (null != spnego) {
spnego.disconnect();
}
}
}
}
I installed JDK7 and set the JAVA_HOME environment variable as an
Administrator. I am working on a Windows XP machine as a regular domain
user while compiling and running.
I have the spnego-r7.jar in the same directory as the HelloKeytab.java and
I compiled with:
javac -cp .;spnego-r7.jar HelloKeytab.java
which succesfully creates the class.
When I run the program with:
java -cp .;spengo-r7.jar HelloKeytab
I get the following error:
Exception in thread "main" java.lang.SecurityException: Configuration Error:
Line 2: expected [controlFlag]
at com.sun.security.auth.login.ConfigFile.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
Source)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
Sou
rce)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javax.security.auth.login.Configuration$3.run(Unknown Source)
at javax.security.auth.login.Configuration$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at
javax.security.auth.login.Configuration.getConfiguration(Unknown
Sour
ce)
at javax.security.auth.login.LoginContext$1.run(Unknown Source)
at javax.security.auth.login.LoginContext$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.init(Unknown Source)
at javax.security.auth.login.LoginContext.<init>(Unknown Source)
at
net.sourceforge.spnego.SpnegoHttpURLConnection.<init>(SpnegoHttpURLCo
nnection.java:206)
at HelloKeytab.main(HelloKeytab.java:15)
Caused by: java.io.IOException: Configuration Error:
Line 2: expected [controlFlag]
at com.sun.security.auth.login.ConfigFile.match(Unknown Source)
at com.sun.security.auth.login.ConfigFile.parseLoginEntry(Unknown
Source
)
at com.sun.security.auth.login.ConfigFile.readConfig(Unknown Source)
at com.sun.security.auth.login.ConfigFile.init(Unknown Source)
at com.sun.security.auth.login.ConfigFile.init(Unknown Source)
... 17 more
The spnego-r7.jar can be found here:
http://sourceforge.net/projects/spnego/files/
What is wrong that I am getting this error?
ASP CODE and ms Access catastrophe
ASP CODE and ms Access catastrophe
I have problem with this code i got error as ADODB.Field error '80020009'
Either BOF or EOF is True, or the current record has been deleted.
Requested operation requires a current record.
/pinner/actionpinn.asp, line 0
code is as follows please help how to resolve this problem i have tried a
lot search in google check my query db everything i have not found any
error
`<html>
<body>
<div id ="pin">
<%
city= Request.Form("username")
area = Request.Form("password")
Dim Conn,rs,strSQL
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open"Provider= Microsoft.Jet.OLEDB.4.0;Data Source=" &
Server.MapPath("/pinner/db/database1.mdb")
'Conn.Open"DRIVER=Microsoft Access Driver(*.mdb);DBQ=" &
Server.MapPath("/pinner/db/Database1.mdb")
'strSQL = "SELECT pincodes.officename FROM pincodes where pincode = '"
& city & "';"
Set rs = Server.CreateObject("ADODB.Recordset")
strSQL = "Select pincode from pincodes WHERE regionname = '" & city
& "' AND officename = '" & area &"';"
rs.Open strSQL,Conn
Response.Write ("<br>")
Response.Write (rs("pincode"))
Response.Write ("<br>")
rs.close
Set rs = Nothing
Set Conn = Nothing
%>
</div>
</body>
</html>`
`
I have problem with this code i got error as ADODB.Field error '80020009'
Either BOF or EOF is True, or the current record has been deleted.
Requested operation requires a current record.
/pinner/actionpinn.asp, line 0
code is as follows please help how to resolve this problem i have tried a
lot search in google check my query db everything i have not found any
error
`<html>
<body>
<div id ="pin">
<%
city= Request.Form("username")
area = Request.Form("password")
Dim Conn,rs,strSQL
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open"Provider= Microsoft.Jet.OLEDB.4.0;Data Source=" &
Server.MapPath("/pinner/db/database1.mdb")
'Conn.Open"DRIVER=Microsoft Access Driver(*.mdb);DBQ=" &
Server.MapPath("/pinner/db/Database1.mdb")
'strSQL = "SELECT pincodes.officename FROM pincodes where pincode = '"
& city & "';"
Set rs = Server.CreateObject("ADODB.Recordset")
strSQL = "Select pincode from pincodes WHERE regionname = '" & city
& "' AND officename = '" & area &"';"
rs.Open strSQL,Conn
Response.Write ("<br>")
Response.Write (rs("pincode"))
Response.Write ("<br>")
rs.close
Set rs = Nothing
Set Conn = Nothing
%>
</div>
</body>
</html>`
`
How do I change the position of JQuery Autocomplete from the top of the page?
How do I change the position of JQuery Autocomplete from the top of the page?
I have a JSFiddle here. Whenever I use the autocomplete, the available
options appear at the top of the page, instead of below the text box.
Other questions here hasn't helped.
What I want to do is move the available options below the text box, but I
don't know how to do it.
HTML here
<br><br><br><br><br><br><br><br><br><br><br>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
Javascript here
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
I have a JSFiddle here. Whenever I use the autocomplete, the available
options appear at the top of the page, instead of below the text box.
Other questions here hasn't helped.
What I want to do is move the available options below the text box, but I
don't know how to do it.
HTML here
<br><br><br><br><br><br><br><br><br><br><br>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
Javascript here
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
Word Macro for Acronyms and Defnition, putting results in a table
Word Macro for Acronyms and Defnition, putting results in a table
I have the following bit of code which works lovely and produces a new
document with the information formatted however i would like it in a table
so that i can simply paste it back into my document. I have looked at a
few other codes which do this but i have no experience at all in this
language and cant make sense of it (amature python programer at best)
Sub ListAcronyms()
Dim strAcronym As String
Dim strDefine As String
Dim strOutput As String
Dim newDoc As Document
Application.ScreenUpdating = False
Selection.HomeKey Unit:=wdStory
ActiveWindow.View.ShowHiddenText = False
'Loop to find all acronyms
Do
'Search for acronyms using wildcards
Selection.Find.ClearFormatting
With Selection.Find
.ClearFormatting
.Text = "<[A-Z]@[A-Z]>"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWildcards = True
.MatchWholeWord = True
.Execute
End With
'Only process if something found
If Selection.Find.Found Then
'Make a string from the selection, add it to the
'output string
strAcronym = Selection.Text
'Look for definition
Selection.MoveRight Unit:=wdWord
Selection.MoveRight Unit:=wdCharacter, _
Extend:=wdExtend
strDefine = ""
If Selection.Text = "(" Then
While Selection <> ")"
strDefine = strDefine & Selection.Text
Selection.Collapse Direction:=wdCollapseEnd
Selection.MoveRight Unit:=wdCharacter, _
Extend:=wdExtend
Wend
End If
Selection.Collapse Direction:=wdCollapseEnd
If Left(strDefine, 1) = "(" Then
strDefine = Mid(strDefine, 2, Len(strDefine))
End If
If strDefine > "" Then
'Check if the search result is in the Output string
'if it is, ignore the search result
If InStr(strOutput, strAcronym) = 0 Then
strOutput = strOutput & strAcronym _
& vbTab & strDefine & vbCr
End If
End If
End If
Loop Until Not Selection.Find.Found
'Create new document and change active document
Set newDoc = Documents.Add
'Insert the text
Selection.TypeText Text:=strOutput
'Sort it
newDoc.Content.Sort SortOrder:=wdSortOrderAscending
Application.ScreenUpdating = True
Selection.HomeKey Unit:=wdStory
End Sub
I have the following bit of code which works lovely and produces a new
document with the information formatted however i would like it in a table
so that i can simply paste it back into my document. I have looked at a
few other codes which do this but i have no experience at all in this
language and cant make sense of it (amature python programer at best)
Sub ListAcronyms()
Dim strAcronym As String
Dim strDefine As String
Dim strOutput As String
Dim newDoc As Document
Application.ScreenUpdating = False
Selection.HomeKey Unit:=wdStory
ActiveWindow.View.ShowHiddenText = False
'Loop to find all acronyms
Do
'Search for acronyms using wildcards
Selection.Find.ClearFormatting
With Selection.Find
.ClearFormatting
.Text = "<[A-Z]@[A-Z]>"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWildcards = True
.MatchWholeWord = True
.Execute
End With
'Only process if something found
If Selection.Find.Found Then
'Make a string from the selection, add it to the
'output string
strAcronym = Selection.Text
'Look for definition
Selection.MoveRight Unit:=wdWord
Selection.MoveRight Unit:=wdCharacter, _
Extend:=wdExtend
strDefine = ""
If Selection.Text = "(" Then
While Selection <> ")"
strDefine = strDefine & Selection.Text
Selection.Collapse Direction:=wdCollapseEnd
Selection.MoveRight Unit:=wdCharacter, _
Extend:=wdExtend
Wend
End If
Selection.Collapse Direction:=wdCollapseEnd
If Left(strDefine, 1) = "(" Then
strDefine = Mid(strDefine, 2, Len(strDefine))
End If
If strDefine > "" Then
'Check if the search result is in the Output string
'if it is, ignore the search result
If InStr(strOutput, strAcronym) = 0 Then
strOutput = strOutput & strAcronym _
& vbTab & strDefine & vbCr
End If
End If
End If
Loop Until Not Selection.Find.Found
'Create new document and change active document
Set newDoc = Documents.Add
'Insert the text
Selection.TypeText Text:=strOutput
'Sort it
newDoc.Content.Sort SortOrder:=wdSortOrderAscending
Application.ScreenUpdating = True
Selection.HomeKey Unit:=wdStory
End Sub
Paste the Files present in any folder into Richtextbox
Paste the Files present in any folder into Richtextbox
I am having multiple format files(.jpeg,.txt,.doc,.excel) in a folder.I
want to show those file with their icon in richtextbox in c#.
string[] files = Directory.GetFiles(pp);
foreach (string file in files)
{
StringCollection paths = new StringCollection();
paths.Add(file); // Clipboard.
// Clipboard.SetFileDropList(paths);
// lst.Items.Add(file);
rht_attachment.Focus();
Clipboard.SetFileDropList(paths);
rht_attachment.Paste();
}
I am having multiple format files(.jpeg,.txt,.doc,.excel) in a folder.I
want to show those file with their icon in richtextbox in c#.
string[] files = Directory.GetFiles(pp);
foreach (string file in files)
{
StringCollection paths = new StringCollection();
paths.Add(file); // Clipboard.
// Clipboard.SetFileDropList(paths);
// lst.Items.Add(file);
rht_attachment.Focus();
Clipboard.SetFileDropList(paths);
rht_attachment.Paste();
}
Wednesday, 11 September 2013
.NET - high memory usage by clr.dll and native heaps
.NET - high memory usage by clr.dll and native heaps
I have been performing memory leak analysis using DebugDiag for a .NET
application which has shown continuous increase in memory.
After several test dumps and then capturing dumps over a day, I see that
the module clr.dll has 5.08 MB of allocations in first dump, 286.4 MB of
allocations in second and 609.56 MB in the third.
Specifically, the rise is in allocations caused by
clr!DoNDirectCall__PatchGetThreadCall+7b which has 894.33 KB allocation in
first, 280.85 MB in second and 601.13 MB in third. Here are some of the
call stacks from the third dump -
Call stack sample 1
Address 0x00730074`00210048
Allocation Time 00:09:03 since tracking started
Allocation Size 34 Bytes
Function Source Destination
clr!DoNDirectCall__PatchGetThreadCall+7b
mscorlib_ni+b9597b
mscorlib_ni+b940ed
mscorlib_ni+b9513e
System_Management_ni+dc561
System_Management_ni+aa364
System_Management_ni+e4616
Call stack sample 2
Address 0x00730074`00210048
Allocation Time 00:05:00 since tracking started
Allocation Size 34 Bytes
Function Source Destination
clr!DoNDirectCall__PatchGetThreadCall+7b
mscorlib_ni+9bb2cc
mscorlib_ni+b934aa
System_Management_ni+dc714
System_Management_ni+acb99
System_Management_ni+e41a5
Call stack sample 3
Address 0x00730074`00210048
Allocation Time 00:05:00 since tracking started
Allocation Size 34 Bytes
Function Source Destination
clr!DoNDirectCall__PatchGetThreadCall+7b
mscorlib_ni+9bb2cc
mscorlib_ni+b934aa
System_Management_ni+dc714
System_Management_ni+acb99
System_Management_ni+e41a5
0x6448017AE50
What could be causing this and how do I find out more about this ?
Also, my code uses the avaliable C# methods to run remote WMI queries and
retrieve that data.
In addition, my Native Heaps usage also increases. There are 40 native
heaps for my application. The memory usage of the last heap always
increases. Its total usage goes from 67.57 MB to 1.59 GB to 3.82 GB. What
could be the cause of this, and is this related to clr's usage ?
I have been performing memory leak analysis using DebugDiag for a .NET
application which has shown continuous increase in memory.
After several test dumps and then capturing dumps over a day, I see that
the module clr.dll has 5.08 MB of allocations in first dump, 286.4 MB of
allocations in second and 609.56 MB in the third.
Specifically, the rise is in allocations caused by
clr!DoNDirectCall__PatchGetThreadCall+7b which has 894.33 KB allocation in
first, 280.85 MB in second and 601.13 MB in third. Here are some of the
call stacks from the third dump -
Call stack sample 1
Address 0x00730074`00210048
Allocation Time 00:09:03 since tracking started
Allocation Size 34 Bytes
Function Source Destination
clr!DoNDirectCall__PatchGetThreadCall+7b
mscorlib_ni+b9597b
mscorlib_ni+b940ed
mscorlib_ni+b9513e
System_Management_ni+dc561
System_Management_ni+aa364
System_Management_ni+e4616
Call stack sample 2
Address 0x00730074`00210048
Allocation Time 00:05:00 since tracking started
Allocation Size 34 Bytes
Function Source Destination
clr!DoNDirectCall__PatchGetThreadCall+7b
mscorlib_ni+9bb2cc
mscorlib_ni+b934aa
System_Management_ni+dc714
System_Management_ni+acb99
System_Management_ni+e41a5
Call stack sample 3
Address 0x00730074`00210048
Allocation Time 00:05:00 since tracking started
Allocation Size 34 Bytes
Function Source Destination
clr!DoNDirectCall__PatchGetThreadCall+7b
mscorlib_ni+9bb2cc
mscorlib_ni+b934aa
System_Management_ni+dc714
System_Management_ni+acb99
System_Management_ni+e41a5
0x6448017AE50
What could be causing this and how do I find out more about this ?
Also, my code uses the avaliable C# methods to run remote WMI queries and
retrieve that data.
In addition, my Native Heaps usage also increases. There are 40 native
heaps for my application. The memory usage of the last heap always
increases. Its total usage goes from 67.57 MB to 1.59 GB to 3.82 GB. What
could be the cause of this, and is this related to clr's usage ?
Updating a .jar file that is in use
Updating a .jar file that is in use
I have a C# program that updates and then launches a Java application.
Before actually launching Java, it checks for updates to the .jar files
that program uses. It's possible that multiple people are running the
application on a given machine at one time (it could be a terminal server)
or that the same user is running multiple instances of the program. If
other people are running the application, the .jar file will be in use and
can't be updated. I'm trying to work around this.
My preference would be to rename the .jar file and update it. All the
people currently running the application can still use the renamed jar
file. Windows won't let you rename a file that's in use, either (though I
think Unix systems will).
I noticed that with Windows Explorer, though, you can copy/paste a jar
file and overwrite a .jar file that's in use. How does that work, and can
I somehow do something similar in my updater/launcher program?
Are there any other approaches I might use?
I have a C# program that updates and then launches a Java application.
Before actually launching Java, it checks for updates to the .jar files
that program uses. It's possible that multiple people are running the
application on a given machine at one time (it could be a terminal server)
or that the same user is running multiple instances of the program. If
other people are running the application, the .jar file will be in use and
can't be updated. I'm trying to work around this.
My preference would be to rename the .jar file and update it. All the
people currently running the application can still use the renamed jar
file. Windows won't let you rename a file that's in use, either (though I
think Unix systems will).
I noticed that with Windows Explorer, though, you can copy/paste a jar
file and overwrite a .jar file that's in use. How does that work, and can
I somehow do something similar in my updater/launcher program?
Are there any other approaches I might use?
Find out what branches are merged into master via Github API?
Find out what branches are merged into master via Github API?
On the Github website they list what branches have been merged into
master. I would like to know how to list those branches through the Github
API.
On the Github website they list what branches have been merged into
master. I would like to know how to list those branches through the Github
API.
Why addClass not working?
Why addClass not working?
<div class="form-group">
<label class="control-label" for="test1"></label>
<input type="text" name="test1" class="form-control test1" id="test1"
placeholder="" width="200">
</div>
For add class for div <div class="form-group"> i use code:
var FindName = arr[i].name; //test1
$("input[name=FindName]").parent().removeClass("test").addClass("test2");
But code isnt working. Tell me please where error in my code?
<div class="form-group">
<label class="control-label" for="test1"></label>
<input type="text" name="test1" class="form-control test1" id="test1"
placeholder="" width="200">
</div>
For add class for div <div class="form-group"> i use code:
var FindName = arr[i].name; //test1
$("input[name=FindName]").parent().removeClass("test").addClass("test2");
But code isnt working. Tell me please where error in my code?
Youtube android player api getCurrentTimeMillis only updates every 1 second
Youtube android player api getCurrentTimeMillis only updates every 1 second
I'm using the Youtube player android api (latest version, fetched from
https://developers.google.com/youtube/android/player/). In my app I've
added a timer that calls the player's getCurrentTimeMillis method every
200 msec. The problem is that the method returns the same value for each
second that passes by. for example, I get the following output after the
running the app:
1877 1877 1877 1877 1877 2878 2878 2878 2878 2878 3879 3879 3879 3879 3879
4880 4880 4880 4880 4880 5881
As you can see, the time effectively updates every 1 second (5 timer
ticks). The same happens with a timer delay of 100 msec (every 10 ticks).
This of course, does not happen with the javascript api or the AS3 api.
Does anyone have any idea why it happens and how can I get a higher
resolution?
I tried the same app on the Nexus 7 and Galaxy Nexus (both running android
4.3) and got the same results.
Thanks in advance! Roy
I'm using the Youtube player android api (latest version, fetched from
https://developers.google.com/youtube/android/player/). In my app I've
added a timer that calls the player's getCurrentTimeMillis method every
200 msec. The problem is that the method returns the same value for each
second that passes by. for example, I get the following output after the
running the app:
1877 1877 1877 1877 1877 2878 2878 2878 2878 2878 3879 3879 3879 3879 3879
4880 4880 4880 4880 4880 5881
As you can see, the time effectively updates every 1 second (5 timer
ticks). The same happens with a timer delay of 100 msec (every 10 ticks).
This of course, does not happen with the javascript api or the AS3 api.
Does anyone have any idea why it happens and how can I get a higher
resolution?
I tried the same app on the Nexus 7 and Galaxy Nexus (both running android
4.3) and got the same results.
Thanks in advance! Roy
Excel Date Format Change
Excel Date Format Change
I receive a CSV file from an external data source with the dates formatted
as shown below. I need to "convert" whatever is coming over into a date
that can be sorted properly. I've tried text to columns, formulas,
importing as text, etc but nothing will change this data into a usable
format. Each date comes over in one cell. I've had to clean data in the
past but the techniques used in the past are not working with this set. If
anyone has any ideas I would greatly appreciate the help. Thank you.
Apr 16 2013 12:40PM Apr 19 2012 3:49PM Apr 30 2012 10:33AM Aug 14 2013
10:25AM Aug 29 2013 4:21PM Dec 28 2012 10:22AM May 13 2013 5:02PM
I receive a CSV file from an external data source with the dates formatted
as shown below. I need to "convert" whatever is coming over into a date
that can be sorted properly. I've tried text to columns, formulas,
importing as text, etc but nothing will change this data into a usable
format. Each date comes over in one cell. I've had to clean data in the
past but the techniques used in the past are not working with this set. If
anyone has any ideas I would greatly appreciate the help. Thank you.
Apr 16 2013 12:40PM Apr 19 2012 3:49PM Apr 30 2012 10:33AM Aug 14 2013
10:25AM Aug 29 2013 4:21PM Dec 28 2012 10:22AM May 13 2013 5:02PM
Remain status on checkbox, when refresh
Remain status on checkbox, when refresh
New to php, and sql. But here is the thing. I have a page that displays a
table from a database, based on certain criteria. The table is loaded
anytime I refresh the page. I am using this as a list of tasks for
service.
I'va added a column with checkboxes for service-personell to mark
everytime service has been done, ie. using this as a tasklist. But when u
refresh page, or close browser to visit the page again, the checkboxes are
listed as unchecked(of course)
I was just wondering how to maintain the status of checkboxes for a
certain time? Maybe cookies? If so I need some guidance.
My php
{foreach ($list as $key => $row)
{
echo '<tr class="xcrud-row-' . $i . '"><td class
="check_row"><div><input type="checkbox" name="status"
></div></td>';
if($this->is_numbers) echo '<td class="xcrud-num">' .
($key + $start + 1) . '</td>';}
Live example :
Here
New to php, and sql. But here is the thing. I have a page that displays a
table from a database, based on certain criteria. The table is loaded
anytime I refresh the page. I am using this as a list of tasks for
service.
I'va added a column with checkboxes for service-personell to mark
everytime service has been done, ie. using this as a tasklist. But when u
refresh page, or close browser to visit the page again, the checkboxes are
listed as unchecked(of course)
I was just wondering how to maintain the status of checkboxes for a
certain time? Maybe cookies? If so I need some guidance.
My php
{foreach ($list as $key => $row)
{
echo '<tr class="xcrud-row-' . $i . '"><td class
="check_row"><div><input type="checkbox" name="status"
></div></td>';
if($this->is_numbers) echo '<td class="xcrud-num">' .
($key + $start + 1) . '</td>';}
Live example :
Here
SQL date issue when date is not isdate
SQL date issue when date is not isdate
Expiry************ DateEnd**
None ********** 2000-06-29 00:00:00.000
None ********** 2000-06-29 00:00:00.000
september 2013 ********** 2013-06-29 00:00:00.000
January 2012 ********** 2013-06-29 00:00:00.000
May 2020 ********** 2013-06-29 00:00:00.000
2013-06-29 00:00:00.000 ********** 2013-06-29 00:00:00.000
From two column I want pick all dates except May 2020 rows, due to future
date. this is what I have so far
DECLARE @YearFlag datetime
SET @YearFlag = DATEADD(yy,-5,GETDATE())
SELECT * FROM #Table
where (DateEnd IS NULL OR DateEnd = '' OR DateEnd <= @YearFlag)
OR (CHARINDEX(Convert(varchar, YEAR(GETDATE())),Expiry) > 0)
--was using below one to pick January 2012 row but getting error
OR (Expiry != 'none' AND Expiry <= GETDATE())
Expiry************ DateEnd**
None ********** 2000-06-29 00:00:00.000
None ********** 2000-06-29 00:00:00.000
september 2013 ********** 2013-06-29 00:00:00.000
January 2012 ********** 2013-06-29 00:00:00.000
May 2020 ********** 2013-06-29 00:00:00.000
2013-06-29 00:00:00.000 ********** 2013-06-29 00:00:00.000
From two column I want pick all dates except May 2020 rows, due to future
date. this is what I have so far
DECLARE @YearFlag datetime
SET @YearFlag = DATEADD(yy,-5,GETDATE())
SELECT * FROM #Table
where (DateEnd IS NULL OR DateEnd = '' OR DateEnd <= @YearFlag)
OR (CHARINDEX(Convert(varchar, YEAR(GETDATE())),Expiry) > 0)
--was using below one to pick January 2012 row but getting error
OR (Expiry != 'none' AND Expiry <= GETDATE())
Tuesday, 10 September 2013
Java Swing project on Library management System slide issue
Java Swing project on Library management System slide issue
Just one last question. I understood making frames.But,I want to know..
How to open the other frame on clicking a button.That is suppose... On
clicking book section button...it should redirect me to all list of books.
What to do?
Just one last question. I understood making frames.But,I want to know..
How to open the other frame on clicking a button.That is suppose... On
clicking book section button...it should redirect me to all list of books.
What to do?
Try to use quatitize.js but got error message "Uncaught TypeError: Object # has no method 'palette'"
Try to use quatitize.js but got error message "Uncaught TypeError: Object
# has no method 'palette'"
I am learning to use the quantitize.js but getting the error "Uncaught
TypeError: Object # has no method 'palette'". I don't know what is wrong.
PLease help. Thanks.
Here is the code:
<div></div>
<script
src="jquery-2.0.3.min.js"></script>
<script>
/*!
* quantize.js Copyright 2008 Nick Rabinowitz.
* Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
*/
// fill out a couple protovis dependencies
/*!
* Block below copied from Protovis:
http://mbostock.github.com/protovis/
* Copyright 2010 Stanford Visualization Group
* Licensed under the BSD License:
http://www.opensource.org/licenses/bsd-license.php
*/
if (!pv) {
var pv = {
map: function (array, f) {
var o = {};
return f ? array.map(function (d, i) {
o.index = i;
return f.call(o, d);
}) : array.slice();
},
naturalOrder: function (a, b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
},
sum: function (array, f) {
var o = {};
return array.reduce(f ? function (p, d, i) {
o.index = i;
return p + f.call(o, d);
} : function (p, d) {
return p + d;
}, 0);
},
max: function (array, f) {
return Math.max.apply(null, f ? pv.map(array, f) :
array);
}
};
}
/**
* Basic Javascript port of the MMCQ (modified median cut
quantization)
* algorithm from the Leptonica library (http://www.leptonica.com/).
* Returns a color map you can use to map original pixels to the
reduced
* palette. Still a work in progress.
*
* @author Nick Rabinowitz
* @example
*/
// array of pixels as [R,G,B] arrays
var myPixels = [
[190, 197, 190],
[202, 204, 200],
[207, 214, 210],
[211, 214, 211],
[205, 207, 207]
// etc
];
var maxColors = 4;
var cmap = MMCQ.quantize(myPixels, maxColors);
var newPalette = cmap.palette();
var newPixels = myPixels.map(function (p) {
return cmap.map(p);
});
// */
var MMCQ = (function () {
// private constants
var sigbits = 5,
rshift = 8 - sigbits,
maxIterations = 1000,
fractByPopulations = 0.75;
// get reduced-space color index for a pixel
function getColorIndex(r, g, b) {
return (r << (2 * sigbits)) + (g << sigbits) + b;
}
// Simple priority queue
function PQueue(comparator) {
var contents = [],
sorted = false;
function sort() {
contents.sort(comparator);
sorted = true;
}
return {
push: function (o) {
contents.push(o);
sorted = false;
},
peek: function (index) {
if (!sorted) sort();
if (index === undefined) index = contents.length - 1;
return contents[index];
},
pop: function () {
if (!sorted) sort();
return contents.pop();
},
size: function () {
return contents.length;
},
map: function (f) {
return contents.map(f);
},
debug: function () {
if (!sorted) sort();
return contents;
}
};
}
// 3d color space box
function VBox(r1, r2, g1, g2, b1, b2, histo) {
var vbox = this;
vbox.r1 = r1;
vbox.r2 = r2;
vbox.g1 = g1;
vbox.g2 = g2;
vbox.b1 = b1;
vbox.b2 = b2;
vbox.histo = histo;
}
VBox.prototype = {
volume: function (force) {
var vbox = this;
if (!vbox._volume || force) {
vbox._volume = ((vbox.r2 - vbox.r1 + 1) * (vbox.g2
- vbox.g1 + 1) * (vbox.b2 - vbox.b1 + 1));
}
return vbox._volume;
},
count: function (force) {
var vbox = this,
histo = vbox.histo;
if (!vbox._count_set || force) {
var npix = 0,
i, j, k;
for (i = vbox.r1; i <= vbox.r2; i++) {
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(i, j, k);
npix += (histo[index] || 0);
}
}
}
vbox._count = npix;
vbox._count_set = true;
}
return vbox._count;
},
copy: function () {
var vbox = this;
return new VBox(vbox.r1, vbox.r2, vbox.g1, vbox.g2,
vbox.b1, vbox.b2, vbox.histo);
},
avg: function (force) {
var vbox = this,
histo = vbox.histo;
if (!vbox._avg || force) {
var ntot = 0,
mult = 1 << (8 - sigbits),
rsum = 0,
gsum = 0,
bsum = 0,
hval,
i, j, k, histoindex;
for (i = vbox.r1; i <= vbox.r2; i++) {
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
histoindex = getColorIndex(i, j, k);
hval = histo[histoindex] || 0;
ntot += hval;
rsum += (hval * (i + 0.5) * mult);
gsum += (hval * (j + 0.5) * mult);
bsum += (hval * (k + 0.5) * mult);
}
}
}
if (ntot) {
vbox._avg = [~~(rsum / ntot), ~~ (gsum /
ntot), ~~ (bsum / ntot)];
} else {
// console.log('empty box');
vbox._avg = [~~(mult * (vbox.r1 + vbox.r2 + 1)
/ 2), ~~ (mult * (vbox.g1 + vbox.g2 + 1) / 2),
~~ (mult * (vbox.b1 + vbox.b2 + 1) / 2)];
}
}
return vbox._avg;
},
contains: function (pixel) {
var vbox = this,
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
return (rval >= vbox.r1 && rval <= vbox.r2 &&
gval >= vbox.g1 && rval <= vbox.g2 &&
bval >= vbox.b1 && rval <= vbox.b2);
}
};
// Color map
function CMap() {
this.vboxes = new PQueue(function (a, b) {
return pv.naturalOrder(
a.vbox.count() * a.vbox.volume(),
b.vbox.count() * b.vbox.volume()
)
});;
}
CMap.prototype = {
push: function (vbox) {
this.vboxes.push({
vbox: vbox,
color: vbox.avg()
});
},
palette: function () {
return this.vboxes.map(function (vb) {
return vb.color
});
},
size: function () {
return this.vboxes.size();
},
map: function (color) {
var vboxes = this.vboxes;
for (var i = 0; i < vboxes.size(); i++) {
if (vboxes.peek(i).vbox.contains(color)) {
return vboxes.peek(i).color;
}
}
return this.nearest(color);
},
nearest: function (color) {
var vboxes = this.vboxes,
d1, d2, pColor;
for (var i = 0; i < vboxes.size(); i++) {
d2 = Math.sqrt(
Math.pow(color[0] - vboxes.peek(i).color[0], 2) +
Math.pow(color[1] - vboxes.peek(i).color[1], 2) +
Math.pow(color[1] - vboxes.peek(i).color[1], 2)
);
if (d2 < d1 || d1 === undefined) {
d1 = d2;
pColor = vboxes.peek(i).color;
}
}
return pColor;
},
forcebw: function () {
// XXX: won't work yet
var vboxes = this.vboxes;
vboxes.sort(function (a, b) {
return pv.naturalOrder(pv.sum(a.color),
pv.sum(b.color))
});
// force darkest color to black if everything < 5
var lowest = vboxes[0].color;
if (lowest[0] < 5 && lowest[1] < 5 && lowest[2] < 5)
vboxes[0].color = [0, 0, 0];
// force lightest color to white if everything > 251
var idx = vboxes.length - 1,
highest = vboxes[idx].color;
if (highest[0] > 251 && highest[1] > 251 && highest[2]
> 251)
vboxes[idx].color = [255, 255, 255];
}
};
// histo (1-d array, giving the number of pixels in
// each quantized region of color space), or null on error
function getHisto(pixels) {
var histosize = 1 << (3 * sigbits),
histo = new Array(histosize),
index, rval, gval, bval;
pixels.forEach(function (pixel) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
index = getColorIndex(rval, gval, bval);
histo[index] = (histo[index] || 0) + 1;
});
return histo;
}
function vboxFromPixels(pixels, histo) {
var rmin = 1000000,
rmax = 0,
gmin = 1000000,
gmax = 0,
bmin = 1000000,
bmax = 0,
rval, gval, bval;
// find min/max
pixels.forEach(function (pixel) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
if (rval < rmin) rmin = rval;
else if (rval > rmax) rmax = rval;
if (gval < gmin) gmin = gval;
else if (gval > gmax) gmax = gval;
if (bval < bmin) bmin = bval;
else if (bval > bmax) bmax = bval;
});
return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);
}
function medianCutApply(histo, vbox) {
if (!vbox.count()) return;
var rw = vbox.r2 - vbox.r1 + 1,
gw = vbox.g2 - vbox.g1 + 1,
bw = vbox.b2 - vbox.b1 + 1,
maxw = pv.max([rw, gw, bw]);
// only one pixel, no split
if (vbox.count() == 1) {
return [vbox.copy()]
}
/* Find the partial sum arrays along the selected axis. */
var total = 0,
partialsum = [],
lookaheadsum = [],
i, j, k, sum, index;
if (maxw == rw) {
for (i = vbox.r1; i <= vbox.r2; i++) {
sum = 0;
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(i, j, k);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
} else if (maxw == gw) {
for (i = vbox.g1; i <= vbox.g2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(j, i, k);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
} else { /* maxw == bw */
for (i = vbox.b1; i <= vbox.b2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.g1; k <= vbox.g2; k++) {
index = getColorIndex(j, k, i);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
}
partialsum.forEach(function (d, i) {
lookaheadsum[i] = total - d
});
function doCut(color) {
var dim1 = color + '1',
dim2 = color + '2',
left, right, vbox1, vbox2, d2, count2 = 0;
for (i = vbox[dim1]; i <= vbox[dim2]; i++) {
if (partialsum[i] > total / 2) {
vbox1 = vbox.copy();
vbox2 = vbox.copy();
left = i - vbox[dim1];
right = vbox[dim2] - i;
if (left <= right)
d2 = Math.min(vbox[dim2] - 1, ~~ (i +
right / 2));
else d2 = Math.max(vbox[dim1], ~~ (i - 1 -
left / 2));
// avoid 0-count boxes
while (!partialsum[d2]) d2++;
count2 = lookaheadsum[d2];
while (!count2 && partialsum[d2 - 1]) count2 =
lookaheadsum[--d2];
// set dimensions
vbox1[dim2] = d2;
vbox2[dim1] = vbox1[dim2] + 1;
// console.log('vbox
counts:', vbox.count(), vbox1.count(),
vbox2.count());
return [vbox1, vbox2];
}
}
}
// determine the cut planes
return maxw == rw ? doCut('r') :
maxw == gw ? doCut('g') :
doCut('b');
}
function quantize(pixels, maxcolors) {
// short-circuit
if (!pixels.length || maxcolors < 2 || maxcolors > 256) {
// console.log('wrong number of maxcolors');
return false;
}
// XXX: check color content and convert to grayscale if
insufficient
var histo = getHisto(pixels),
histosize = 1 << (3 * sigbits);
// check that we aren't below maxcolors already
var nColors = 0;
histo.forEach(function () {
nColors++
});
if (nColors <= maxcolors) {
// XXX: generate the new colors from the histo and return
}
// get the beginning vbox from the colors
var vbox = vboxFromPixels(pixels, histo),
pq = new PQueue(function (a, b) {
return pv.naturalOrder(a.count(), b.count())
});
pq.push(vbox);
// inner function to do the iteration
function iter(lh, target) {
var ncolors = 1,
niters = 0,
vbox;
while (niters < maxIterations) {
vbox = lh.pop();
if (!vbox.count()) { /* just put it back */
lh.push(vbox);
niters++;
continue;
}
// do the cut
var vboxes = medianCutApply(histo, vbox),
vbox1 = vboxes[0],
vbox2 = vboxes[1];
if (!vbox1) {
// console.log("vbox1 not
defined; shouldn't happen!");
return;
}
lh.push(vbox1);
if (vbox2) { /* vbox2 can be null */
lh.push(vbox2);
ncolors++;
}
if (ncolors >= target) return;
if (niters++ > maxIterations) {
// console.log("infinite
loop; perhaps too few pixels!");
return;
}
}
}
// first set of colors, sorted by population
iter(pq, fractByPopulations * maxcolors);
// Re-sort by the product of pixel occupancy times the
size in color space.
var pq2 = new PQueue(function (a, b) {
return pv.naturalOrder(a.count() * a.volume(),
b.count() * b.volume())
});
while (pq.size()) {
pq2.push(pq.pop());
}
// next set - generate the median cuts using the (npix *
vol) sorting.
iter(pq2, maxcolors - pq2.size());
// calculate the actual colors
var cmap = new CMap();
while (pq2.size()) {
cmap.push(pq2.pop());
}
return cmap;
}
return {
quantize: quantize
}
})();
</script>
The code is from quantitize.js. Thanks alot.
# has no method 'palette'"
I am learning to use the quantitize.js but getting the error "Uncaught
TypeError: Object # has no method 'palette'". I don't know what is wrong.
PLease help. Thanks.
Here is the code:
<div></div>
<script
src="jquery-2.0.3.min.js"></script>
<script>
/*!
* quantize.js Copyright 2008 Nick Rabinowitz.
* Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
*/
// fill out a couple protovis dependencies
/*!
* Block below copied from Protovis:
http://mbostock.github.com/protovis/
* Copyright 2010 Stanford Visualization Group
* Licensed under the BSD License:
http://www.opensource.org/licenses/bsd-license.php
*/
if (!pv) {
var pv = {
map: function (array, f) {
var o = {};
return f ? array.map(function (d, i) {
o.index = i;
return f.call(o, d);
}) : array.slice();
},
naturalOrder: function (a, b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
},
sum: function (array, f) {
var o = {};
return array.reduce(f ? function (p, d, i) {
o.index = i;
return p + f.call(o, d);
} : function (p, d) {
return p + d;
}, 0);
},
max: function (array, f) {
return Math.max.apply(null, f ? pv.map(array, f) :
array);
}
};
}
/**
* Basic Javascript port of the MMCQ (modified median cut
quantization)
* algorithm from the Leptonica library (http://www.leptonica.com/).
* Returns a color map you can use to map original pixels to the
reduced
* palette. Still a work in progress.
*
* @author Nick Rabinowitz
* @example
*/
// array of pixels as [R,G,B] arrays
var myPixels = [
[190, 197, 190],
[202, 204, 200],
[207, 214, 210],
[211, 214, 211],
[205, 207, 207]
// etc
];
var maxColors = 4;
var cmap = MMCQ.quantize(myPixels, maxColors);
var newPalette = cmap.palette();
var newPixels = myPixels.map(function (p) {
return cmap.map(p);
});
// */
var MMCQ = (function () {
// private constants
var sigbits = 5,
rshift = 8 - sigbits,
maxIterations = 1000,
fractByPopulations = 0.75;
// get reduced-space color index for a pixel
function getColorIndex(r, g, b) {
return (r << (2 * sigbits)) + (g << sigbits) + b;
}
// Simple priority queue
function PQueue(comparator) {
var contents = [],
sorted = false;
function sort() {
contents.sort(comparator);
sorted = true;
}
return {
push: function (o) {
contents.push(o);
sorted = false;
},
peek: function (index) {
if (!sorted) sort();
if (index === undefined) index = contents.length - 1;
return contents[index];
},
pop: function () {
if (!sorted) sort();
return contents.pop();
},
size: function () {
return contents.length;
},
map: function (f) {
return contents.map(f);
},
debug: function () {
if (!sorted) sort();
return contents;
}
};
}
// 3d color space box
function VBox(r1, r2, g1, g2, b1, b2, histo) {
var vbox = this;
vbox.r1 = r1;
vbox.r2 = r2;
vbox.g1 = g1;
vbox.g2 = g2;
vbox.b1 = b1;
vbox.b2 = b2;
vbox.histo = histo;
}
VBox.prototype = {
volume: function (force) {
var vbox = this;
if (!vbox._volume || force) {
vbox._volume = ((vbox.r2 - vbox.r1 + 1) * (vbox.g2
- vbox.g1 + 1) * (vbox.b2 - vbox.b1 + 1));
}
return vbox._volume;
},
count: function (force) {
var vbox = this,
histo = vbox.histo;
if (!vbox._count_set || force) {
var npix = 0,
i, j, k;
for (i = vbox.r1; i <= vbox.r2; i++) {
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(i, j, k);
npix += (histo[index] || 0);
}
}
}
vbox._count = npix;
vbox._count_set = true;
}
return vbox._count;
},
copy: function () {
var vbox = this;
return new VBox(vbox.r1, vbox.r2, vbox.g1, vbox.g2,
vbox.b1, vbox.b2, vbox.histo);
},
avg: function (force) {
var vbox = this,
histo = vbox.histo;
if (!vbox._avg || force) {
var ntot = 0,
mult = 1 << (8 - sigbits),
rsum = 0,
gsum = 0,
bsum = 0,
hval,
i, j, k, histoindex;
for (i = vbox.r1; i <= vbox.r2; i++) {
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
histoindex = getColorIndex(i, j, k);
hval = histo[histoindex] || 0;
ntot += hval;
rsum += (hval * (i + 0.5) * mult);
gsum += (hval * (j + 0.5) * mult);
bsum += (hval * (k + 0.5) * mult);
}
}
}
if (ntot) {
vbox._avg = [~~(rsum / ntot), ~~ (gsum /
ntot), ~~ (bsum / ntot)];
} else {
// console.log('empty box');
vbox._avg = [~~(mult * (vbox.r1 + vbox.r2 + 1)
/ 2), ~~ (mult * (vbox.g1 + vbox.g2 + 1) / 2),
~~ (mult * (vbox.b1 + vbox.b2 + 1) / 2)];
}
}
return vbox._avg;
},
contains: function (pixel) {
var vbox = this,
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
return (rval >= vbox.r1 && rval <= vbox.r2 &&
gval >= vbox.g1 && rval <= vbox.g2 &&
bval >= vbox.b1 && rval <= vbox.b2);
}
};
// Color map
function CMap() {
this.vboxes = new PQueue(function (a, b) {
return pv.naturalOrder(
a.vbox.count() * a.vbox.volume(),
b.vbox.count() * b.vbox.volume()
)
});;
}
CMap.prototype = {
push: function (vbox) {
this.vboxes.push({
vbox: vbox,
color: vbox.avg()
});
},
palette: function () {
return this.vboxes.map(function (vb) {
return vb.color
});
},
size: function () {
return this.vboxes.size();
},
map: function (color) {
var vboxes = this.vboxes;
for (var i = 0; i < vboxes.size(); i++) {
if (vboxes.peek(i).vbox.contains(color)) {
return vboxes.peek(i).color;
}
}
return this.nearest(color);
},
nearest: function (color) {
var vboxes = this.vboxes,
d1, d2, pColor;
for (var i = 0; i < vboxes.size(); i++) {
d2 = Math.sqrt(
Math.pow(color[0] - vboxes.peek(i).color[0], 2) +
Math.pow(color[1] - vboxes.peek(i).color[1], 2) +
Math.pow(color[1] - vboxes.peek(i).color[1], 2)
);
if (d2 < d1 || d1 === undefined) {
d1 = d2;
pColor = vboxes.peek(i).color;
}
}
return pColor;
},
forcebw: function () {
// XXX: won't work yet
var vboxes = this.vboxes;
vboxes.sort(function (a, b) {
return pv.naturalOrder(pv.sum(a.color),
pv.sum(b.color))
});
// force darkest color to black if everything < 5
var lowest = vboxes[0].color;
if (lowest[0] < 5 && lowest[1] < 5 && lowest[2] < 5)
vboxes[0].color = [0, 0, 0];
// force lightest color to white if everything > 251
var idx = vboxes.length - 1,
highest = vboxes[idx].color;
if (highest[0] > 251 && highest[1] > 251 && highest[2]
> 251)
vboxes[idx].color = [255, 255, 255];
}
};
// histo (1-d array, giving the number of pixels in
// each quantized region of color space), or null on error
function getHisto(pixels) {
var histosize = 1 << (3 * sigbits),
histo = new Array(histosize),
index, rval, gval, bval;
pixels.forEach(function (pixel) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
index = getColorIndex(rval, gval, bval);
histo[index] = (histo[index] || 0) + 1;
});
return histo;
}
function vboxFromPixels(pixels, histo) {
var rmin = 1000000,
rmax = 0,
gmin = 1000000,
gmax = 0,
bmin = 1000000,
bmax = 0,
rval, gval, bval;
// find min/max
pixels.forEach(function (pixel) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
if (rval < rmin) rmin = rval;
else if (rval > rmax) rmax = rval;
if (gval < gmin) gmin = gval;
else if (gval > gmax) gmax = gval;
if (bval < bmin) bmin = bval;
else if (bval > bmax) bmax = bval;
});
return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);
}
function medianCutApply(histo, vbox) {
if (!vbox.count()) return;
var rw = vbox.r2 - vbox.r1 + 1,
gw = vbox.g2 - vbox.g1 + 1,
bw = vbox.b2 - vbox.b1 + 1,
maxw = pv.max([rw, gw, bw]);
// only one pixel, no split
if (vbox.count() == 1) {
return [vbox.copy()]
}
/* Find the partial sum arrays along the selected axis. */
var total = 0,
partialsum = [],
lookaheadsum = [],
i, j, k, sum, index;
if (maxw == rw) {
for (i = vbox.r1; i <= vbox.r2; i++) {
sum = 0;
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(i, j, k);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
} else if (maxw == gw) {
for (i = vbox.g1; i <= vbox.g2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(j, i, k);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
} else { /* maxw == bw */
for (i = vbox.b1; i <= vbox.b2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.g1; k <= vbox.g2; k++) {
index = getColorIndex(j, k, i);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
}
partialsum.forEach(function (d, i) {
lookaheadsum[i] = total - d
});
function doCut(color) {
var dim1 = color + '1',
dim2 = color + '2',
left, right, vbox1, vbox2, d2, count2 = 0;
for (i = vbox[dim1]; i <= vbox[dim2]; i++) {
if (partialsum[i] > total / 2) {
vbox1 = vbox.copy();
vbox2 = vbox.copy();
left = i - vbox[dim1];
right = vbox[dim2] - i;
if (left <= right)
d2 = Math.min(vbox[dim2] - 1, ~~ (i +
right / 2));
else d2 = Math.max(vbox[dim1], ~~ (i - 1 -
left / 2));
// avoid 0-count boxes
while (!partialsum[d2]) d2++;
count2 = lookaheadsum[d2];
while (!count2 && partialsum[d2 - 1]) count2 =
lookaheadsum[--d2];
// set dimensions
vbox1[dim2] = d2;
vbox2[dim1] = vbox1[dim2] + 1;
// console.log('vbox
counts:', vbox.count(), vbox1.count(),
vbox2.count());
return [vbox1, vbox2];
}
}
}
// determine the cut planes
return maxw == rw ? doCut('r') :
maxw == gw ? doCut('g') :
doCut('b');
}
function quantize(pixels, maxcolors) {
// short-circuit
if (!pixels.length || maxcolors < 2 || maxcolors > 256) {
// console.log('wrong number of maxcolors');
return false;
}
// XXX: check color content and convert to grayscale if
insufficient
var histo = getHisto(pixels),
histosize = 1 << (3 * sigbits);
// check that we aren't below maxcolors already
var nColors = 0;
histo.forEach(function () {
nColors++
});
if (nColors <= maxcolors) {
// XXX: generate the new colors from the histo and return
}
// get the beginning vbox from the colors
var vbox = vboxFromPixels(pixels, histo),
pq = new PQueue(function (a, b) {
return pv.naturalOrder(a.count(), b.count())
});
pq.push(vbox);
// inner function to do the iteration
function iter(lh, target) {
var ncolors = 1,
niters = 0,
vbox;
while (niters < maxIterations) {
vbox = lh.pop();
if (!vbox.count()) { /* just put it back */
lh.push(vbox);
niters++;
continue;
}
// do the cut
var vboxes = medianCutApply(histo, vbox),
vbox1 = vboxes[0],
vbox2 = vboxes[1];
if (!vbox1) {
// console.log("vbox1 not
defined; shouldn't happen!");
return;
}
lh.push(vbox1);
if (vbox2) { /* vbox2 can be null */
lh.push(vbox2);
ncolors++;
}
if (ncolors >= target) return;
if (niters++ > maxIterations) {
// console.log("infinite
loop; perhaps too few pixels!");
return;
}
}
}
// first set of colors, sorted by population
iter(pq, fractByPopulations * maxcolors);
// Re-sort by the product of pixel occupancy times the
size in color space.
var pq2 = new PQueue(function (a, b) {
return pv.naturalOrder(a.count() * a.volume(),
b.count() * b.volume())
});
while (pq.size()) {
pq2.push(pq.pop());
}
// next set - generate the median cuts using the (npix *
vol) sorting.
iter(pq2, maxcolors - pq2.size());
// calculate the actual colors
var cmap = new CMap();
while (pq2.size()) {
cmap.push(pq2.pop());
}
return cmap;
}
return {
quantize: quantize
}
})();
</script>
The code is from quantitize.js. Thanks alot.
Subscribe to:
Posts (Atom)