Thursday, 3 October 2013

InvokeOnMainThread doesn't work with `method group`

InvokeOnMainThread doesn't work with `method group`

NOTE: I found a workaround to my problem even before asking the question,
but I'm still wondering why it behave like this.
I'm doing an usual xamarin.iOS application, using async/await, Mvvm, ...
nothing fancy on the technology side.
I found out that the following code (using a method group) wasn't working:
ViewModel.PropertyChanged += (sender, e) => {
if (e.PropertyName != "MyProperty")
return;
InvokeOnMainThread (tableViewController.TableView.ReloadData);
};
If I put a breakpoint on InvokeOnMainThread, I can see the exception:

But the same code with a lambda expression works just fine.
ViewModel.PropertyChanged += (sender, e) => {
if (e.PropertyName != "MyProperty")
return;
InvokeOnMainThread (() => tableViewController.TableView.ReloadData ());
};
A part of me is suspecting a bug, another part is already blaming my
ignorance. Anyone knows which part is right ?
Version details:
Xamarin Studio
Version 4.1.12 (build 6)
Installation UUID: [...]
Runtime:
Mono 3.2.3 ((no/8d3b4b7)
GTK+ 2.24.20 theme: Raleigh
GTK# (2.12.0.0)
Package version: 302030000
Apple Developer Tools
Xcode 5.0 (3332.22)
Build 5A1412
Xamarin.iOS
Version: 7.0.1.4 (Business Edition)
Hash: [...]
Branch:
Build date: 2013-20-09 23:14:32-0400
Build Information
Release ID: 401120006
Git revision: a9ae69a4bf37955e4ab4df0cec7804f574c51f72
Build date: 2013-09-25 16:59:37+0000
Xamarin addins: 761ae26f220068dda0b62f0dd2253f617589a8c6
Operating System
Mac OS X 10.8.5
Darwin Stephanes-MacBook-Air.local 12.5.0 Darwin Kernel Version 12.5.0
Mon Jul 29 16:33:49 PDT 2013
root:xnu-2050.48.11~1/RELEASE_X86_64 x86_64

Wednesday, 2 October 2013

NSJSONSerialization - What is the proper value to specify no NSJSONWritingOptions for dataWithJSONObject:options:error:?

NSJSONSerialization - What is the proper value to specify no
NSJSONWritingOptions for dataWithJSONObject:options:error:?

Apple's documentation has the NSJSONWritingOptions enum with one constant
defined: NSJSONWritingPrettyPrinted, and says that "If this option is not
set, the most compact possible JSON representation is generated."
I definitely want the most compact JSON representation.
My question is: what is the proper value to pass the
dataWithJSONObject:options:error: function if I don't want pretty printed,
and why?
The NSJSONWritingOptions enum is defined as
enum { NSJSONWritingPrettyPrinted = (1UL << 0) }; typedef NSUInteger
NSJSONWritingOptions;
I have read in a different post that 0 should be passed, but with no
further explanation as to why it shouldn't be nil.

Why content_for method undefined in rails view?

Why content_for method undefined in rails view?

I have a rails project.
In the application.html.slim I have:
doctype html
html
head
title RailsMongoidPj
= stylesheet_link_tag "application", media: "all",
"data-turbolinks-track" => true
= javascript_include_tag "application", "data-turbolinks-track" => true
= csrf_meta_tags
meta content="width=device-width, initial-scale=1.0" name="viewport"
= yield(:html_head)
body
= yield
In a controller SearchController, which has a method:
def javascript(*files)
content_for(:html_head) do
javascript_include_tag(*files)
end
end
helper_method :javascript
Also this controller has a method new with a corresponding view, which
content is:
= javascript('/vendor/assets/javascript/handelbars.runtime.js')
- content_for :html_head do
script#entry-template type="text/x-handlebars-template"
| template content
But I have an error:
undefined method `content_for' for #<SearchFlickrController:0x007f8e4f2bae78>
Extracted source (around line #3):
1 / search flickr api page
2
3 = javascript('/vendor/assets/javascript/handelbars.runtime.js')
4
5 - content_for :html_head do
6 script#entry-template type="text/x-handlebars-template"
Why the method is content_for undefined? Isn't it an standard rails method?

When overriding the registration controller from devise, is it possible to access the newly created user on the create action?

When overriding the registration controller from devise, is it possible to
access the newly created user on the create action?

I'm trying to create a folder right after a user registers, so I override
the create action on the registration controller (devise) but I don't know
how to access the newly created user in order to create the folder with
it's name to upload files later.
So far I've got this:
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
super
create_folder
end
def update
super
end
def create_folder
path = Pathname.new(':rails_root/tmp/')
directory_name = ":current_user"
Dir.mkdir(path, directory_name) unless File.exists?(directory_name)
end
end
routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
I followed this to override the registration controller.
Should I leave it there or move it to the create action? Instead of using
a method
is that the right way to access the current user?
Maybe instead of registration it's better to do it on sign in?
I'd appreciate any help I can get.

LINQ to SQL, not null, use default value

LINQ to SQL, not null, use default value

I'm using EF with DB First. My table looks like this:
CREATE TABLE [dbo].[Person](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[dob] [datetime] NOT NULL
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED )
GO
ALTER TABLE [dbo].[Person]
ADD CONSTRAINT [DF_Person_dob] DEFAULT ('12.12.3000') FOR [dob]
After using DB First I get the following partial Person class:
using System;
public partial class Person
{
public int id { get; set; }
public string name { get; set; }
public System.DateTime dob { get; set; }
}
The problem I have is that when I want to use the DB generated default
value for 'dob' field I get an exception because nulls are not allowed.
I'm trying to do this:
using (var db = new NullTestEntities())
{
var person = db.Person.Create();
person.name = "John Doe";
db.Person.Add(person);
db.SaveChanges();
}
I've tried adding
Column(IsDataBaseGenerated=true)
but I can't compile because I get an error:
'System.ComponentModel.DataAnnotations.Schema.ColumnAttribute' does not
contain a
definition for 'IsDatabaseGenerated'
What do I need to do in order to not define the dob attribute in C# code
and let the database generate the default value?

Tuesday, 1 October 2013

Menu images dropping down a little to low?

Menu images dropping down a little to low?

You can view the page in question here: http://portal.envisionlocal.com
Basically the image menu-sep.png which acts as a line break between the
different menus in my header is dropping down just a fraction below the
navigation bar and I can't figure out what to do to fix that. I'd prefer
to fix it inline instead of in a CSS file because the only solution to
fixing in the CSS file that I've found is editing line 52 of flex.css:
I changed
font: 13px/1.6em "Open Sans",Arial,sans-serif;
to
font: 11px/1.6em "Open Sans",Arial,sans-serif;
and it fixed the problem but also made all of the other text on the page
way too small - it didn't change the text size in the header but did fix
the problem for some reason...
Any help would be appreciated! Thanks!

Which is most cache friendly?

Which is most cache friendly?

I am trying to get a good grip on data oriented design and how to program
best with the cache in mind. There's basically two scenarios that I cannot
quite decide which is better and why - is it better to have a vector of
objects, or several vectors with the objects atomic data?
A) Vector of objects example
struct A
{
GLsizei mIndices;
GLuint mVBO;
GLuint mIndexBuffer;
GLuint mVAO;
size_t vertexDataSize;
size_t normalDataSize;
};
std::vector<A> gMeshes;
for_each(gMeshes as mesh)
{
glBindVertexArray(mesh.mVAO);
glDrawElements(GL_TRIANGLES, mesh.mIndices, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
....
}
B) Vectors with the atomic data
std::vector<GLsizei> gIndices;
std::vector<GLuint> gVBOs;
std::vector<GLuint> gIndexBuffers;
std::vector<GLuint> gVAOs;
std::vector<size_t> gVertexDataSizes;
std::vector<size_t> gNormalDataSizes;
size_t numMeshes = ...;
for (index = 0; index++; index < numMeshes)
{
glBindVertexArray(gVAOs[index]);
glDrawElements(GL_TRIANGLES, gIndices[index], GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
....
}
Which one is more memory efficient and cache friendly resulting in less
cache misses and better performance, and why?

SIEM DSCC - Upgrade Fails and then web console doesn't shows anything

SIEM DSCC - Upgrade Fails and then web console doesn't shows anything

Since trying to patch, we can not access the Web Interface, the Console
page is empty.
We also tried to upgrade trough CLI but it returns this error messages
Checking for undeployed changes...
Found undeployed changes!
[PATCH_UPDATER] [ERROR] The patch cannot continue because you have
undeployed changes in your system.
[PATCH_UPDATER] [ERROR] Please go to the Administration Console and deploy
changes before continuing with the patch.
An error was encountered attempting to process patches. Please contact
customer support for further assistance.
Check the Build Version of DSCC
[root@NOCMSIEM1 ~]# cat /opt/qradar/conf/build_version
7.1.0.414913
Before we start we did a backup of the configuration.
-rw-r--r-- 1 nobody nobody 57428857 Sep 19 12:51
backup.BackupUpgrade.NOCMSIEM1_3.19_09_2013.config.1379587862604.tgz
I don't have experience and have never worked with this console. But
looking through the internet I have seen similar errors in your forum and
I think you maybe could help me, I think the error is related to the
tomcat.
/opt/tomcat6/logs/catalina.2013-09-23.log
------------------
Sep 25, 2013 3:10:14 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Sep 25, 2013 3:10:14 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Sep 25, 2013 3:10:14 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=1/14 config=null
Sep 25, 2013 3:10:14 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 6132 ms
Sep 25, 2013 3:10:14 PM org.apache.coyote.http11.Http11Protocol pause
INFO: Pausing Coyote HTTP/1.1 on http-8080
Sep 25, 2013 3:10:15 PM org.apache.catalina.core.StandardService stop
INFO: Stopping service Catalina
Sep 25, 2013 3:10:15 PM org.apache.coyote.http11.Http11Protocol destroy
INFO: Stopping Coyote HTTP/1.1 on http-8080
Sep 25, 2013 3:10:24 PM org.apache.catalina.realm.JAASRealm
setUseContextClassLoader
INFO: Setting useContextClassLoader = false
Sep 25, 2013 3:10:24 PM org.apache.tomcat.util.digester.SetPropertiesRule
begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Realm} Setting property
'debug' to '99' did not find a matching property.
Sep 25, 2013 3:10:24 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Sep 25, 2013 3:10:24 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 355 ms
Sep 25, 2013 3:10:24 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Sep 25, 2013 3:10:24 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
Sep 25, 2013 3:10:24 PM org.apache.catalina.startup.HostConfig
deployDirectory
INFO: Deploying web application directory console
Sep 25, 2013 3:10:29 PM
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
contextInitialized
INFO: WSSERVLET12: JAX-WS context listener initializing
Sep 25, 2013 3:10:30 PM
com.sun.xml.ws.transport.http.servlet.WSServletDelegate <init>
**INFO: WSSERVLET14: JAX-WS servlet initializing
Sep 25, 2013 3:10:30 PM org.apache.catalina.core.StandardContext start
SEVERE: Error listenerStart
Sep 25, 2013 3:10:30 PM org.apache.catalina.core.StandardContext start
SEVERE: Context [/console] startup failed due to previous errors**
Sep 25, 2013 3:10:30 PM
com.sun.xml.ws.transport.http.servlet.WSServletDelegate destroy
INFO: WSSERVLET15: JAX-WS servlet destroyed
Sep 25, 2013 3:10:30 PM
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
contextDestroyed
INFO: WSSERVLET13: JAX-WS context listener destroyed
Sep 25, 2013 3:10:30 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Sep 25, 2013 3:10:30 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Sep 25, 2013 3:10:30 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/13 config=null
Sep 25, 2013 3:10:30 PM org.apache.catalina.startup.Catalina start
We have restored from the backup settings and reboot the appliance several
times and have not gotten to load the DSCC web interface.

Series $\sum=?iso-8859-1?Q?=5F{n_=3D_0}^{\infty}_?=(-1)^n \frac{5}{4^n}$ – math.stackexchange.com

Series $\sum_{n = 0}^{\infty} (-1)^n \frac{5}{4^n}$ – math.stackexchange.com

$$\sum_{n = 0}^{\infty} (-1)^n \frac{5}{4^n}$$ I tried writing out the
values for n = 0, 1, 2, 3, 4 so try to find partial sum equation but was
unsuccessful.

Monday, 30 September 2013

Using absolute coordinates in 2D affine transformation matrix

Using absolute coordinates in 2D affine transformation matrix

In my 2D animation program I have a sprite which transformation is
described by a 2D affine transformation matrix (SVGMatrix):
$$ \begin{bmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \\ \end{bmatrix} $$
I'm trying to figure out how to set this sprite position to given screen
coordinates:
$$ \begin{bmatrix} x \\ y \\ 1 \\ \end{bmatrix} $$
The sprite position is the position of sprite's pivot point, which is
defined by sprite's transformation matrix.
For example, if a sprite of 64 x 64 pixels in size has this transformation
matrix:
$$ \begin{bmatrix} 2 & 0 & 32 \\ 0 & 2 & 32 \\ 0 & 0 & 1 \\ \end{bmatrix} $$
...The sprite's pivot point is in its center, and the sprite is scaled x2.
The operation I look for, set_position(x, y), should change sprite's
transformation matrix in such way, so that the center (pivot point) of
this sprite will be at $(x, y)$.
(Unfortunately, I'm quite rusty on the topic and googling does not yield
anything satisfactory. However, I feel that this is an embarassingly basic
question...)
Say, I want the sprite to appear at $(300, 200)$:
set_position(300, 200)
For a sprite with identity transformation matrix —not scaled, rotated,
inverted or skewed, pivot at $(0, 0)$:
$$ \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \\ \end{bmatrix} $$
...The result would be:
$$ \begin{bmatrix} 1 & 0 & 300 \\ 0 & 1 & 200 \\ 0 & 0 & 1 \\
\end{bmatrix} $$
If the sprite was scaled:
$$ \begin{bmatrix} 2 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 1 \\ \end{bmatrix} $$
...The result should take that in account:
$$ \begin{bmatrix} 2 & 0 & 150 \\ 0 & 2 & 100 \\ 0 & 0 & 1 \\
\end{bmatrix} $$
Same thing for rotation, inversion and skew/shear.
That is, for a sprite of 64 x 64 pixels in size, this operation (in
pseudocode) would move the sprite's pivot to its center and will rotate
around the pivot by 90 degrees:
translate(32, 32)
rotate(ð/2)
The corresponding matrix for the sprite:
$$ \begin{bmatrix} 0 & 1 & 32 \\ -1 & 0 & 32 \\ 0 & 0 & 1 \\ \end{bmatrix} $$
Now, my set_position(300, 200) operation should change the sprite's
transformation matrix so that the sprite's center (i.e. the pivot) would
be at specified coordinates, $(300, 200)$.
Calculating expected set_position() result in this case will require some
trigonometry, I guess, since sprite's coordinate system was rotated
beforehand.
Looks like I'm missing something. Any clues on how to approach this?

Checking my work on a Lennard-Jones potential problem in differential equations

Checking my work on a Lennard-Jones potential problem in differential
equations

The Lennard-Jones potential is $$U(r) = \left[ \left( \frac{\rho}{r}
\right)^{12} - \left( \frac{\rho}{r} \right)^6 \right]$$.
What is the equilibrium distance?
OK, so I know that the equilibrium distance has to be where the force is
zero. So all I need do is take a derivative of $U(r)$. I get:
$$ \frac{dU(r)}{dr} = -12 \rho^{12} r^{-13} + 6 \rho^6 r^{-7} $$
and making that equal to zero we end up with $ r^6 = -2 \rho^6 $
So far so good, that means $r_{min} = \rho 2^{\frac{1}{6}} $
Now to show that it is a simple harmonic oscillator.
$$ F(r) = -12 \rho^{12} r^{-13} + 6 \rho^6 r^{-7} = ma = m \ddot r $$
so
$$ \ddot r = \frac{F(r)}{m} = -12 \frac{\rho^{12}}{r^{13}m} + 6 \frac{
\rho^6} {r^{7}m} $$
When I plug in the value of $r_{min}$ I end up with $ \ddot r (0) =
\frac{-3}{mr} - \frac{3}{mr} = \frac {-6}{mr} $. Which would seem to
indicate that the natural frequency is $\sqrt{\frac{-6}{mr}}$ which is
$\sqrt{\frac{-6}{m} \frac{1}{2^{1/6}\rho}}$
But that's an imaginary quantity so I think I messed up somewhere. If
anyone can point out a mistake that would be most appreciated.

How to format composition functions in python?

How to format composition functions in python?

When I use composition functions Such as Collatz(MerrenianPrime(Number)) I
get the error of:
'Merrenian=2**PrimeCount(Number)-1
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'NoneType.'
How would I resolve this?
This is my code:
def MerrenianPrime(Number):
Merrenian=2**Prime.PrimeCount(Number)-1 #PrimeCount=nth Prime and this
is where I get an error
if Prime.isPrime(Merrenian)==True: #isPrime function checks primality
of number
print "the prime number",Merrenian,"was found"
else:
print Merrenian,"is not prime."
thanks!

MS Word: regex for identifying hyperlinks

MS Word: regex for identifying hyperlinks

I am working on books. Part of my brief is to find and remove hyperlinks.
Commonly these are hidden underneath citations, so can be very hard to
identify as they look identical to surrounding text.
E.g. something like "(1876) 1 CPD 691 at 701" can look like text but has
an underlying hyperlink. Mouse hovering works to ID them but takes an age,
especially when there are 1000s in footnotes! :)
The books are all styled using custom, in-house MS Word styles so the
in-built Find > Format > Style > Hyperlink doesn't work.
Is there a Word regex that can identify hyperlinks in Word docs using the
Find function using Wildcards? I searched existing questions but couldn't
find anything that looked to match my needs...
Thanks!

Sunday, 29 September 2013

Incremental loading of GridView with MVVMCross in WinRT

Incremental loading of GridView with MVVMCross in WinRT

I'm struggling to come with a way to implement incremental loading of
GridView when using WinRT.
The documentation only specifies one method for doing incremental loading
in WinRT - binding to a collection that implements
ISupportIncrementalLoading. However, this interface does not exist in
portable class library.
I am wondering if it's possible to keep viewmodels in a core PCL and still
implement incremental loading?

DFP API Keyword Forecasting

DFP API Keyword Forecasting

I want to create an app which will show me the forecasting on my DFP
network by keywords and by time. It seems that the api only forecasts on
created ad_id's. Does this mean, I would require a dummy ad_id, then run
that through the forecasting methods?
I can't seem to find good tutorials regarding dfp api's. Google provides
examples, but nothing great.

Algorithm for counting substrings in a numerical range

Algorithm for counting substrings in a numerical range

I'm looking for a fast algorithm that can be used to solve this problem:
Giving A and B integers (in the range [0,10^18]), and giving a list of N
(N<=1000) numerical substrings; the goal is to count all the numbers in
the range [A,B] containing any of the N substrings. We've always A<=B and
the numerical substrings are also integers in the range [0,10^18].
Example1: if A=10, B=22, and giving N=2 substrings={1,10} ; the count
would be = 11; counting the numbers: 10->19 and 21.
Example2: If A=175, B=201, and giving N=3 substrings={55,0,200} ; the
count would be = 4; counting the numbers: 180, 190, 200 and 201.
The straight-forward way is to analyse each integer in the range [A,B],
one after another, but it's not a solution since the range can be so big
(until 10^18 integers).
One first thing I did to reduce the problem complexity is to delete some
useless substrings from the original list of N substrings, such that "no
substring is contained in another". For example: {1,10} becomes {1} and
{55,0,200} becomes {55,0}. This won't change the final count.
Next, even assuming we can get the count for one substring in the range
[A,B], we still cannot sum this count with those of other substrings from
the list, as one number can contain many substrings and should not be
counted more than once.
Any ideas to solve the problem et get the wanted count?
Thanks

How do I convert vector of bytes (u8) to string in Rust 0.8?

How do I convert vector of bytes (u8) to string in Rust 0.8?

I am trying to write simple tcp/ip client in Rust and I need to print out
my buffer I got from the server. How do I convert the u8 vector to string
for printing?

Saturday, 28 September 2013

Matplotlib overlapping annotations / text

Matplotlib overlapping annotations / text

I'm trying to stop annotation text overlapping in my graphs. The method
suggested in the accepted answer to Matplotlib overlapping annotations
looks extremely promising, however is for bar graphs. I'm having trouble
converting the "axis" methods over to what I want to do, and I don't
understand how the text lines up.
import sys
import matplotlib.pyplot as plt
# start new plot
plt.clf()
plt.xlabel("Proportional Euclidean Distance")
plt.ylabel("Percentage Timewindows Attended")
plt.title("Test plot")
together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50,
1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100,
1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150,
1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)]
together.sort()
for x,y,z in together:
plt.annotate(str(x), xy=(y, z), size=8)
eucs = [y for (x,y,z) in together]
covers = [z for (x,y,z) in together]
p1 = plt.plot(eucs,covers,color="black", alpha=0.5)
plt.savefig("test.png")
Images (if this works) can be found here (this code):

and here (more complicated):

Identify extension of a file without extension

Identify extension of a file without extension

In my current application I am downloading few files from server, and
storing them locally.
Based on extension of file I am loading the file in appropriate view.
Example:
file extensions: mov, 3gp, m4a, etc., => display in media player.
file extensions: rtf, pptx, numbers, etc., =>display in UIWebView.
file extensions: gif, png, xbm, etc., =>display in UIImageView.
Problem is: some of the downloaded files may not have any extension.
One approach which I found is- in connectionDidFinishLoading obtain
MIMEType from response and from that obtain file extension. I used below
code, for the same:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
CFStringRef mimeType = (__bridge CFStringRef)[_respo MIMEType];
CFStringRef uti =
UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType,
NULL);
CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti,
kUTTagClassFilenameExtension);
NSString *fileName = [NSString stringWithFormat:@"%@.%@", [[_respo
suggestedFilename] stringByDeletingPathExtension], (__bridge NSString
*)extension];
[[NSFileManager defaultManager] createFileAtPath:[[self docsDir]
stringByAppendingPathComponent:[NSString
stringWithFormat:@"Downloads/%@", fileName]] contents:_downloadedData
attributes:nil];
}
Now my questions are:
Is there any other way to identify file extension for the files without
extensions, say from NSData object?
In place of checking file extension, is there any other way to show the
file in appropriate view?
Please suggest.

Android how to set up a Search Interface for RadioButtons

Android how to set up a Search Interface for RadioButtons

I have seen this two links:
http://developer.android.com/guide/topics/search/index.html
http://developer.android.com/training/search/setup.html
and I have set up the searching interface, but now I have a question: What
I have is to have an activity with a list of buttons, and since there are
a lot of them, I want the user to be able to search for the buttons by
there text. How could I search the buttons?

Github Master repository changes

Github Master repository changes

I'm pretty new to github and have a few questions.
I forked a repository and commited some changes to it. When the master
repository gets updated or somethling like this, do i get these updates
to? Or do i have to merge them manually?

Friday, 27 September 2013

Encrypt a password in a preferences/properties file - Java

Encrypt a password in a preferences/properties file - Java

I'm no expert in cryptography, cracking passwords and security. I need to
store in the preferences a password and username for a SQL server that
I'll use to connect the client to the SQL server.
I've been reading around, mostly here in SO but most of them are older
than 2 years and we all know the security world is changing on a fast
pace.
From what I read, I came to the conclusion that most people suggest
hashing the password using SHA-XXX and/or recommend using jasypt to
encrypt and decrypt the password
So my question is what is the most secure way to protect passwords in a
preferences file? Can I just use SHA-512 with salt and save the salt in
the preferences file as well? Is this safe?

Give a box an ID, once clicked shows alert of that ID?

Give a box an ID, once clicked shows alert of that ID?

The idea is when the button is clicked it will generate as many boxes as
there are clicks (ex: 20 clicks = 20 boxes on the page) However, I need it
where when you click on the box an alert of a unique ID pops up. I'm not
sure of how to assign each box a unique ID...
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>E02W03_Q2</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="E03_Q2.css">
<script src="E03_Q2.js"></script>
</head>
<body>
<form>
<input type="button" id="addButton" value="Add Box">
</form>
<div class="clrBox">
</div>
</body>
</html>
The CSS code:
.clrBox {
background-color: red;
width: 50px;
height: 50px;
margin: 10px;
}
The JavaScript code:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
var box = document.getElementByTagName("div");
button.onclick = handleButtonClick;
box.onclick = handelBoxClick;
}
function handleButtonClick(e) {
var div = document.createElement("div");
div.setAttribute("class","clrBox");
var body = document.getElementsByTagName("body");
body[0].appendChild(div);
}
function handelBoxClick(e){ <<This isnt quite finished yet since i'm not
sure of how to assign each box a unique id...
var div = document.getElementById("");
alert();
}

Weird Twitter error

Weird Twitter error

I'm trying to access the user's credentials of Twitter with this code :
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil
completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
NSURL *requestURL = [NSURL
URLWithString:@"https:api.twitter.com/1.1/account/verify_credentials.json"];
SLRequest *getRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:requestURL parameters:nil];
[getRequest setAccount:twitterAccount];
[getRequest performRequestWithHandler:^(NSData
*responseData, NSHTTPURLResponse *urlResponse, NSError
*error) {
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData options:kNilOptions
error:nil];
NSLog(@"Twitter Response : %@ ",json);
}];
}
};
}];
}
With this code i'm getting this error :
Twitter Response : {
errors = (
{
code = 32;
message = "Could not authenticate you";
}
);
}
The weird thing is that, if i try tweet something or access some other
endpoint of Twitter,where is required to have a oauth-token, the operation
ends successfully.
Thank you all in advance!

SolidCone not visible in OpenGL

SolidCone not visible in OpenGL

I am new to OpenGL so I imagine that I have overlooked something simple
but I have seemed to have lost my cone. In the code below I set up my
viewport and its glOrtho. Then I try to draw a cone. It should be placed
in the middle of the bottom edge of the window, it should also follow the
mouse so that the base is facing the mouse. But the cone never appears. I
have tried different translations and different rotations, I have tried to
take those out, I have even tried to give it color to make it appear, but
nothing. So where is my cone?
###called when the window is created, or reshaped
def reshape(self, height, width):
if height >= 90 and width >= 90:
self.index_location_dict =
self.create_index_location_dict(height, width)
self.height = height
self.width = width
glViewport(0, 0, height, width)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, height, width, 0.0, -20.0, 20.0)
glEnable(GL_DEPTH_TEST)
else:
self.game_over = True
###called by the a display function
def draw_cannon(self):
glPushMatrix()
glTranslatef(self.width/2, 0.0, 0.0)
rotation_angle = self.cannon_rotation()
glRotatef(rotation_angle, 0, 0, 1)
glutSolidCone(10, 20, 50, 50)
glPopMatrix()

Payment gateway using paypal

Payment gateway using paypal

I am creating a web app using jsp where I require to implement a payment
gateway. I got this site
https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/ht_test-pps-buttons/
This is similar to what I want but in this case to make a payment I should
have an account on payapal and enter the email id and password to make a
transaction but in my case I want to be able to enter the credit card
number and CVV number.I tried finding on the same site but couldnt find
anything. Could anyone provide me with a link which could help?

Thursday, 26 September 2013

Uncaught Error: No define call for reveal

Uncaught Error: No define call for reveal

This what I did in main.js :
requirejs.config({
enforceDefine: true,
paths: {
"jquery": "libs/jquery/jquery-min",
"underscore": "libs/underscore/underscore-min",
"backbone": "libs/backbone/backbone-min",
"reveal":"libs/jquery/jquery.reveal"
},
shim: {
"underscore": {
deps: [],
exports: "_"
},
"backbone": {
deps: ["jquery", "underscore"],
exports: "Backbone"
},
"reveal": {
exports: "Reveal"
}
}
});
Uncaught Error: No define call for reveal
http://requirejs.org/docs/errors.html#nodefine
Any idea what could be causing this. Thanks.

Wednesday, 25 September 2013

Background color doesn't apply after changing visibility

Background color doesn't apply after changing visibility

The pink background color disappear after I change the visibility of the
container ul tag. The codes are as follows. Did I miss something ? Why
does the li doesn't inherit the background color of ul tag?
<style type="text/css">
.div_r3r4_container { width:760px; background-color:lightblue; }
.div_r3_class { margin-left:132px; width:630px; }
.ul_r3hz_class { background-color:pink; font-size:0px; padding:2px 2px
1px 3px;list-style:none;margin:0; }
.li_r3hz_class { font-size:14px; color:black; display:inline; }
.ul_r4hz_class {background-color:yellow; font-size:0px; border:1px solid
red; padding:1px 2px 2px 3px;list-style:none;margin:0; }
.li_r4hz_class {font-size:14px; color:green; display:inline; }
</style>
<div id="div_r3_r4_id" class="div_r3r4_container">
<label id="city"> hide and show ul </label>
<div class="div_r3_class" >
<ul class="ul_r3hz_class" id="sid" >
<li class="li_r3hz_class"> aaaa, aaaa1, aaa2, aaa3, </li>
<li class="li_r3hz_class"> aaaaa4, aaaa5, aaaa5, aaa6, </li>
</ul>
</div>
<div class="div_r4_class" >
<ul class="ul_r4hz_class" >
<li class="li_r4hz_class"> bb, bbb, bbbb, bbbb2, bbbb3 </li>
<li class="li_r4hz_class"> bbbb5, bbb6, bbb7, bbb8, </li>
</ul>
</div>
</div>
<div>
<input id="minus" value="-" type="submit" style="background-color:white;
float:right; font-size:6px;" onClick="hide_show_div('sid', 'minus', 'plus'
); return flase; ">
<input id="plus" value="+" type="submit" style="background-color:white;
float:right; font-size:6px;" onClick="show_hide_div('sid',
'minus','plus','div_r3_class' ); return flase; ">
</div>
<script language = "JavaScript">
function hide_show_div( hideid1, hideid2, showid1 ){
hideObjDiv( hideid1 ) ;
hideObjDiv( hideid2 ) ;
showObjDiv( showid1 ) ;
}
function show_hide_div( showdivid1, showid2, hideid1, newclass ){
hideObjDiv( hideid1 ) ;
showObjDiv( showid2 ) ;
showObjDiv( showdivid1 ) ;
}
function hideObjDiv(obj) {
if (document.getElementById) {
document.getElementById(obj).style.visibility = 'hidden';
document.getElementById(obj).style.display = 'none';
}
}
function showObjDiv(obj) {
if (document.getElementById) {
document.getElementById(obj).style.visibility = 'visible';
document.getElementById(obj).style.display = 'inline';
}
}
</script>

Thursday, 19 September 2013

Mozilla Persona / BrowserID as auth method for a REST api

Mozilla Persona / BrowserID as auth method for a REST api

I would like to use Persona as auth method for our website based on a
whose functionalities are based on a REST API. In a traditional method we
send the informations about user at each request - username and password -
with the connection secured with SSL.
We would achieve the same, but using Mozilla Persona to allow people to
the initial login instead, how can this be achieved?

JTextArea two lines limit

JTextArea two lines limit

I have a String of certain length and a JTextArea of specific width.
What I need is a way to trim the string so it would fit to exactly two
rows of JTextArea.
Kinda like this:
String:
"This is a string that surely would not fit the JTextArea"
JTextArea:
This is a string that
surely would not fit t...
It wraps at the word on the first line, but cuts at the second so max
number of characters would fit followed by three dots.
I could get a DocumentListener and remove a char by char when line number
limit is exceded, and adding dots/removing additional characters when line
number criteria is met...
But this would be used a lot of times in a lot of places, so I'm looking
for a maybe faster solution, if there is one...
Font is unfortunately not monospaced.

CGContextDrawPDFPage crashed and does not free memory

CGContextDrawPDFPage crashed and does not free memory

i have a problem with my pdf generation in iOS.
I am loading a pdf and generating a list (tableview) of thubmnails. Each
thumbnail will be generated if it is displayed (tableView:-
(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath).
The generation of an thumbnail will be done by a NSBlockOperation in a
NSOperationQueue with max 1 concurrent operation.
Sometimes the app crashes with exc_bad_access at CGContextDrawPDFPage.
Additionally the CGContextDrawPDFPage does not release the used memory and
caches it. I try to clear the cache by reopening the pdf with
CGPDFDocumentCreateWithURL which is wrapped in a NSObject.
Generation:
- (void)loadThumbnailsFromPage:(int)fromPage toPage:(int)toPage {
if (self.thumbnailOperationQueue == nil) {
self.thumbnailOperationQueue = [NSOperationQueue new];
self.thumbnailOperationQueue.maxConcurrentOperationCount = 1;
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self
selector:@selector(test) userInfo:nil repeats:YES];
} else {
// [self.thumbnailOperationQueue cancelAllOperations];
}
NSBlockOperation *blockOperation = [NSBlockOperation
blockOperationWithBlock:^{
PDFWrapper *pdf = [[PDFWrapper alloc] initWithPDFURL:self.pdfURL];
int pages = CGPDFDocumentGetNumberOfPages(pdf.pdfRef);
int from = fromPage;
int to = toPage;
if (from > to) {
to = from;
}
if (from > pages) {
from = pages;
}
if (to > pages) {
to = pages;
}
for (int i = fromPage; i <= toPage; i++) {
NSString *imageName = [NSString
stringWithFormat:@"%d.thumb.png", i];
NSString *fullPathToFile = [self.thumbDocPath
stringByAppendingPathComponent:imageName];
if (![[NSFileManager defaultManager]
fileExistsAtPath:fullPathToFile]) {
[ThumbnailLoader loadThumbnailForPage:i pdf:pdf
filePath:fullPathToFile];
}
if (self.didLoadPage != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
self.didLoadPage(i, fullPathToFile);
});
}
}
[pdf close];
pdf = nil;
}];
[self.thumbnailOperationQueue addOperation:blockOperation];
}
(there some testing stuff within so ignore it.
[PDFWrapper close] releases the CGPDFDocumentRef and the initialization
opens it.
The thumbnail generation itself
+ (void)loadThumbnailForPage:(int)pageIndex pdf:(PDFWrapper *)pdf
filePath:(NSString *)filePath {
@synchronized(pdf) {
CGPDFPageRef page = CGPDFDocumentGetPage(pdf.pdfRef, pageIndex);
if (!page) {
return;
}
CGSize thumbSize = CGSizeMake(THUMB_WIDTH, THUMB_HEIGHT);
CGRect thumbRect = CGRectMake(0, 0, THUMB_WIDTH, THUMB_HEIGHT);
UIGraphicsBeginImageContext(thumbSize);
CGContextRef context = UIGraphicsGetCurrentContext();
//prevent releasing while drawing
CGPDFPageRetain(page);
CGContextRetain(context);
CGContextTranslateCTM(context, 0.0, thumbSize.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextFillRect(context, thumbRect);
CGAffineTransform pdfTransform =
CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, thumbRect, 0,
true);
CGContextConcatCTM(context, pdfTransform);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
CGContextDrawPDFPage(context, page);
CGContextRelease(context);
CGPDFPageRelease(page);
UIImage *thumbnailImage =
UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
@autoreleasepool {
NSData *imageData = UIImageJPEGRepresentation(thumbnailImage,
30);
if (imageData) {
NSLog(@"WROTE TO:%@", filePath);
if (![imageData writeToFile:filePath atomically:NO])
NSLog(@"ERROR: Thumb Didnt Save"); //COMMENT OUT TO
DISABLE WRITE
}
imageData = nil;
thumbnailImage = nil;
}
}
}
I hope anyone can help me.
Best,
Richard

Scala.NotImplementedError: an implementation is missing?

Scala.NotImplementedError: an implementation is missing?

Here is my code:
package example
object Lists {
def max(xs: List[Int]): Int = {
if(xs.isEmpty){
throw new java.util.NoSuchElementException()
}
else {
max(xs.tail)
}
}
}
When i run it in sbt console:
scala> import example.Lists._
scala> max(List(1,3,2))
I have the following error:
Scala.NotImplementedError: an implementation is missing
How can I fix that?
Thanks.

Moving mongodb database to new location

Moving mongodb database to new location

When initially setting up mongodb I must've done something wrong as my
data isn't being written to /data/db as I intended. I have no idea where
my data is being stored (doing a search in finder for the db naem returns
no results and I can't find in the docs how I can find out the current
directory used). How can I safely point mongodb to use my desired
directory while making sure it moves all my existing data to the new
location?

Does OpenShift Online provide an API to manage apps?

Does OpenShift Online provide an API to manage apps?

Can't see from the doc whether I can launch / manage apps on OpenShift
Online, via a standard Java API (like Cloudbees has)?

Python PY files does not reflect changes

Python PY files does not reflect changes

I have experience with PHP but now have to manage a python application. It
is already developed and running on live server. On live server we have
beta.domain.com as well. which has its own copy of same source, other than
the main domain application.
Now, when we print something within template it effects but before that,
following MVC, if we try to print or use sys.exit() in "manage.py" or
later imported "settings.py" or then "views.py", nothing effects these
files at all. After any change in just mentioned files, Website still
renders everything and display related template.
Another thing that if even we remove "return
render_to_response('home.html', RequestContext(request, context))" inside
the "views.py" for testing, nothing effects and website still gets
rendered with template.
Do I need to think that if website code is already hosted then in order to
have changes to reflect new one in the code in any file (.py), needs to be
reinitialized by executing any project related file?
I am not sure how python code needs to be updated at all, any quick help
is much appreciated.

Wednesday, 18 September 2013

how to set view on list view for calander

how to set view on list view for calander

public class DayActivity extends Activity
{
public Calendar calendar;
public Calendar date;
TextView title_day ;
TextView title_date;
String day;
public CalendarAdapter adapter;
boolean leapYear;
int month;
int year;
int daysInMonth;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
calendar = Calendar.getInstance();
date=Calendar.getInstance();
title_day = (TextView)findViewById(R.id.title_day);
getdayname();
title_day.setText(day+",");
title_date = (TextView) findViewById(R.id.title_dateformat);
title_date.setText(android.text.format.DateFormat.format("dd MMM
yyyy", calendar));
final TextView previous = (TextView) findViewById(R.id.previous_day);
TextView next = (TextView) findViewById(R.id.next_day);
ListView oListView= (ListView)findViewById(R.id.listlayout);
oListView.setAdapter(new TextRepeatAdapter(this));
previous.setOnClickListener(new OnClickListener()
{ @Override
public void onClick(View v)
{ if(calendar.get(Calendar.DAY_OF_MONTH)==
calendar.getActualMinimum(Calendar.DAY_OF_MONTH))
{ month=(calendar.get(Calendar.MONTH));
year=calendar.get(Calendar.YEAR);
daysInMonth=getDaysInMonth(month,year);
calendar.set((calendar.get(Calendar.YEAR)),calendar.get(Calendar.MONTH)-1,daysInMonth);
if(calendar.get(Calendar.MONTH)-1== -2) {
calendar.set((calendar.get(Calendar.YEAR)-1),calendar.getActualMaximum(Calendar.MONTH),1);
} }
else {
calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)-1);
}
getdayname();
title_day.setText(day+",");
title_date.setText(android.text.format.DateFormat.format("dd MMM
yyyy", calendar));
//refreshCalendar();
} private int getDaysInMonth(int mnth, int yr)
{ // TODO Auto-generated method stub
int daysInMnth;
int leapYearReminder=yr%4;
if(leapYearReminder==0)
{ leapYear=true; }
else { leapYear=false; }
//Value of mnth for Apr=4,june=6,sep=9,nov=11 if (mnth== 4 || mnth ==
6 || mnth == 9 || mnth == 11)
{ daysInMnth = 30; }
//Value of mnth for feb=1 else if (mnth == 2)
{ daysInMnth = (leapYear) ? 29 : 28; } // Value of mnth for
Jan=1,Mar=3,May=5,july=7,Aug=8,oct=10, Dec=12
else
{ daysInMnth = 31; } return daysInMnth; } });
next.setOnClickListener(new OnClickListener() { @Override public void
onClick(View v) { if(calendar.get(Calendar.DAY_OF_MONTH)==
calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) {
calendar.set((calendar.get(Calendar.YEAR)),calendar.get(Calendar.MONTH)+1,1);
if(calendar.get(Calendar.MONTH)+1== 13) {
calendar.set((calendar.get(Calendar.YEAR)+1),calendar.getActualMinimum(Calendar.MONTH),1);
} } else
{
calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);
} //refreshCalendar(); getdayname();
title_day.setText(day+",");
title_date.setText(android.text.format.DateFormat.format("dd MMM
yyyy", calendar)); } });
}
private void getdayname()
{ int dayint=calendar.get(Calendar.DAY_OF_WEEK);
switch(dayint)
{ case 1: day="SUNDAY";
break; case 2: day="MONDAY";
break; case 3: day="TUESDAY";
break; case 4: day="WEDNESDAY";
break; case 5: day="THURSDAY";
break; case 6: day="FRIDAY";
break; case 7: day="SATURDAY";
break; } } }
This is my
TextRepeatAdapter class public class TextRepeatAdapter implements
ListAdapter {
Context mContext;
LinearLayout eventsLL;
private static int HOURS_PER_DAY = 24;
public TextRepeatAdapter(Context c)
{ mContext=c;
}
@Override
public int getCount()
{ // TODO Auto-generated method stub
return HOURS_PER_DAY; }
@Override
public Object getItem(int position)
{ // TODO Auto-generated method stub
return null; }
@Override
public long getItemId(int position)
{ // TODO Auto-generated method stub
return 0; }
@Override
public int getItemViewType(int position)
{ // TODO Auto-generated method stub
return 0; }
@Override
public View getView(int position, View convertView, ViewGroup parent)
{ // TODO Auto-generated method stub
LayoutInflater inflater =
(LayoutInflater)mContext.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View oView = (View) inflater.inflate(R.layout.repeat, null,false);
TextView hourTV=(TextView)oView.findViewById(R.id.hourTV);
TextView amTV=(TextView)oView.findViewById(R.id.amTV);
hourTV.setTextColor(Color.BLUE);
amTV.setTextColor(Color.BLUE);
hourTV.setText(String.valueOf((position+9)%24));
String Mode="am";
if(((position>=0)&&(position<=2))||((position>=15)&&(position<=23)))
{ Mode="am";
amTV.setText(Mode);
} else
{ Mode="pm"; amTV.setText(Mode); }
oView.setOnClickListener(mBuyButtonClickListener);
return oView;
}
@Override
public int getViewTypeCount()
{ // TODO Auto-generated method stub
return 1; }
@Override
public boolean hasStableIds() { // TODO Auto-generated method stub
return false; }
@Override
public boolean isEmpty() { // TODO Auto-generated method stub
return false; }
@Override
public void registerDataSetObserver(DataSetObserver observer)
{ // TODO Auto-generated method stub }
@Override
public void unregisterDataSetObserver(DataSetObserver observer)
{ // TODO Auto-generated method stub }
@Override
public boolean areAllItemsEnabled()
{ // TODO Auto-generated method stub
return false;
}
@Override
public boolean isEnabled(int arg0)
{ // TODO Auto-generated method stub return false; } }

Can TM decide the change of contents on the tape?

Can TM decide the change of contents on the tape?

I don't even know that TM can recognize this problem. I've been thinking
for all day but have no idea to prove this. T T Dose anyone can help ?
Please...
Here is the problem
"Given a Turing machine with input x, if its tape length is infinite, do
we know whether or not some contents on the tape are altered after the
machine has started? State your reasons."

How can I write this LINQ query as a Lambda expression?

How can I write this LINQ query as a Lambda expression?

Here's my query expression:
ddCourse.DataSource = (from c in db.COURSE_MASTERs
orderby c.COURSE_TITLE
select new { c.COURSE_ID, c.COURSE_TITLE }).ToList();
Just for the sake of knowledge, I'd like to know how to write this as a
Lambda expression. Here is what I have so far:
ddCourse.DataSource = db.COURSE_MASTERs
.OrderBy(c => c.COURSE_TITLE)
.Select(c => {c.COURSE_ID, c.COURSE_TITLE})
.ToList();
Of course, what I have is wrong so I'm hoping that someone can help point
me in the right direction? Again, the only reason I'm doing this is for
the sake of knowledge.

EXC_BAD_ACCESS code=1 to EXC_BREAKPOINT in main.m

EXC_BAD_ACCESS code=1 to EXC_BREAKPOINT in main.m

I've been searching the web (mostly this site) for answers to this
question. I have found some relative questions, all of which didn't work
for me or were not answered themselves. I am writing a simple pong
program, where right now I have the main load screen with a button that
brings you to the game screen. On the game screen is a button that is
meant to start the ball moving by using an NSTimer.
GameComputerVSPlayer.h
#import <UIKit/UIKit.h>
int x;
int y;
@interface GameComputerVSPlayer : UIViewController {
IBOutlet UIImageView *backcolor;
IBOutlet UIImageView *ball;
IBOutlet UIImageView *computerPaddleVert;
IBOutlet UIImageView *computerPaddle;
IBOutlet UIImageView *playerPaddleVert;
IBOutlet UIImageView *playerPaddle;
IBOutlet UIImageView *cornerTL;
IBOutlet UIImageView *cornerTR;
IBOutlet UIImageView *cornerBL;
IBOutlet UIImageView *cornerBR;
IBOutlet UIButton *startButton;
NSTimer *timer;
}
@property (nonatomic, retain) UIImageView *ball;
@property (nonatomic, retain) UIImageView *computerPaddleVert;
@property (nonatomic, retain) UIImageView *computerPaddle;
@property (nonatomic, retain) UIImageView *playerPaddleVert;
@property (nonatomic, retain) UIImageView *playerPaddle;
-(IBAction)nextPoint:(id)sender;
-(void)ballMovement;
@end
GameComputerVSPlayer.m
#import "GameComputerVSPlayer.h"
#import "ViewController.h"
@interface GameComputerVSPlayer ()
@end
@implementation GameComputerVSPlayer
@synthesize ball, playerPaddleVert, playerPaddle, computerPaddleVert,
computerPaddle;
-(void)ballMovement {
ball.center = CGPointMake(ball.center.x + x, ball.center.y + y);
}
-(IBAction)nextPoint:(id)sender{
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self
selector:@selector(ballMovement) userInfo:nil repeats:YES];
x = arc4random()%9;
x = x - 5;
y = arc4random()%9;
y = y - 5;
if (y==0) {
y = 1;
}
if (x==0) {
x = 1;
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
I have also tried to use NSZombie as well, but that hadn't shown me
anything. Thanks in advance for your work!

How to write robust, large scale TCP server in python?

How to write robust, large scale TCP server in python?

I'm searching for a tutorial or more info on how to write robust TCP
server (with some custom app-protocol) in python that will be able to
maintain several connections to TCP clients.
Each TCP client will send some data to server and server will enter this
data in local mysql database. After some predefined period of inactivity,
server will close connection to each client.
Is there any simple example or documentation that I could start ? Any
frameworks for writing such type of web application that could let me
start quickly ?
Thanks in advance, regards, Bulek.

posting json object to rest web service through android client

posting json object to rest web service through android client

I think my android client is unable to send data to my web service, this
is my client code:
value1 = json_obj.getString("dbname");
value2 = json_obj.getString("dbuser");
value3 = json_obj.getString("dbpwd");
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("****/api/v1/user/");
post.setHeader("content-type", "application/json;
charset=UTF-8");
JSONObject dato = new JSONObject();
dato.put("dbname", value1);
dato.put("dbuser", value2);
dato.put("dbpwd", value3);
StringEntity entity = new StringEntity(dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());
and my web service's model for receiving the object is:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
public String getDBname() {
return dbName;
}
public void setDBname(String database) {
this.dbName = database;
}
public String getUserName() {
return dbUser;
}
public void setUserName(String username) {
this.dbUser = username;
}
public String getPass() {
return dbPwd;
}
public void setPass(String password) {
this.dbPwd = password;
}
public User() {
dbName = "";
dbUser = "";
dbPwd = "";
}
public User(String dbname, String dbuser, String dbpwd) {
this.dbName = dbname;
this.dbUser = dbuser;
this.dbPwd = dbpwd;
}
private String dbName;
private String dbUser;
private String dbPwd;
}
@POST side is:
@Path("/v1/user/")
public class V1_user {
@Context
UriInfo uriInfo;
@Context
Request request;
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public User postPerson(
MultivaluedMap<String, String> personParams
) {
String dbName = personParams.getFirst(DB_NAME);
String userName = personParams.getFirst(USER_NAME);
String password = personParams.getFirst(PASSWORD);
System.out.println("Storing posted " + dbName + " " + userName + " "
+ password);
user.setDBname(dbName);
user.setUserName(userName);
user.setPass(password);
System.out.println("person info: " + user.getDBname() + " " +
user.getUserName() + " " + user.getPass());
return user;
}
}
The web service side works on another android client, but this one I
couldn't get working, what am I doing wrong? Why doesn't the web service
print the result to the console? Thanks in advance.

reference type and primitive type like in JavaScript but in PHP

reference type and primitive type like in JavaScript but in PHP

You know how in javascript it's
var firstVar = 'hello'; // 'hello'
var secondVar = firstVar; // 'hello'
firstVar = 'hi'; // 'hi'
secondVar // 'hello'
Can I do this in php or not?

Tuesday, 17 September 2013

CAS proxy ticket

CAS proxy ticket

In what cases the statement below might return null?
assertion.getPrincipal().getProxyTicketFor("myURL")
assertion is of org.jasig.cas.client.validation.Assertion type.
P.S. The reason behid this question is that we have read documentation and
followed instructions. The line above works for some of us, and same thing
doesn't work for me. Security Certificates were suspected at first. I
fixed them, but still it does not work.

Unknown error when printing solutions in for statment

Unknown error when printing solutions in for statment

I'm fairly new to java and I'm attempting to create a simple java program
that checks for arithmetic and geometric sequences and lists the desired
amount of terms from the sequence out. Everything in the program works
properly until the printing of the next terms in the for statement occurs.
There is no errors, and I can't find anything wrong. Any help is
appreciated.
if(num2-num1 == num3-num2){
d = num2-num1;
System.out.println("This is a arithmetic sequence.\nCommon Difference
= " + d);
System.out.println("How many terms of this sequence would you like?");
int a = scanner.nextInt();
for(int i = 1; i >= a; i++){
num3 += d;
System.out.println(num3);
}
suc = 1;
}

How to calculate average time to bed

How to calculate average time to bed

So for e.g. if I go to bed Monday: 11:59 pm Tuesday: 12:00 am the average
is 11:59:30 am
how can I get it to be 11:59:30 pm ?
using an algorithm?

XPath reference

XPath reference

I don't know the proper terminology for what I'm looking for, but what I
am looking for is a complete reference the statements that can go between
the double quotes, things like *, node(), @*, and all the ones listed here
plus any others that exist.
<xsl:template match="*">
The answer I linked to provides some detail, but not enough. For instance,
that answer says "can be applied to any element" about the example I gave
above, but what is considered an "element" in Xpath? What does node()
include? What statements include attributes? etc.
I have searched the references here and here and I'm slowly making my way
through this book, but I'm not seeing the info I want, which is basically
a consolidated (and hopefully exhaustive) list of statements and what they
mean. Does such a list exist and if so where is it? Free is nice but not
necessary.

JSP/EL output current URL

JSP/EL output current URL

I'm awful at Java. I've tried looking for this but it is surprisingly hard
to find an answer to despite how easy I'm sure it is.
My URL is: https://www.example.com/path/to/file.jsp
I just need to print it. That simple. Something like:
<a
href="http://www.foo.com?TARGET=https://www.example.com/path/to/file.jsp">Go</a>
I've tried...
(request.getRequestURL()).toString();
...but it gives http://www.example.com/path/to/file.jsp - i need HTTPS
I've tried...
<c:set var="req" value="${pageContext.request}" />
<c:set var="targetURL"
value="${req.scheme}://${req.serverName}${req.contextPath}" />
...but it gives https://www.example.com/
What's in the address bar is and always will be correct. I just need it to
have the proper protocol and full path.

Sunday, 15 September 2013

How to make iframe load on top of page?

How to make iframe load on top of page?

How do I create an iframe over the top of my page... For example this
website http://todoist.com/ when you click "get started" loads a page up
on top of the main webpage. The rest of the webpage greys out as you focus
on the create account frame. What code makes this possible?

How to upload and store image together with text field in datastore? google app engine + java servlet

How to upload and store image together with text field in datastore?
google app engine + java servlet

My form has text field and file field. When I upload, only image is stored
inside the datastore. Username is blank. I uses JDO. When I tried to do
video.setUsername("username" ); in the servlet. The Username field in
datastore is still blank. Any idea how to solve this issue?
Here is my jsp code.
<form method="post" enctype="multipart/form-data" action="/Upload">
Username : <input type="text" id="username" name="username"/> <br/>
<input type="file" id="uploadImg" name="uploadImg" accept="image/gif,
image/jpeg"></input>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
Here is my servlet code.
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Video video = new Video();
try {
List<FileItem> items = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input
// type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
video.setUsername(fieldvalue);
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
byte[] bytes = IOUtils.toByteArray(filecontent);
video.setVideo(bytes);
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
// Store the image in App Engine's datastore
pm.makePersistent(video);
} finally {
pm.close();
}

Automatically download a list of images and name them

Automatically download a list of images and name them

I have a xls/csv list of images:
Name image url test.jpg http://test.com/232dd.jpg test2.jpg
http://test.com/2390j.jpg
I have about 200 of these...is there a way to download the list and name
them as identified in the xls file?
Thanks!

Communication and using Methods between Header and CPP files in C++

Communication and using Methods between Header and CPP files in C++

I've got a header file named ArrayLinearList.h and a Main.cpp file for a
project I'm working on. I declare and initialize all methods and
constructors in the Header file for use in my main method. I'm confused as
to the communication between these files, specifically when using
templates. Why don't any of my three method calls in main.cpp work? They
all say that the methods or classes are not delcared. My code is below.
ArrayLinearList.h
//Header file
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
#include <ostream>
#include <string>
#include <list>
using namespace std;
template<class T>
class linearList
{
public:
virtual ~linearList() {};
virtual bool empty() const = 0;
virtual int size() const = 0;
virtual T& get(int theIndex) const = 0;
virtual int indexOf(const T& theElement)const = 0;
virtual void erase(int theIndex) = 0;
virtual void insert(int theIndex, const T& theElement) = 0;
virtual void output(ostream& out) const = 0;
};
template<class T>
class arrayList : public linearList<T>
{
public:
arrayList(int initialCapacity=10);
arrayList(const arrayList<T>&);
~arrayList() {delete[] element;}
bool empty() const {return listSize==0;}
int size() const {return listSize;}
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(ostream& out) const;
int capacity() const {return arrayLength;}
void changeLength1D(T*&a, int oldLength, int newLength);
protected:
void checkIndex(int theIndex) const;
//Throw error if invalid Brett
T* element; //One dimensional array
int arrayLength; //Max capacity of array
int listSize; //Current # of elements in array
T* temp;
int number;
};
//First Constructor
template <class T>
arrayList<T>::arrayList(int initialCapacity)
{
//Constructor
if (initialCapacity<1)
{
// throw error Brett
}
arrayLength=initialCapacity;
element = new T[arrayLength];
listSize=0;
}
//Copy Constructor
template <class T>
arrayList<T>::arrayList(const arrayList<T>& theList)
{
arrayLength=theList.arrayLength;
listSize=theList.listSize;
element=new T[arrayLength];
copy(theList.element,theList.element+listSize,element);
}
template <class T>
void arrayList<T>::checkIndex(int theIndex) const
{
//Check that index is between 0 and listsize-1
if(theIndex<0 || theIndex >=listSize)
{
//Brett
}
}
template <class T>
T& arrayList<T>::get(int theIndex) const
{
//Return element at index, throw exception if illegal
checkIndex(theIndex);
return element[theIndex];
}
template <class T>
int arrayList<T>::indexOf(const T& theElement) const
{
//Return index of first occurence of theElement
int theIndex=(int) (find(element, element+listSize,
theElement)-element);
//Check if it was found
if(theIndex==listSize)
return -1;
else return theIndex;
}
template <class T>
void arrayList<T>::erase(int theIndex)
{
//Delete element at theIndex
checkIndex(theIndex);
//If a valid index, shift elements with higher index
copy(element+theIndex+1, element+listSize, element+theIndex);
element[--listSize].~T; //Destructor
}
template <class T>
void arrayList<T>::insert(int theIndex, const T& theElement)
{
//Insert the eleemnt at valid index
checkIndex(theIndex);
//Check for space
if(listSize==arrayLength)
{
//no space, double the capacity
changeLength1D(element, arrayLength, 2*arrayLength);
arrayLength *=2;
}
//shift elements right one position
copy_backward(element +theIndex, element+listSize,
element+listSize+1);
element[theIndex] = theElement;
listSize++;
}
template <class T>
void arrayList<T>::changeLength1D (T*&a, int oldLength, int newLength)
{
if (newLength<0)
//Brett
T* temp = new T[newLength];
int number = min(oldLength,newLength);
copy(a, a+number, temp);
delete[] a;
a=temp;
}
/* template<class T>
void arrayList<T>::output(ostream& out) const
{
//Put the list into the stream out
copy(element, element+listSize,ostream_iterator<T>(out," "));
}
template <class T>
{
ostream& operator<<(ostream& out, const arrayList<T>& x)
{x.output(out); return out;}
}
*/
Main.cpp
//Main.cpp file
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
#include "ArrayLinearList.h"
using namespace std;
int main()
{
ArrayLinearList::arrayList(); //Call constructor?
ArrayLinearList:: checkIndex(3); //Check index of constructor-made
list
arrayList::arrayList();
arrayList::erase(3);
}
The errors I am getting:
g++ main.cpp -o run
main.cpp: In function 'int main()':
main.cpp:22: error: 'ArrayLinearList' has not been declared
main.cpp:23: error: 'ArrayLinearList' has not been declared
main.cpp:24: error: 'template<class T> class arrayList' used without
template parameters
main.cpp:25: error: 'template<class T> class arrayList' used without
template parameters
Any help or pointers will be much appreciated
-Brett

jQuery json value is not being appended

jQuery json value is not being appended

This is my code:
success: function (data) {
var jsonData = $.parseJSON(data);
console.log("done");
$.each(jsonData, function(key, value) {
if (value !== "") { console.log("working on " +
"#"+key+".div")
$("#"+key+".div").append("<pre>"+value+"</pre>");
}
});
}
As you see, this is a snippet of the success callback function.
Everything works fine up to the point where value should be appended to
the selector I provide. But for some reason, nothing is added.
console.log("working on " + "#"+key+".div")
Is printed, so I know the if statement is not the issue.
I believe the error lays with this line:
$("#"+key+".div").append("<pre>"+value+"</pre>");
But I can't tell what exactly I am missing.

CoSign API: Sending SOAP from Python client generated by suds

CoSign API: Sending SOAP from Python client generated by suds

I need to access the signing appliance from Python. To this end, using
suds, I generated a Python client from the WSDL at
https://cosigndemo.arx.com:8080/sapiws/dss.asmx?wsdl . I then used the
generated client to build a simple signature request which more or less
does the same as shown in the Java example provided by ARX (only, I'm
asking for an invisible signature). The problem is that when I send the
request to the demo appliance, here's what I receive in return:
(DssSignResult){
Result =
(Result){
ResultMajor =
"urn:oasis:names:tc:dss:1.0:resultmajor:ResponderError"
ResultMinor = "urn:oasis:names:tc:dss:1.0:resultminor:GeneralError"
ResultMessage =
(ResultMessage){
value = "Exception occured"
_lang = "en"
}
}
}
Here's the Python code I wrote:
from suds.client import Client
from suds.plugin import MessagePlugin
from suds.sax.attribute import Attribute
import logging
class MyPlugin(MessagePlugin):
def marshalled(self, context):
foo =
context.envelope.getChild('ns2:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:InputDocuments').getChild('ns1:Document')
foo[0].attributes.append(Attribute('MimeType', 'application/pdf'))
print context.envelope
url = 'https://cosigndemo.arx.com:8080/sapiws/dss.asmx?wsdl'
client = Client(url, plugins=[MyPlugin()])
cid = client.factory.create("ns4:ClaimedIdentity")
cid.Name = "John Miller"
cid.SupportingInfo.LogonPassword = "12345678"
sigReq = client.factory.create("ns4:RequestBaseType")
sigReq._RequestID = "DummyRequestId"
sigReq.OptionalInputs.ClaimedIdentity = cid
sigReq.OptionalInputs.SignatureType="http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign"
sigReq.OptionalInputs.SAPISigFieldSettings._Name = "SigField"
sigReq.OptionalInputs.SAPISigFieldSettings._Invisible = "true"
sigReq.OptionalInputs.SAPISigFieldSettings._DependencyMode = "Independent"
sigReq.OptionalInputs.SAPISigFieldSettings._SignatureType = "Digital"
sigReq.OptionalInputs.SAPISigFieldSettings._EmptyFieldLabel = ""
sigReq.OptionalInputs.SAPISigFieldSettings._Page = "1"
sigReq.OptionalInputs.ReturnPDFTailOnly = "true"
sigReq.OptionalInputs.IncludeObject=None
sigReq.OptionalInputs.SignaturePlacement=None
doc = client.factory.create("ns4:DocumentType")
doc.Base64Data = open("/Users/mar/CoSignWSDL/factures-comptat217.pdf",
"rb").read().encode("base64")
sigReq.InputDocuments.Document = doc
result = client.service.DssSign(sigReq)
print result
And here's the SOAP that (at least I think) it is sending to the appliance:
<SOAP-ENV:Envelope xmlns:ns3="http://arx.com/SAPIWS/DSS/1.0"
xmlns:ns0="http://arx.com/SAPIWS/DSS/1.0/"
xmlns:ns1="urn:oasis:names:tc:dss:1.0:core:schema"
xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns2:Body>
<ns0:DssSign>
<ns0:SignRequest RequestID="DummyRequestId">
<ns1:OptionalInputs>
<ns1:ClaimedIdentity>
<ns1:Name>John Miller</ns1:Name>
<ns1:SupportingInfo>
<ns3:LogonPassword>12345678</ns3:LogonPassword>
</ns1:SupportingInfo>
</ns1:ClaimedIdentity>
<ns1:SignatureType>http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign</ns1:SignatureType>
<ns1:SAPISigFieldSettings Name="SigField"
DependencyMode="Independent" SignatureType="Digital"
Page="1" Invisible="true"/>
<ns1:ReturnPDFTailOnly>true</ns1:ReturnPDFTailOnly>
</ns1:OptionalInputs>
<ns1:InputDocuments>
<ns1:Document>
<ns1:Base64Data
MimeType="application/pdf">...</ns1:Base64Data>
</ns1:Document>
</ns1:InputDocuments>
</ns0:SignRequest>
</ns0:DssSign>
</ns2:Body>
</SOAP-ENV:Envelope>
Note that I replaced the (very long) Base64Data content with "..." here
for space reasons. Why is it not working?
Update Problem solved thanks to the answer. Here is the working code that
adds a sig to a PDF:
from suds.client import Client
from suds.plugin import MessagePlugin
from suds.sax.attribute import Attribute
from suds.bindings import binding
import logging
import xml.dom.minidom as minidom
import base64
class MyPlugin(MessagePlugin):
def marshalled(self, context):
documentNode =
context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:InputDocuments').getChild('ns1:Document')
documentNode[0].attributes.append(Attribute('MimeType',
'application/pdf'))
SAPISigFieldSettingsNode =
context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:OptionalInputs').getChild('ns1:SAPISigFieldSettings')
SAPISigFieldSettingsNode.setPrefix('ns2')
ReturnPDFTailOnlyNode =
context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest').getChild('ns1:OptionalInputs').getChild('ns1:ReturnPDFTailOnly')
ReturnPDFTailOnlyNode.setPrefix('ns2')
signRequestNode =
context.envelope.getChild('ns3:Body').getChild('ns0:DssSign').getChild('ns0:SignRequest')
signRequestNode.setPrefix('ns1')
binding.envns = ('SOAP-ENV', 'http://www.w3.org/2003/05/soap-envelope')
url = 'https://cosigndemo.arx.com:8080/sapiws/dss.asmx?wsdl'
client = Client(url, plugins=[MyPlugin()])
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.plugin').setLevel(logging.DEBUG)
cid = client.factory.create("ns4:ClaimedIdentity")
cid.Name = "John Miller"
cid.SupportingInfo.LogonPassword = "12345678"
sigReq = client.factory.create("ns4:RequestBaseType")
sigReq._RequestID = "DummyRequestId"
sigReq.OptionalInputs.ClaimedIdentity = cid
sigReq.OptionalInputs.SignatureType="http://arx.com/SAPIWS/DSS/1.0/signature-field-create-sign"
sigReq.OptionalInputs.SAPISigFieldSettings._Name = "SigField"
sigReq.OptionalInputs.SAPISigFieldSettings._Invisible = "true"
sigReq.OptionalInputs.SAPISigFieldSettings._DependencyMode = "Independent"
sigReq.OptionalInputs.SAPISigFieldSettings._SignatureType = "Digital"
sigReq.OptionalInputs.SAPISigFieldSettings._EmptyFieldLabel = ""
sigReq.OptionalInputs.SAPISigFieldSettings._Page = "1"
sigReq.OptionalInputs.ReturnPDFTailOnly = "true"
sigReq.OptionalInputs.IncludeObject=None
sigReq.OptionalInputs.SignaturePlacement=None
doc = client.factory.create("ns4:DocumentType")
f = open('/Users/mar/CoSignWSDL/factures-comptat217.pdf', 'r+b')
doc.Base64Data = f.read().encode("base64")
sigReq.InputDocuments.Document = doc
result = client.service.DssSign(sigReq)
signature = base64.b64decode(result.SignatureObject.Base64Signature.value)
f.seek(0, 2) #go to the end of the file
f.write(signature)
f.close()

How to capture image directly from my apk and post it to a url as file upload

How to capture image directly from my apk and post it to a url as file upload

I am developing apk file that contains a view and a button. 1 the view
will show async video view from camera. 2 on button click event--> my apk
take picture from camera directly and than post it as file upload to
dedicated url. (I don't want to get image via camera app). please help me
how to do and which libs should be used.

How can SQL store 9 digits in 4 bytes?

How can SQL store 9 digits in 4 bytes?

MySQL 5.0 Reference, 11.2. Data Type Storage Requirements:
As of MySQL 5.0.3, values for DECIMAL columns are represented using a
binary format that packs nine decimal (base 10) digits into four bytes.
Storage for the integer and fractional parts of each value are determined
separately. Each multiple of nine digits requires four bytes, and the
"leftover" digits require some fraction of four bytes. The storage
required for excess digits is given by the following table.
I can imagine storing 8 BCD digits in 4 bytes (each in 4 bits), so the
result would be (MSB first)
112 => 0x01 0x12
148,225 => 0x14 0x82 0x25
12,310,789 => 0x12 0x31 0x07 0x89
In other words, I know how to store 10 possible values (0 - 9) in each 4
bits.
How does MySQL store 9 decimal digits in 4 bytes?

Saturday, 14 September 2013

Rails Polymorphic Children

Rails Polymorphic Children

I've seen many good examples of a child model (say, a 'Comment') belonging
to multiple parent models ('Post', 'Product', etc). Here is one, for
example: http://railscasts.com/episodes/154-polymorphic-association.
I am looking to accomplish the opposite however, where a parent has
multiple polymorphic children. A classic example would be an
'ActivityFeed' that has multiple types of children ('Photo', 'Comment',
etc).
How would one go about modeling this relationship in Rails?

Can MongoDB MapReduce functions behave like CouchDB views?

Can MongoDB MapReduce functions behave like CouchDB views?

The nice thing about CouchDB is that the view results are updated
incrementally as the database changes. Is there a way to accomplish the
same thing with MongoDB? I've been unable to locate any specifics in the
documentation. Thanks

insert into DB and output blob images using Coldfusion 10

insert into DB and output blob images using Coldfusion 10

I have been working on a script that will allow users to asynchronously
upload images.
the script contains several segments of code and while most of it works
like a charm i've been experiencing issue while trying to convert
coldfusion image object to blob, pass it to another object (cfc component
method), insert values to DB using stored procedure and finaly output blob
images to see the result.
here is the testing code for particular segment i am having issues with,
the final one will be a bit more complex:
<cfimage source="#CFFILE.ServerDirectory#\#CFFILE.ServerFile#"
name="Image" overwrite="no">
<cfif ImageGetWidth(Image) lt 1024>
<cfset ArrayAppend(set.Errors,"you can not add image that's less
than 1024px wide")>
<cfelse>
<!---now resize image scale to fit (709px wide)--->
<cfset ImageSetAntialiasing(Image,"on")>
<cfset ImageScaleToFit(Image,709,"","highestPerformance")>
<!---now crop image if height is more than 350px--->
<cfif ImageGetHeight(Image) gt 350>
<cfif ImageGetHeight(Image) gt 350>
<cfset yPosition = (ImageGetHeight(Image) - 350) / 2>
<cfset ImageCrop(Image, 0, #yPosition#,
#ImageGetWidth(Image)#, 350)>
</cfif>
</cfif>
</cfif>
<cfif ArrayLen (set.Errors) is 0>
<cfset testAddImage = testImg.AddImage(finalImage=#ImageGetBlob(Image)#)>
</cfif>
need to admit that did not use much image functions with CF, hence I have
to learn a few tricks. anyway, as i can see this testing code apparently
works considering that all values are neatly added to the DB every time
the form has been submited and no CF nor client side errors are thrown. on
the other hand, although I read a lot about outputting blob I am pretty
much confused what's the best approach to achieve this with CF 10. that
said, should I use cfcontent, binaryEncode, to string or something else to
do it right.
I've also tried to set a binary object, cffile action = "readBinary"... as
well as set ImageNew , however as I could see everything was the same. is
there a difference between a binary and image object!?

Invalid number of arguments error in oracle

Invalid number of arguments error in oracle

Please let me know whether there is anything wrong in the insert statement
of the below query. It is giving me 'invalid number of arguments' errors
create or replace PROCEDURE adm_getMaxTableIdLimited
(
v_TableName IN VARCHAR2 DEFAULT NULL ,
v_TableIDColumnName IN VARCHAR2 DEFAULT NULL ,
v_MaxTableId OUT NUMBER
)
AS
v_Limit NUMBER(10,0);
v_SQLStatement VARCHAR2(255);
BEGIN
v_Limit:= 99999 ;
v_MaxTableId:= 0 ;
EXECUTE IMMEDIATE 'DROP TABLE TempResult';
EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE TempResult
(
Result NUMBER(10,0)
)';
v_SQLStatement:= 'Insert INTO TempResult(Result) SELECT max(' ||
v_TableIDColumnName || ')
FROM ' || v_TableName || ' WHERE ' || v_TableIDColumnName || ' <= ' ||
CAST(v_limit AS
VARCHAR2) || ';';
EXECUTE IMMEDIATE v_SQLStatement;
EXECUTE IMMEDIATE 'SELECT Result INTO v_MaxTableId FROM TempResult' ;
IF ( v_MaxTableId = v_Limit ) THEN
v_MaxTableId := -1 ;
ELSE
v_MaxTableId := v_MaxTableId + 1 ;
END IF;
EXECUTE IMMEDIATE ' TRUNCATE TABLE TempResult ';
END;

C++ MapVirtualFileEx - Creating multiple maps for faster access

C++ MapVirtualFileEx - Creating multiple maps for faster access

I am using MapVirtualFile to quickly access data from a file. However,
this is too slow. I guess it is because the file is huge (300 mb), and I
need to read from different locations (for example from the start of the
file, then from the end of the file).
I would like to know if somebody has any experience with creating multiple
maps from a file. Would that perhaps speed everything up?
I would then for example create 4 maps. One map that point to section 1 in
the file, the second map would point to section 2 in the file, the third
to section 3 of the file, etc.
Is that possible and would it make reading data faster?
My code is huge, and I would prefer thoughts about this before I invest 2
days just to find out that it does not solve my problem.
Thank you.

Java Swing JFileChooser append files to a JTextArea

Java Swing JFileChooser append files to a JTextArea

I have a browse button which opens a dialog where the user can view
directories and files. I am having some trouble appending the files the
user selects to a JTextArea. I am trying to do this so the user can select
multiple files at a time. The files eventually will be submitted to an
Oracle database.
The code I have used for the filechooser is here:
final JFileChooser fc = new JFileChooser();
JList list = new JList();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
File file = fc.getSelectedFile();
Can you please show me how to append the files to a JTextArea?
Thanks.

CSS3 Class-Selector NTH

CSS3 Class-Selector NTH

Have nine .projects ul class and i want select this explain in an image:
the middle three:
image here
[JSFIDDLE source][2]

Friday, 13 September 2013

searching images in preetyPhoto in Bloggger

searching images in preetyPhoto in Bloggger

I have implemented preetyPhoto gallery plugin
(http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/)
in my BLOG ( built in Blogger) for showing images.
Now I want to implement a SEARCH image functionality which will allow
Keyword search for the images and display it in a separate page/ window.
When clicked those images it will open again in prettyPhoto or so.
Is there any way this can be done in google BLOGGER. Any help/link will be
appreciated. The site is in building state.
Thanks and Warm Regards, Ari.

How is Summation(n) Theta(n^2) according to its formula but Theta(n) ij we just look at it as a single for loop?

How is Summation(n) Theta(n^2) according to its formula but Theta(n) ij we
just look at it as a single for loop?

Our prof and various materials say Summation(n) = (n) (n+1) /2 and hence
is theta(n^2). But intuitively, we just need one loop to find the sum of
first n terms! So, it has to be theta(n).I'm wondering what am I missing
here?!

Get Windows login password - Python

Get Windows login password - Python

How would I get the user password for the current account on Windows 7 in
python?
My vision of how it might work:
...
passwd = someWindowsApi.GetUserPassword()
print("Your current password is: " + passwd)
...
Then running the script would output something like this:
>python whatsmypassword.py
Your password is "password"
Seriously? You might as well not have a password. This incident will be
reported to the security fanatics foundation!
I am assuming that this script would have to be run as administrator, and
that is fine.

Facebook local currency

Facebook local currency

I'm changing a facebook game from using facebook credits to the new user
local currency model. Everything seems ok except the price that shows at
facebook pay dialog. It shows an old price that I had defined before.
After I change the price in the product file, I upload it and re-scraped
at [object debugger][1]
No errors returned and the price array turned out ok. { "amount": 3
"currency": "USD" }
My facebook account has set the payment currency in "EUR". So at the store
the price should be returned in euros by the facebook callback. And it
does, except for the value that comes out wrong in the facebook pay
dialog.
Accordingly to facebook exchange rates the price shoud be 2.29€ (3 US
dollars) instead it returns 1.99€
I don't know where this value is coming from. Do you have any idea?

Joomla-paypal How to show an agreement during between the selection of payment and redirection to paypal

Joomla-paypal How to show an agreement during between the selection of
payment and redirection to paypal

I have four membership package and each of them have two payment option
like 6 month and 12 month but as the laws forces to show an agreement
during an e-commerce I need to show the agrement after the user select the
type of duration and membership. How to know which package is selected and
wich option before redirection to paypal since the price will be in that
agreement. How can I solve this.

Thursday, 12 September 2013

Is it any way to automatically change value of chart after specific period without refreshing page?

Is it any way to automatically change value of chart after specific period
without refreshing page?

i am using open flash charts in my web but when i want to update chart's
value, i must refresh page. Is it any way to automatically change value of
chart after specific period without refreshing page?

can we find does dwg file contact xref or not using jdwglib

can we find does dwg file contact xref or not using jdwglib

How to find out that given dwg contains xref or not using jdwglib. And if
dwg contains xref how to find out xref path.
In autocad it has a utility's db xscanxref I need same function using java
is it possible?
Thanks

Hostname in Peer to Peer Wireless Networking using Socket between two Mobile devices

Hostname in Peer to Peer Wireless Networking using Socket between two
Mobile devices

My goal is set up a wireless peer to peer networking using socket. Server
and Client model. The code for Server is such.
Server.c
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0) error("ERROR writing to socket");
Client.c
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
return 0;
My questions are
1)What's the hostname I should set in the server.c in one of the Mobile
Phone? Or what should the hostname the client (another one of the Mobile
Phone) expect to see.
2)what should I use for port number for TCP communication between two
Mobile devices. ANything above 2000? Let say I have one iPhone and one
Android and I am trying to setup peer to peer wireless networking between
the two.