## Thursday, 3 October 2013

I'm trying to add in an additional variable to an if statement but I'm
having trouble. #status refers to the id of a select, and 'student' is one
of the options. The code works fine without the additional && statement.
What am I doing wrong?
var status
$("#status").change(function() { status =$(this).val();
});
$(function() {$('#fb').flexbox(jobroles, {
onSelect: function() {
if(this.value==="Multi therapist" &&
$('#status').val()==="Student"){$("#gdc").show();
}
else{
$("#gdc").hide(); } ## Wednesday, 2 October 2013 ### Search multine issue Search multine issue Hello i'm doing a search by multi lines Here is my table PEOPLE |id| |name| |lastname1| integer varchar(255) varchar(255) |1| |Michael New Rails| |Morote| |2| |Charles Chris Angels| |Flowers| |3| |Gabriel Francis James| |Owen| Here is my controller @people = Person.find(:all,:conditions => ["( name LIKE ? OR lastname1 LIKE ? OR (concat(name, \" \", lastname1) LIKE ? ) )" , "%#{params[:query]}%", "%#{params[:query]}%", "%#{params[:query]}%" ]) But is not working properly Someone can help me to search by whatever order in the name like me example? I will really appreciate help ### 3dsmax to Unity export animation 3dsmax to Unity export animation I'm having some difficulty exporting animated meshes from 3dsmax to Unity3d. I've succeeded in getting transform animations to export ok, for instance if something is moving. But animated parameters on something dont seem to export, for instance the height of box. Here are my fxb export settings I'm guessing they are losing this information when they are turned from boxes to meshes and i must back the animations on manually somehow but I have no idea how. ### Why I can't get complete data from using Google Map api? Why I can't get complete data from using Google Map api? I created a Python project to test google map api. I occured problem when I test the first API:Nearby Search Requests. I tried this url official doc provided: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere if I put this url on my browser,I'll get perfect data on browser. Then I did nothing but created a python module , here is the code : if __name__ == '__main__': import socket import ssl sock = ssl.wrap_socket(socket.socket()) sock.connect(('maps.googleapis.com', 443)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('maps.googleapis.com', 443)) sslSocket = socket.ssl(s) uri = 'GET /maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=MyKey HTTP/1.1\r\nHost:maps.googleapis.com\r\nContent-Type: application/json; charset=UTF-8\r\naccept-encoding:gzip,deflate,sdch\r\n\r\n' sslSocket.write(uri) data = sock.read() print 'going to connect...' print data s.close() UnfortunatelyCthe result on the console I got is like this F going to connect... HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Date: Wed, 02 Oct 2013 08:05:59 GMT Expires: Wed, 02 Oct 2013 08:10:59 GMT Cache-Control: public, max-age=300 Vary: Accept-Language Server: mafe X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN Alternate-Protocol: 443:quic Transfer-Encoding: chunked 560b { "debug_info" : [], "html_attributions" : [ "Listings by \u003ca href=\"http://www.yellowpages.com.au/\"\u003eYellow Pages\u003c/a\u003e"], "next_page_token" : "ClRHAAAA4lOaMlZcUjyndIqhBsHzyyU0nD5PHarmjgmnguj3morn7Em- ipqhSR33V__d0kjrL4PzAqY7y4TAK7Uj3XzWjhoUchLBcBs- TNFxWIvGst8SEArmj_T7_eDZWyr8UDGy5OEaFPFaK2yHDg7Kv2U3Obsy7opkQfEw", "results" : [ { "geometry" : { "location" : { "lat" : -33.8599827, "lng" : 151.2021282 }, "viewport" : { "northeast" : { "lat" : -33.8552584, "lng" : 151.2031401 }, this result is incomplete and I tried many times, the results are same. So, how to solve this problem? ## Tuesday, 1 October 2013 ### PostgreSQL crashes upon startup PostgreSQL crashes upon startup Every time I restart my Mac OS X Version 10.8.3. and open PSQL Version 9.2.4.3 (14), the PSQL terminal appears for a second and then shuts down. Below is the info from the docs http://postgresapp.com/documentation Uninstalling What I do to remedy the problem is type these 3 lines of code in bash: open ~/Library/Application\ Support/Postgres --> I delete the Var folder sudo sysctl -w kern.sysv.shmall=65536 sudo sysctl -w kern.sysv.shmmax=16777216 When I restart PSQL, it works. The problem I have an empty database. All my work is gone. How can I get PSQL running permantely so that I do not have to restart with an empty database? ### Logic in an overloaded constructor in scala Logic in an overloaded constructor in scala I am trying to add some processing logic in an overloaded constructor, but cannot seem to get it working. Here is a simplified example of what I want to do: class FooBar(val x: String, val y: String) { this(z: String) = { // DO SOME ARBITRARY CODE val x = // SOME ARBITRARY PROCESSING USING z val y = // SOME ARBITRARY PROCESSING USING z this(x, y) } } However, I am getting a compilation error: : 'this' expected but 'val' found This is a very simple task in Java, I would simply set the x, y instance variables from 2 separate constructors. Here is my Java equivalent of what I would like to accomplish: class FooBar { public String x; public String y; public FooBar(String x, String y) { this.x = x; this.y = y; } public FooBar(String z) { // DO SOME ARBITRARY CODE this.x = // SOME ARBITRARY PROCESSING USING z this.y = // SOME ARBITRARY PROCESSING USING z } } ### Square root of a natural number to square root of another natural number – math.stackexchange.com Square root of a natural number to square root of another natural number – math.stackexchange.com Is there such integers$x,y$which they're not perfect squares and they're not equal, such that:$\sqrt{x}^\sqrt{y}$is actually an integer? Or rational number? ### IPv6, cant ping Google from linux server IPv6, cant ping Google from linux server i assigned an IPv6 to my VPS (myipv6::5) from my host dedicated server which has myipv6::/64 assigned to it by datacenter. from VPS i did: ping6 -I myipv6::5 myipv6::1 So Im able to ping gateway, but I cannot ping past the gateway like this... ping6 -I myvpsipv6::5 ipv6.google.com PING ipv6.google.com(wg-in-x6a.1e100.net) from myipv6::5 : 56 data bytes From myipv6::1 icmp_seq=2 Destination unreachable: Address unreachable From myipv6::1 icmp_seq=3 Destination unreachable: Address unreachable From myipv6::1 icmp_seq=4 Destination unreachable: Address unreachable When i do same command (ping6 -I myipv6::5ipv6.google.com) at host machine (node server) where this VPS resides, the result is SAME "Address unreachable". Here are commands i did on host dedicated server ifconfig eth0 Link encap:Ethernet HWaddr 4C:72:B9:D2:BD:D4 inet addr:myipv4addresshere Bcast:*.*.*.255 Mask:255.255.255.0 inet6 addr: myipv6here::1/64 Scope:Global inet6 addr: fe80::4e27:c8ff:fec2:bdd4/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1767143835 errors:0 dropped:0 overruns:0 frame:0 TX packets:2246662202 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:878001097058 (817.7 GiB) TX bytes:2303874402348 (2.0 TiB) Interrupt:225 Memory:fe500000-fe520000 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:8467408 errors:0 dropped:0 overruns:0 frame:0 TX packets:8467408 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:1050265852 (1001.6 MiB) TX bytes:1050265852 (1001.6 MiB) venet0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet6 addr: fe80::1/128 Scope:Link UP BROADCAST POINTOPOINT RUNNING NOARP MTU:1500 Metric:1 RX packets:2223530855 errors:0 dropped:0 overruns:0 frame:0 TX packets:1740960126 errors:0 dropped:1948050 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:2262666403904 (2.0 TiB) TX bytes:831015511414 (773.9 GiB) route -n -A inet6 Kernel IPv6 routing table Destination Next Hop Flags Metric Ref Use Iface myipv6here::5/128 :: U 1024 0 0 venet0 myipv6here::6/128 :: U 1024 0 0 venet0 myipv6here::/64 :: U 256 1 0 eth0 myipv6herefff:ff:ff:ff:ff/128 :: U 1024 1 0 eth0 fe80::/64 :: U 256 0 0 eth0 fe80::/64 :: U 256 0 0 venet0 ::/0 myipv6here:: UG 1 34866 0 eth0 ::/0 myipv6herefff:ff:ff:ff:ff UG 1024 0 0 eth0 ::1/128 :: U 0 18787 1 lo myipv6here::/128 :: U 0 0 1 lo myipv6here::1/128 :: U 0 131933 1 lo fe80::/128 :: U 0 0 1 lo fe80::1/128 :: U 0 0 1 lo fe80::4e27:c8ff:fec2:bdd4/128 :: U 0 2 1 lo ff00::/8 :: U 256 0 0 eth0 ff00::/8 :: file /etc/sysconfig/network: NETWORKING_IPV6=yes IPV6FORWARDING=yes IPV6_DEFAULTDEV=eth0 IPV6_DEFAULTGW=myipv6here:0000:0000:0000:0000 ([openvz][1] shows that it should end by ::1) IPV6_AUTOCONF=no file etc/sysconfig/network-scripts/ifcfg-eth0 IPV6INIT=yes IPV6_AUTOCONF=no IPV6ADDR=myipv6here::1/64 (openvz shows that this ip should be without /64) file /etc/sysctl.conf net.ipv6.conf.default.forwarding = 1 net.ipv6.conf.all.forwarding = 1 net.ipv6.conf.all.proxy_ndp = 1 net.ipv6.bindv6only = 1 net.ipv4.conf.default.proxy_arp=0 net.ipv4.conf.all.rp_filter=1 net.ipv4.conf.default.send_redirects=1 net.ipv4.conf.all.send_redirects=0 Please anyone have ideas how to make this IPv6 working on the host server? Isnt there any issue with route? I read this post, which might give an idea about route, but i cant understand how that apply on my case, anyone please can help? ## Monday, 30 September 2013 ### Is the union of finitely many open sets in an omega-cover contained within some member of the cover? Is the union of finitely many open sets in an omega-cover contained within some member of the cover? Let$\mathcal{U}$be an open cover of$\mathbb{R}$(Standard Topology) such that$\mathbb{R} \not \in \mathcal{U}$and for any finite set$A$there is a$U \in \mathcal{U}$such that$A \subseteq U$. We call such an open cover an$\omega$-cover. Can we show that for any finite set$B
\subset \mathcal{U}$, there is a$V \in \mathcal{U}$such that$\cup B
\subseteq V$? Ultimately I'm working on showing the following. Let$\langle
$scaffold; } else { [user-friendly version code] } } But no dice. How can I achieve what I want? ### Undiscovered POCO class requirements Undiscovered POCO class requirements I have been developing an application for the last five months and just ran into this problem. We are using EF5 and, similar to this question, I designed the class hierarchy to have all entity classes derived from an abstract base class to force validation interfaces to be implemented. We are also using the validation attributes in the entity classes. Everything has worked fine until I started trying to use the entity classes in WCF Services. I am getting a bunch of serialization exceptions, and have been trying to figure out what "POCO" rule I broke in the design. This article tells me the class (obviously...) cannot be abstract, but since my classes are DERIVING from an abstract class, have I perhaps broken a rule I don't know about? Thanks, Peter ### trying to create Fibonacci Sequence trying to create Fibonacci Sequence I don't know what I'm doing wrong. I'm trying to print "fn" of the sequence. I based it on someone else's code. Any thoughts? Here is my code: int num = n; int fn = 1; int f1 = 0; int f2 = 1; for (int i = 2; i < n; i++) { fn = f1 + f2; f1 = f2; f2 = fn; } System.out.print( "fib( " + num + " ) is "); System.out.println( fn ); ### Can't get Robert Giesecke's Unmanaged Exports to work when trying to export a C# function from a dll Can't get Robert Giesecke's Unmanaged Exports to work when trying to export a C# function from a dll I created a dll in C# (in VS2012), that should export a function as unmanaged. My C# code looks like this: using RGiesecke.DllExport; using System.Runtime.InteropServices; using WMPLib; namespace WMPNative { public class WMP { [DllExport] public static string getCurrentlyPlayingSong() { WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer(); if (null != player.currentMedia) { return player.currentMedia.name; } else { return null; } } } } However, when I use dumpbin /exports, I don't see anything exported from my dll. I also tried using [DllExport()], [DllExport("getCurrentlyPlayingSong")] and [DllExport("getCurrentlyPlayingSong", CallingConvention = CallingConvention.Cdecl)], but neither produced different results. I'm also getting 2 warnings, but they seem to me unrelated to the problem: (Processing COM reference "WMPLib" from path "C:\Windows\system32\wmp.dll". Type library importer encountered a property getter 'sessionPlaylistCount' on type 'WMPLib.IWMPNowPlayingHelperDispatch' without a valid return type. The importer will attempt to import this property as a method instead. Processing COM reference "WMPLib" from path "C:\Windows\system32\wmp.dll". At least one of the arguments for 'IWMPGraphEventHandler.NotifyAcquireCredentials' cannot be marshaled by the runtime marshaler. Such arguments will therefore be passed as a pointer and may require unsafe code to manipulate. What am I doing wrong? ### Error code 1582: Incorrect parameter count in the call to native function 'FROM_UNIXTIME' Error code 1582: Incorrect parameter count in the call to native function 'FROM_UNIXTIME' My code is like:$current = time();
$nexttime = mktime($hour,$minute,$second,$month,$day,$year); //$hour...from a table
and mySQL statement is like:
INSERT INTO table(...) values
('FROM_UNIXTIME(".$current.")',FROM_UNIXTIME(".$nexttime."));
I found the first FROM_UNIXTIME(".$current.") is accepted by mySQL, while the second FROM_UNIXTIME(".$nexttime.") shows:
Error code 1582: Incorrect parameter count in the call to native function
'FROM_UNIXTIME'.
Any suggestion is appreciated.

## Thursday, 26 September 2013

I want my app to redirect to my home page ie posts#index. It is a rails2
app which I am trying to migrate to rails 3.
def rescue_action_in_public(exception)
flash[:notice] = "There was an error. Please try again." # #{exception}
redirect_to :controller => :posts, :action => :index
end
This method I presume does this task. How ever, It won't work in rails 3
and I see the 'Sorry something went wrong!' page
How can I get this functionality working in rails 3? If any more info is,
needed I am willing to paste here.

## Thursday, 19 September 2013

### HTML page not rendered correctly on PhoneGap

HTML page not rendered correctly on PhoneGap

First time i'm using PhoneGAP. We just design a responsive HTML template
and i'll integrate it to Phonegap. I have Android SDK .
phonegap create testApp com.example.testapp testApp
cd testApp
phonegap build android
This command creating a testApp folder and putting an example Android
project to testApp/platforms/android/
After this, i'm creating a new project with existed content on Eclipse ADT
. And then, i'm copying our responsive template's main.html file and all
other css, js and image files to testApp/platform/android/assets/www
folder. And lastly copy paste this to assets/www/index.html file. (It's a
workaround for a bug, see here)
<!doctype html>
<html>
<title>tittle</title>
<script>
window.location='./main.html';
</script>
<body>
</body>
</html>
Now it should work, but it's not. I'm starting emulator and then Run As
Android App on Eclipse, this is result. Blank (white) screen and a weird
black box.

Can you tell me what is i'm missing?

### rails - Adding static html pages without controller support

rails - Adding static html pages without controller support

I have a problem.
Well, I've got an website with some sitemap and I want to keep active
links to several html pages due to their high ranking in Google. Sample
page has the address: http://domain.com/my_important_page.html - this is a
static page in pure html written (requires no backend support).
Webpage has been re-written in RunyOnRails. How to make routes.rb to the
above page(s) (ex. domain.com/my_important_page.html) was seen at the same

### How to make Sign up page be root page in Devise?

I'm running on Rails 4.0.0 with Devise 3.1.0. My routes are setup like this:
devise_for :users do
root "devise/registrations#new"
end
resources :books
What I'm trying to do is make the Devise Sign Up Page be the Welcome Page
for users if they haven't signed in but if their signed in they'll go to
the Book Index. Right now it just gives me the standard Ruby on
Rails:Welcome Aboard page as if Devise doesn't exist. How would I do this?

### OpenGL multiple matrix transormations

OpenGL multiple matrix transormations

I have simple vertex shader for models
#version 330
layout(location = 0) in vec3 VertexPosition;
layout(location = 1) in vec3 VertexNormal;
layout(location = 2) in vec2 VertexUV;
out VS_GS_VERTEX
{
vec3 vs_worldpos;
vec3 vs_normal;
vec2 VertexUV;
} vertex_out;
uniform mat4 modelMatrix;
uniform mat4 projectionMatrix;
uniform mat4 lookAtMatrix;
void main(void)
{
mat4 MVP = projectionMatrix * lookAtMatrix * modelMatrix;
gl_Position = MVP * vec4(VertexPosition, 1.0);
gl_Normal = mat3(modelMatrix) * VertexNormal;
vertex_out.vs_worldpos = gl_Position.xyz;
vertex_out.vs_normal = gl_Normal;
vertex_out.VertexUV = VertexUV;
}
and I pass there modelMatrix
modelMat := MatrixMultiply(transMat, baseMat);
modelMat := MatrixMultiply(modelMat, scaleMat);
modelMat := MatrixMultiply(modelMat, rotMat);
glUniformMatrix4fv(modelMatrix_loc, 1, false, @modelMat);
where transMat for positioning, scaleMat to enlarge whole picture and
rotMat to rotate whole terrain. Everything fine while baseMat is
coordinates of model on terrain
baseMat := CreateTranslationMatrix(AffineVectorMake(pos.x, pos.y, pos.z));
but when I trying also to enlarge model by own model's scale (model have
zero based coordinates, for example roots of tree at (0, 0, 0))
scMat := CreateScaleMatrix(AffineVectorMake(scale, scale, scale));
trMat := CreateTranslationMatrix(AffineVectorMake(pos.x, pos.y, pos.z));
baseMat := MatrixMultiply(scMat, trMat);

models not just enlarged, they also changing coordinates and not placed on
terrain anymore. Is it possible to make one model matrix with model's
scaling, rotation, translation, yet another translation, scaling and
rotation? Or I should do something else? Matrix math from GLScene and
seems works fine.

### How to remove Midori from Elementary OS 0.2?

How to remove Midori from Elementary OS 0.2?

Sometime ago I met Elementary OS and I loved it, but it isn't stable yet.
Midori is the default browser of Elementary. If you go to "Applications"
you can find and open Midori, but when you go to Software Center you can't
find it.
I want delete Midori because I prefer Chromium, but as I can't find it in
Software Center, how I can remove that?

### MySQL transaction to single query

MySQL transaction to single query

I have a game with 2 users, at the game start I want to save their initial
balance then cut some amount of money from them.
Currently I do this with 3 queries in a transaction. Here's the code:
#region cut_money
bool success = true;
tr = conn.BeginTransaction();
cmd = new MySqlCommand("UPDATE games SET user1_starting_balance = (SELECT
money FROM users WHERE users.id = games.user1_id), user2_starting_balance
= (SELECT money FROM users WHERE users.id = games.user2_id) WHERE id =
@id", conn, tr);
if (cmd.ExecuteNonQuery() != 1)
success = false;
for (int i = 0; i <= 1; i++)
lock (this.users[i].id.ToString())
{
cmd = new MySqlCommand("UPDATE users SET money = money - @bmoney,
blocked_money = blocked_money + @bmoney WHERE id = @user_id AND
money >= @bmoney", conn, tr);
if (cmd.ExecuteNonQuery() != 1)
{
success = false;
break;
}
}
if (success)
tr.Commit();
else
tr.Rollback();
conn.Close();

### How to find out wich key has the same key in Microsoft.Practices.EnterpriseLibrary.SemanticLogging unit test

How to find out wich key has the same key in
Microsoft.Practices.EnterpriseLibrary.SemanticLogging unit test

I'm using Enterprise Librarys Semantic Logging. When I run my unit test:
EventSourceAnalyzer.InspectAll(MyEventSource.Log)
it fails, throwing an exception: System.ArgumentException: An item with
This is all good, but I made a bunch of Changes in the last check in. Is
there a way to find out what key allready have been added?
The app also fails with the same error message when I add my
ObservableEventLister:
_logListener.EnableEvents(MyEventSource.Log, EventLevel.Verbose,
Keywords.All)

## Wednesday, 18 September 2013

### fgets printing two lines before input

fgets printing two lines before input

So I am trying to write a program that will let me read a user input for
data on an MP3 file using a doubly linked list data structure. I got most
of the methods and functions to work, but when I am prompting the user to
put in input it prints out two lines before the user can input for the
first line. So for example
int main()
{
int user_input = 0;
while(!(user_input >= 4))
{
struct MP3_data_node* MP3_data;
MP3_data = (struct MP3_data_node*)malloc(sizeof(struct
MP3_data_node));
printf("\nPlease select a number for one of the following
instructions:\n");
printf("0: add to list\n1: delete from list\n2: print the list
from beginning to end\n3: print the list from end to
beginning\n4: exit\n");
scanf("%d", &user_input);
if(user_input == 0)
{
fgets(MP3_data->artist,50,stdin);
fgets(MP3_data->artist,50,stdin);
fgets(MP3_data->artist,50,stdin);
printf("Please provide the year the song was released:
");
scanf("%d", &MP3_data->yearReleased);
printf("Please provide the length of the song in
seconds: ");
scanf("%d", &MP3_data->runTime);
}
...
So it prints out "Please provide the artist:Please provide the album:" and
then let's me put the input in, so my question is how do I make it so that
album: (user input) etc.

### AudioSessionSetActive and AudioSessionSetProperty is deprecated in iOS 7

AudioSessionSetActive and AudioSessionSetProperty is deprecated in iOS 7

The following code has been deprecated in iOS 7:
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof
(category), &category);
AudioSessionSetActive (true);
Anyone know what the replacement is?

### Any libraries for recommendation engines for company names? (preferably node/javascript)

Any libraries for recommendation engines for company names? (preferably
node/javascript)

Are there any libraries or services that allow the developer to pass in a
brand / company name, and returns other brands / company names that might
be similar?
Ideally, I'd like to be able to let a user enter in a company or companies
(say, samsung and HTC), and the user would get back some companies that
might be similar (say, LG, Apple, Nokia) based on information available on
the web.
Node/javascript would be ideal, since that's what I'm using...
Thanks!

### application:openURL:sourceApplication:annotation: returns a null url

application:openURL:sourceApplication:annotation: returns a null url

I need my iOS app to handle app-URLs like myapp://d1/d2.
I set the URL Typesin my app's info.plist and implemented the required
delegate method:
-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
...
}
I run my app, then switch to Safari (thus my app runs in the background).
In Safari I open URL myapp://d1/d2. As a result my app pops to the
foreground as advertised and the method above is called. The problem is
that that all its parameters (application, url, sourceApplication and
annotation) are null.
After spending some time and not getting any non-null parameters, I tried
to replace the method above with the depreciated
application:handleOpenURL:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
...
}
That worked. The url' parameter is exactly what I typed in Safari.
Obviously I don't want to use a depreciated method. What am I doing wrong?
Running on iPad with iOS 6.1.3, and on a simulator.

### WPF Binding from strings to Canvas objects in a ResourceDictionary using Converter

WPF Binding from strings to Canvas objects in a ResourceDictionary using
Converter

I have a ResourceDictionary made up of icons/Canvas objects drawn with
Paths. My ViewModel includes a string property (IconName) that contains a
string matching one of the entries in the ResourceDictionary. I developed
a MultiBinding (IMultiValueConverter) that takes the string, and a
FrameworkElement and does a resource lookup, returning the resource
matching the name. Before getting to this point, I stubbed my View
explicitly with the following:
<Rectangle Width="10" Height="10" Margin="0,0,10,0">
<Rectangle.Fill>
<VisualBrush Stretch="Fill" Visual="{StaticResource defalt_icon}" />
</Rectangle.Fill>
</Rectangle>
This renders correctly. However, when I switch out to the following,
nothing is rendered in the Rectangle.
<Rectangle Width="10" Height="10" Margin="0,0,10,0">
<Rectangle.Fill>
<VisualBrush Stretch="Fill">
<VisualBrush.Visual>
<MultiBinding Converter="{StaticResource IconNameConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource
AncestorType=FrameworkElement}"/>
<Binding Path="IconName"/>
</MultiBinding.Bindings>
</MultiBinding>
</VisualBrush.Visual>
</VisualBrush>
</Rectangle.Fill>
</Rectangle>
My converter (show below) is being called, and does find the Canvas object
and returns it (viewing the object in the debugger I can see that Canvas
has a Path child that has the right Data member filled in).
public class IconNameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object
parameter, System.Globalization.CultureInfo culture)
{
FrameworkElement targetElement = values[0] as FrameworkElement;
string iconName = values[1] as string;
if (iconName == null)
return null;
FrameworkElement newIcon =
(FrameworkElement)targetElement.TryFindResource(iconName);
if (newIcon == null)
newIcon =
(FrameworkElement)targetElement.TryFindResource("appbar_page_question");
return newIcon;
}
public object[] ConvertBack(object value, Type[] targetTypes, object
parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Any ideas why the canvas isn't showing up?

### Anonymous function in class php 5.3

Anonymous function in class php 5.3

I searched a lot and try to understand the way anonymous function work.
I found that we can use $seft =$this and then use it inside anonymous
function.
But what I can't understand is:
May I have ?
class A
{
function __Construct()
{
$self = new B;$self->helloworld = function($world,$self) {
echo get_class($self).' '.$world;
};
}
}
class B
{
function __Construct()
{
$this->helloworld('want to say hello world!'); } }$A = new $A; //Ouput B want to say hello world! Or there're other ways to work around this? ### how to add time of rows datatype in sql how to add time of rows datatype in sql 01:24:52.0000000 01:15:00.0000000 04:20:06.0000000 00:59:12.0000000 00:58:00.0000000 01:26:08.0000000 00:13:20.0000000 04:27:45.0000000 01:28:48.0000000 02:07:36.0000000 I want addition of all the values in minutes alone ### Iterate with ng-options in a dictionary(object) Iterate with ng-options in a dictionary(object) I need to iterate over the following object with ng-options: var a = { 'optionName1': 'optionValue1', 'optionName2': 'optionValue2', 'optionName3': 'optionValue3', 'optionName4': 'optionValue4', }; I get this object in this format from a 3rd party resource, and I'd rather no to re-arrange it manually. I already did a Google search, and looked into the documentation, it deals with lists, and lists of objects only from what I could tell. ### remove border from swt tree remove border from swt tree I need to remove border what is on that screen. http://imageshack.us/photo/my-images/4/p85f.png/ I am trying to use style SWT.NONE but with no effect ;/ ## Tuesday, 17 September 2013 ### Sub column in itext Sub column in itext I got 8 columns in the table. But the 4th column has likely 12-sub columns under it. Can anyone suggest how to create a table like that in itext. To be more specific, i need to add 12 more sub columns under the 4th column. ### How to set a custom font for Arraylist Listactivity How to set a custom font for Arraylist Listactivity So i searched and found out that i need to create a custom array adapter to change the font of a listview activity. My list activity consists of an arraylist. So i did as such public class CustomArrayAdapter extends ArrayAdapter <String> { private Typeface tf; private LayoutInflater inflater; private int resource; private int textViewResourceId; private ArrayList<String> objects; public CustomArrayAdapter(Context context, int resource, int textViewResourceId, ArrayList<String> favorites, Typeface tf) { super(context, resource, textViewResourceId, favorites); this.tf = tf; this.resource = resource; this.textViewResourceId = textViewResourceId; this.objects = favorites; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(resource, parent, false); } TextView text = (TextView) convertView.findViewById(textViewResourceId); text.setTypeface(tf); return convertView; } } and here is my Listactivity public class Favorites extends ListActivity { public static ArrayList<String> favorites = new ArrayList<String>(); public static final String PREFS_NAME ="SAVEDATA"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Typeface cFont = Typeface.createFromAsset(getAssets(), "annoyingkettle.ttf"); setListAdapter(new CustomArrayAdapter(this, android.R.layout.simple_list_item_1, R.id.ListView01, favorites, cFont)); This doesnt work, i dont know why. My listactivity crashes when i try to open it. How can i fix this? And here is my xml <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/ListView01" > EDIT: Here is the LogCat '09-18 02:36:16.036: E/Trace(15562): error opening trace file: No such file or directory (2) 09-18 02:36:17.486: D/dalvikvm(15562): GC_FOR_ALLOC freed 73K, 7% free 2655K/2848K, paused 251ms, total 287ms 09-18 02:36:17.539: I/dalvikvm-heap(15562): Grow heap (frag case) to 3.781MB for 1127536-byte allocation 09-18 02:36:17.826: D/dalvikvm(15562): GC_FOR_ALLOC freed 2K, 5% free 3754K/3952K, paused 274ms, total 274ms 09-18 02:36:18.066: D/dalvikvm(15562): GC_CONCURRENT freed <1K, 5% free 3769K/3952K, paused 5ms+13ms, total 224ms 09-18 02:36:18.316: D/gralloc_goldfish(15562): Emulator without GPU emulation detected. 09-18 02:36:24.436: D/AndroidRuntime(15562): Shutting down VM 09-18 02:36:24.436: W/dalvikvm(15562): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 09-18 02:36:24.588: E/AndroidRuntime(15562): FATAL EXCEPTION: main 09-18 02:36:24.588: E/AndroidRuntime(15562): java.lang.NullPointerException 09-18 02:36:24.588: E/AndroidRuntime(15562): at com.mkaya.ultimatejokescollection.CustomArrayAdapter.getView(CustomArrayAdapter.java:41) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.AbsListView.obtainView(AbsListView.java:2159) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.ListView.makeAndAddView(ListView.java:1831) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.ListView.fillDown(ListView.java:674) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.ListView.fillFromTop(ListView.java:735) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.ListView.layoutChildren(ListView.java:1652) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.AbsListView.onLayout(AbsListView.java:1994) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.View.layout(View.java:14008) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewGroup.layout(ViewGroup.java:4373) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.FrameLayout.onLayout(FrameLayout.java:448) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.View.layout(View.java:14008) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewGroup.layout(ViewGroup.java:4373) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.LinearLayout.onLayout(LinearLayout.java:1434) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.View.layout(View.java:14008) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewGroup.layout(ViewGroup.java:4373) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.widget.FrameLayout.onLayout(FrameLayout.java:448) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.View.layout(View.java:14008) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewGroup.layout(ViewGroup.java:4373) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1892) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1711) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
09-18 02:36:24.588: E/AndroidRuntime(15562): at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.Choreographer.doCallbacks(Choreographer.java:562) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.Choreographer.doFrame(Choreographer.java:532) 09-18 02:36:24.588: E/AndroidRuntime(15562): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
09-18 02:36:24.588: E/AndroidRuntime(15562): at
android.os.Handler.handleCallback(Handler.java:725)
09-18 02:36:24.588: E/AndroidRuntime(15562): at
android.os.Handler.dispatchMessage(Handler.java:92)
09-18 02:36:24.588: E/AndroidRuntime(15562): at
android.os.Looper.loop(Looper.java:137)
09-18 02:36:24.588: E/AndroidRuntime(15562): at
09-18 02:36:24.588: E/AndroidRuntime(15562): at
java.lang.reflect.Method.invokeNative(Native Method)
09-18 02:36:24.588: E/AndroidRuntime(15562): at
java.lang.reflect.Method.invoke(Method.java:511)
09-18 02:36:24.588: E/AndroidRuntime(15562): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 09-18 02:36:24.588: E/AndroidRuntime(15562): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 09-18 02:36:24.588: E/AndroidRuntime(15562): at dalvik.system.NativeStart.main(Native Method) 09-18 02:36:27.846: I/Process(15562): Sending signal. PID: 15562 SIG: 9 ' ### neo4j V2.0.0 M5 "java.lang.NullPointerException" neo4j V2.0.0 M5 "java.lang.NullPointerException" After upgrading to Neo4j V2.0.0 M5 I ran into the subject error when running a cypher query in my web app. To isolate the issue, I tried the following similar queries in the basic Neo4j console (http://console.neo4j.org/) as follows: START n=node(*) WHERE n.name ='Neo' RETURN n Result: (6 {name:"Neo"}) Next tested match on regular expression using "=~" START n=node(*) WHERE n.name =~'Neo.*' RETURN n Result: Error: java.lang.NullPointerException Next tested on case insensitive by pre-pending a regular expression with (?i) START n=node(*) WHERE n.name =~'(?i)Neo' RETURN n Result: Error: java.lang.NullPointerException And finally tested for both regex and case insensitivity with =~ '(?i)neo.*' MATCH n WHERE n.name =~ '(?i)neo.*' RETURN n Result: Error: java.lang.NullPointerException I believe the issue is with "=~." Shouldn't all of these queries resulted in returning the "Neo" node? If not, please let me know why? Thank you, Jeff ### Android Fragments: Immediate Null Point Exception Android Fragments: Immediate Null Point Exception I know this information is all over the internet, but I can't for the life of me figure out what I'm doing wrong. When I try to run my code it crashes immediately with a null pointer exception, but I can't seem to figure out why that is happening or where it is happening. I imagine I am missing something fairly simple, but I am new to android so I don't know what it is. Here is the code: MainActivity: public class MainActivity extends Activity implements GetConnInfoFragment.ConnInfoReceiver { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); GetConnInfoFragment frag = new GetConnInfoFragment(); fragmentTransaction.add(R.id.mainFragmentContainer, frag); fragmentTransaction.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } .... GetConnInfoFragment: public class GetConnInfoFragment extends Fragment { ConnInfoReceiver ownerActivity; @SuppressLint("NewApi") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button goButton = (Button) getView().findViewById(R.id.connectButton); goButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText portBox = (EditText) v.findViewById(R.id.portBox); int port = Integer.parseInt(portBox.getText().toString()); EditText ipBox = (EditText) v.findViewById(R.id.ipAddressBox); String address = ipBox.getText().toString(); // create sockets, might these be garbage collected ? // in which case the main activity should create them. That makes // more sense anyway // activate next fragment -- call back up to the main activity to trigger this ownerActivity.receiveConnInfo(port, address); } }); return inflater.inflate(R.layout.getconninfofragment, container, false); } Here is the error message: E/AndroidRuntime(1470): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.htpccontrol/com.htpccontrol.MainActivity}: java.lang.NullPointerException ### I am wanting to run a DOS cmd to copy an exe file from another directory and then run the executable using a wildcard but it's not working I am wanting to run a DOS cmd to copy an exe file from another directory and then run the executable using a wildcard but it's not working Here is the cmd in which it does copy the file but does not execute it afterwards: copy /v /z "\cardinal-9547e3\Active Production\Isotrac Online*.exe" %tmp% %tmp\Isotrac Online*.exe ### MVC .. should one database_model contain CRUD for all object_models? Active record vs. registry pattern MVC .. should one database_model contain CRUD for all object_models? Active record vs. registry pattern I'm writing a fairly simple "fact database" in PHP (with Codeigniter .. but I am trying to get away from the framework internals for learning purposes), and trying to better my MVC/OOP practices. Previously I would have done this: a fact model, a user model, a source model .. and inside each of those models I would place the CRUD logic for each. So my controllers would have$this->fact_model->save($fact);$this->user_model->deactivate($uid);$this->source_model->get_id($sid); But after reading more, it seems to make sense to have a separate persistence model (ie 'database_model'). But then it seems it would have to contain a full range of CRUD for each type of object, which seems wasteful to me. I guess I'm looking for how to go to this...$this->db_m->save(Fact $fact);$this->db_m->update(User $user); // .. etc .. but also ..$this->db_m->get_user_id($uid); // .. and ..$htis->db_m->get_all_facts();
Is this heading in the right direction? Do I just end up testing for type
inside the database model and switching when I need to? Or do I extend the
database model for each type of object?
$this->fact_db_m->save(Fact$fact);
$this->fact_db_m->get_all();$this->source_db_m->get_id($sid); Or something like this, which I guess is the closest to CIs AR implementation.$this->db_m->save('facts', Fact $fact);$this->db_m->get('user', array('id'=>$uid)); I guess this is a case of "active record vs repository". I understand that repository is easier to test, and the CRUD logic is separate from the object data, and that separation makes sense to me. But still.. it means you have to write a separate repository model for each entity. Is this right? BTW - I know Codeigniter has a Database class and uses active record, and in a way I am just kind of re-creating it with some of those approaches. I'm just trying to understand things without relying on the framework internals. Any comments? Is it just a matter of choice? ## Sunday, 15 September 2013 ### Recompiling VIM: apt-get can't find source code? Recompiling VIM: apt-get can't find source code? I'm trying to recompile VIM with clipboard support and I'm attempting to follow this guide. The trouble is that when I do: sudo apt-get source vim I get E: Unable to find a source package for vim, although the package name was auto-completed and exists if you type sudo apt-get source <tab><tab> By the way, before I started, I did sudo apt-get remove vim. Any ideas how to proceed? I'm using Ubuntu 12.04 LTS. ### Android Facebook Authentication Failed- Cannot Find PlatformProvider Android Facebook Authentication Failed- Cannot Find PlatformProvider I am collaborating with someone on an Android application. My partner had the Facebook authentication/sharing process on her emulator, but it fails to launch on my computer. Here's the code: package com.example.music23andme; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.facebook.*; import com.facebook.widget.*; public class MainActivity extends Activity { OnClickListener login23_listener = null; OnClickListener music_listener = null; OnClickListener loginfb_listener = null; Button button_login23w; Button button_musicw; Button button_loginfbw; Button button_demo; private UiLifecycleHelper uiHelper; private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { onSessionStateChange(session, state, exception); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(this, callback); uiHelper.onCreate(savedInstanceState); login23_listener = new OnClickListener() { public void onClick(View v) { Intent intent0 = new Intent(MainActivity.this, WebViewActivity.class); startActivity(intent0); } }; music_listener = new OnClickListener() { public void onClick(View v) { Intent intent1 = new Intent(MainActivity.this, MusicActivity.class); startActivity(intent1); } }; loginfb_listener = new OnClickListener() { public void onClick(View v) { if (FacebookDialog.canPresentShareDialog(getApplicationContext(), FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) { FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(MainActivity.this) .setLink("https://developers.facebook.com/android") .build(); uiHelper.trackPendingDialogCall(shareDialog.present()); } } }; setContentView(R.layout.activity_main); button_login23w = (Button)findViewById(R.id.button_login23); button_login23w.setOnClickListener(login23_listener); button_musicw = (Button)findViewById(R.id.button_music); button_musicw.setOnClickListener(music_listener); button_loginfbw = (Button)findViewById(R.id.button_loginfb); button_loginfbw.setOnClickListener(loginfb_listener); button_demo= (Button) findViewById(R.id.playDemo); button_demo.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Intent demoIntent= new Intent(getApplicationContext(), MusicActivity.class); demoIntent.putExtra("demo", true); startActivity(demoIntent); } }); } private void onSessionStateChange(Session session, SessionState state, Exception exception) { if ((exception instanceof FacebookOperationCanceledException) || (exception instanceof FacebookAuthorizationException)) { new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.cancelled) .setMessage(R.string.permission_not_granted) .setPositiveButton(R.string.ok, null) .show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() { @Override public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) { Log.e("Activity", String.format("Error: %s", error.toString())); } @Override public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) { Log.i("Activity", "Success!"); } }); } @Override protected void onResume() { super.onResume(); uiHelper.onResume(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); uiHelper.onSaveInstanceState(outState); } @Override public void onPause() { super.onPause(); uiHelper.onPause(); } @Override public void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } } The error message was: Failed to find provider info for com.facebook.katana.provider.PlatformProvider ### How can I create an option menu with while and switch statements? How can I create an option menu with while and switch statements? I'm trying to create a menu where you have four options: You can register a bird you have seen in a textfile. You can write the type of a bird you have seen. You can write the place where you have seen the bird. Close the program This is what I have done so far: import easyIO.*; class Menu { public static void main(String[] args) { int counter = 0; while (counter != 4) { counter = meny(); switch (counter) { case 1: ReigsterBird(1); break; case 2: WriteBirdType(2); break; case 3: WritePlace(3); break; case 4: break; default: System.out.println("Give a number between 1 and 4"); } } } But I keep getting these errors, and also i'm not sure how I can solve this. Is there something i'm missing? Menu.java:9: error: cannot find symbol counter = meny(); ^ symbol: method meny() location: class Menu loop.java:13: error: cannot find symbol ReigsterBird(1); ^ symbol: method ReigsterBird(int) location: class Menu Menu.java:16: error: cannot find symbol WriteBirdType(2); ^ symbol: method WriteBirdType(int) location: class Menu loop.java:19: error: cannot find symbol WritePlace(3); ^ symbol: method WritePlace(int) location: class Menu 4 errors I would appreciate if someone could help out on this so I could create a menu where you have four options you can choose from. ### UIToolBar With Status bar UIToolBar With Status bar I have a problem with a view where the Toolbar appears underneath the status bar. In Interface Builder my view looks like... The code that assembles the view controllers... - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.mainVC = [[ChartVC alloc] initWithNibName:@"ChartVC_iPad" bundle:nil]; self.window.rootViewController = self.mainVC; [self.window makeKeyAndVisible]; } And how it appears in the simulator... - (Notice the extra 20px space at the bottom) So my question is, how can I correctly position the Toolbar and get rid of the white space at the bottom? ### MagicalRecord creates Database but no tables? MagicalRecord creates Database but no tables? I am using Magical Record and it is creating my database but it is not creating the underlying tables needed for my model. I've used Magical Record in the past without issue, always simple enough: [MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"]; Am I missing a setting here? Has anyone else ran into this problem? ### Dynamic array class c++ Dynamic array class c++ I am writing a dynamic array class. I included a copy constructor and operator= function to allow me to assign one array to another. It works when I assign arrays of the same length to one another, but when they have different lengths, I get compiler memory warnings, and/or the code bombs without executing, depending on whether the lefthand array is larger than the right-hand array, and vice versa. I have a function that inserts values to the array, and think that the issue might lie here (note: I had to comment out the memory deletion inside the destructor to get the code going). class Array { private: int * ptr; int size; int numElement; public: Array(); Array(const int*, int); Array(const Array&); ~Array(); void setValueAtIndex(int, int); void insertValueAtEnd(int ); int getArraySize(); const Array& operator=(const Array& ); }; #include "array.h" #include <stdlib.h> #include <iostream> using namespace std; Array::Array() { size = 10; numElement = 0; ptr = new int[size]; for (int i = 0; i < size; ++i) { ptr[i] = 0; } } Array::Array(const int * ptr_, int size_) { size = size_; numElement = size; ptr = new int[numElement]; for (int i = 0; i < size; ++i) { ptr[i] = ptr_[i]; } } Array::Array(const Array& other) { size = other.size; numElement = other.numElement; if (other.ptr) { ptr = new int[numElement]; for(int i = 0; i < size; ++i) { ptr[i] = other.ptr[i]; } if(!ptr) { exit(EXIT_FAILURE); } } else ptr = 0; } Array::~Array() { if(ptr) { //delete [] ptr; //ptr = 0; } } void Array::setValueAtIndex(int a, int b) { if(b > size) { exit(EXIT_FAILURE); } ptr[b] = a; } void Array::insertValueAtEnd(int insert) { if(numElement == size) { size++; } ptr[size-1] = insert; numElement++; } int Array::getArraySize() { return size; } const Array& Array::operator=(const Array& other) { if(this != &other) { if (ptr) { delete [] ptr; ptr = 0; } numElement = other.numElement; size = other.size; if(other.ptr) { ptr = new int[numElement]; for(int i = 0; i < size; ++i) { ptr[i] = other.ptr[i]; } } else ptr = 0; } return *this; } ### click event is not captured on android but works on other browsers click event is not captured on android but works on other browsers$('#btnSearchMobile').trigger('click');
document.getElementById('btnSearchMobile').click();
I have tried the above 2 ways to initiate the click on the element id
btnSearchMobile. It works for chrome, firefox, safari, but not on android.
Do you guys have any idea why?
Sorry if it isn't clear. Do comment :)

## Saturday, 14 September 2013

### Is there a way to add column at a specified position?

Is there a way to add column at a specified position?

Consider this inital table I have created:
CUSTOMER_ID ACC_NO ACC_BALANCE
----------- ------ -----------
100 200 1000
101 150 4000
102 350 2000
103 450 2500
104 550 2200
Now I want to add another column customer_name into the table. I used:
alter table bank_account add (Customer_name varchar2(30));
and the column is being inserted as the last column in the table whereas I
want the column to be added to the table as the second column. Now the SQL
code I mentioned is unable to do so. So how can I add the column at a
specified position? Is it even possible in SQL?

### How to get an image sent from a servlet with ajax?

How to get an image sent from a servlet with ajax?

I am trying to send a string to be encoded in a qr image and return the
image on the same page.
<form action="qrservlet" method="get">
<p>create QR Code</p>
<input type="text" name="qrtext" />
<input type="submit" value="Generate QR Code" />
</form>
This works fine but it returns a new page. I'm trying to load the image in
the page itself.
$(document).ready(function(){$("#submit").click(function(){
$.ajax({ type: "GET", url: "qrservlet", data: { "qrtext" : "www.mypage.com" }, success:function(result) {$("#content").html(result);
}
});
});
});
When I try this it returns a bunch of symbols.

### SQL SCOPE_IDENTITY Recording twice

SQL SCOPE_IDENTITY Recording twice

I have a stored procedure as
@user1 uniqueidentifier ,
@user2 uniqueidentifier ,
@mesaj_text varchar(500),
AS
BEGIN
declare @chat_id int
IF EXISTS (SELECT chat_id FROM chat where user1=@user1 and user2 =@user2
or user1=@user2 and user2 =@user1)
BEGIN SELECT @chat_id =chat_id FROM chat where user1=@user1 and
user2 =@user2 or user1=@user2 and user2 =@user1
INSERT INTO mesaj values
ELSE insert into chat values (@user1,@user2)
SET @chat_id=SCOPE_IDENTITY()
insert into mesaj values
Everything is ok.
But recording twice "mesaj".Getting first inserted id of "mesaj" and using
it as chat_id for second record. So recording twice.(mesaj means message
in Turkish :) ) .I tried to use @@IDENTITY instead of SCOPE_IDENTITY but
nothing change.I tried to use IDENT_CURRENT(chat) but return error
"Invalid column name 'chat'."
How can I solve this problem ?

### Parsing simple text file and integrate content in bash script

Parsing simple text file and integrate content in bash script

I want to automatically parse a text file with a content like this:
car 12345 W
train 54321 D
To be integrated in a new bash file. The content after that should look
like that:
curl http://example.com/?vehicle=car&number=12345&period=W
curl http://example.com/?vehicle=train&number=54321&period=D
My problem is that I really don't now how to realize that or which program
to use, sed, awk, etc..
What do I have to do?

### Storing JSON signature captured from web in Filemaker Database as Image with php

Storing JSON signature captured from web in Filemaker Database as Image
with php

web. It is pushing to a filemaker database as JSON coordinates.
Is there a way to store that JSON coordinates as an image on a Filemaker
Database?
Or alternately, is there solution that allows coordinates to be processed
as an image for pdf forms?
p.s. I've tried including the php signature-to-image.php file that is on
the tutorial page, but it was giving me an error on 58 of the code from
that file itself. Not sure if that would have converted the coordinates
for storing in database that way.
Similar issue to: Extract X&Y coordinates

### Pass Core Data Entity Attribute From ViewController A to B

Pass Core Data Entity Attribute From ViewController A to B

I have small problem with Core Data. I will skip the code because it's
working fine. I just need to know what to do inside prepareForSeague
method.
App has 2 Views - ViewControllerA and TableViewControllerB. In
TableViewControllerB I've set up table view with custom cell with cell
identifier: customCell. I press button ADD and it shows Alert view with 2
rows. Alert View adds 2 Attributes to entity and these attributes are
displayed in table cell. Entity is called SOMEentity while Attributes are
name (NSString) and value (NSString also).
View controller A has two textFields: TextFieldA and TextFieldB, a button
calculate and label called calculateLabel. Calculate button simply adds
values from textFields.
Now I want to do this - clicking on cell will display Attribute Value in
TextFieldA.
what do I have to do inside
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender;
{
if ([[segue identifier] isEqualToString:@"FromViewBToViewA"]) {
}
}
Also, do I have to write something inside viewDidLoad method in
ViewControllerA? all strings and labels have nonatomic, strong properties.
Thanks!

### Generating 1lakh solutions using while Loop and bind to grid view

Generating 1lakh solutions using while Loop and bind to grid view

Here i am taking 30 records from database and using these 30 records i'm
doing permutation and combinations in a while loop and its generating
output 1 lakh solutions.while running this looping its taking huge time to
get an output.
Is there any way to speed up this looping and also to speed up the
process of binding these 1 lakh solution to grid view

## Friday, 13 September 2013

### Windows CMD to find listening TCP/IP ports of a "un-ping-able" PC on LAN?

Windows CMD to find listening TCP/IP ports of a "un-ping-able" PC on LAN?

I am developing a server-client web-application on LAN, in which the
clients need to auto-detect & connect to the server.
Because some servers are with windows fiewall on, pinging them reply
nothing. I wonder how can I detect that type of server PCs?
The only clue I have is that the Servers' application run on a random port
in range : 1025 ~ 2025.
Do I need to try connecting from 192.168.0.1 to 192.168.0.254 & check 1000
ports for every IP? Thanks !

### Remove And Hide TD using script

Remove And Hide TD using script

Good Day I'm using Asp.net for my website and I want to remove and Hide
and specific td with class attribute
here is my html code
<table>
<tr>
<td class="1"> 1 </td>
<td class="1"> 1 </td>
<td class="2"> 2 </td>
<td class="2"> 2 </td>
</tr>
</table>
Now i have 2 button in my website named btn1 and btn2
if btn1 is click i want to remove ALL class with 1 and show only class with 2
And
if btn2 is click i want to remove ALL class with 2 and show only class with 1

### JFileChooser has bug with some filenames?

JFileChooser has bug with some filenames?

I'm using Ubuntu, and I tried to use JFileChooser in my java application,
but it seems that it has problems with file names that can be described
with this regex:
.*$.*$.*
Which means file names that contain "[" and "]". Dialog just rejects to
select such files for saving. Am I the only one to have this problem? What
could be the problem?
I used oracle jre and open-jdk jre.

### numerical correctness in openCL (CPU) vs java?

numerical correctness in openCL (CPU) vs java?

I'm implementing a numerical algorithm in both Java and OpenCL (through
the www.jocl.org bindings), and I noticed a strange behaviour: there are
clear differences between the numerical outcome of the java program and
the OpenCL program, even on CPU. On GPU this could be expected, but on
CPU? Aren't both Java and OpenCL supposed to use the same numerical
instructions embedded in the CPU?
Naturally, I first thought that it would be a concurrency issue, but that
turned out not be the case since the results are consistent and the issue
remains identical even when I put global_work_size = 1.
Then, I thought I had maybe stumbled upon a compiler error. Unfortunately,
the results were similar for each of the following device/driver
combinations in my possession:
Intel CPU with Intel driver
Intel CPU with AMD driver
Nvidia GPU with Nvidia driver
AMD GPU with AMD driver
Each of them gave a similar result in OpenCL, but both CPUs yielded a
different result in Java. And the Java result is the "correct" one (yields
the same statistical probabilities as documented in the literature).
So, I would like to know if anyone has any idea what could possibly be
going wrong? I'm out of inspiration what could possibly be going wrong.
Aren't OpenCL on CPU and Java supposed to be identical in numerical
precision, as they should be using the same CPU instructions?

### Unable to find Nvidia OpenCL SDK

Unable to find Nvidia OpenCL SDK

I am trying to find the Nvidia OpenCL SDK. No luck so fare.
I am starting to give up so I am asking here in case someone can cast some
light on the issue.

### Click on "enabled = false" checkbox(asp.net) via jquery

Click on "enabled = false" checkbox(asp.net) via jquery

I want to make eneble asp.net control by click on it. Using java. I know
there is removeAttr('disabled','disabled') but it isn't working at all. I
also know by looking on DevTools, that when i make asp.net control
enabled=false, then control is being put in <span
disabled="disabled">MyControl</span>. That make me think that, maybe I
should make my control disabled in other way but I do not know how. I
would be pleased if someone could show me a way to solve this problem or
rather a direction witch I should head to solve by my efforts this
problem.

### addition of values of variable and convert into hexadecimal in shell script

addition of values of variable and convert into hexadecimal in shell script

in a shell script I have a value
variable=8,4,2
now what I suppose to do is add all the numbers = 1+2+3 = 14
how can I achieve this ? sum of this values in shell script ?
convert this decimal number into hexadecimal number
echo "obase=16; 14" | bc
but i want to answer in these formats
e
0e
00e
how can I achieve it ?

## Thursday, 12 September 2013

### sqlalchemy and how to count row

sqlalchemy and how to count row

I have the following code:
query = self.dbObj.session.query(MaterialsTable)
rowCounter = self.dbObj.session.query(MaterialsTable)
for attr , val in interfaceCodesObject.filterNameDict.items():
query = query.filter(and_(getattr(MaterialsTable,attr).like("%%%s%%" %
val)))
rowCounter =
rowCounter.filter(and_(getattr(MaterialsTable,attr).like("%%%s%%" %
val))).count()
query.all()
When i use mutiple field, i get the following traceback:
Traceback (most recent call last):
File "/home/mohsen/codes/amlak/amlak/src/ui/materialsFindFrame.py", line
202, in <lambda>
QtCore.QObject.connect(self.pushButtonSearch,
QtCore.SIGNAL(_fromUtf8("clicked()")), lambda:
self.interfaceCodesConstructor.responseToRequestForData(self))
File "/home/mohsen/codes/amlak/amlak/src/ui/interface/interface.py",
line 109, in responseToRequestForData
self.materialsObejct.findData(self.objectSearchMaterials,self)
File "/home/mohsen/codes/amlak/amlak/src/materials/materials.py", line
133, in findData
rowCounter =
rowCounter.filter(and_(getattr(MaterialsTable,attr).like("%%%s%%" %
val))).count()
AttributeError: 'long' object has no attribute 'filter'
But when i use just one field it use rowCounter as integer and real return.
My question is , how can i adapt it with multiple field?Such as : Where
name = 'barak' and id != 3 But one filed such as : Where name = 'barak'

### ASP.Net exceptions sending large attachment

ASP.Net exceptions sending large attachment

I'm running the following code in ASP.Net on IIS:
try
{
Response.Clear();
Response.ContentType = "application/zip";
"attachment;filename=MyBigFile.zip");
Response.TransmitFile(Server.MapPath("~/Stuff/MyBigFile.zip"));
Response.Flush();
}
catch (Exception ex)
{
}
However it often throws the exception:
The remote host closed the connection. The error code is 0x800703E3.
Why is this, and how can I prevent it?

### Insert query with slash in a varchar field with php

Insert query with slash in a varchar field with php

I have this query in a php variable:
insert into activadosmil` set cod='TAB08-150', stock='5',
descripcion='YARVIK JUNIOR 8" A9 1GB 8GB KIDO'Z ANDRO',
ean='8717534019003', canon='111.23', fabricante='YARVIK'
And it brokes on descripcion='YARVIK JUNIOR 8" A9 1GB 8GB KIDO'Z ANDRO'
How can i replace the ' in php for the code i need to use for mysql??

### What was the font smoothing for GOOGLE HTML?

What was the font smoothing for GOOGLE HTML?

Hey guys what was the font smoothing for google chrome I cant seem to find
it, here is my code:
-webkit-font-smoothing: antialiased !important;
-moz-font-smoothing: antialiased !important;
text-rendering: optimizeLegibility !important;
What is the font smoothing for google?

### Should I use Telerik Kendo UI Upload or Telerik MVC extensions Upload

Should I use Telerik Kendo UI Upload or Telerik MVC extensions Upload

I have an ASP.NET MVC web application. In one of views users will select
multiple files and attach and upload. I have license for both. I used the
Kendo Upload to try it out and it works fine. Then I realized that Kendo
UI is geared towards mobile application. In my local environment this
upload is working fine but should I use the MVC extensions upload since
its specifically for web applications? My intranet application is not used
via mobile devices.

I am adding a link to a dialog box which I have done, but I have an issue
where it is bringing in part of the URL which I don't want from Apache. I
need the link to go straight to the page.
The code is below:
<h:outputText escape="false" target="tut"
The problem is that the link will need to be frequently updated within the
database. So the text TUTORIAL_LINK points to a link in the database and
the escape='false' takes the HTML away and this should go straight to the
http://localhost/navigate/http://www.tutoriallink.com where as I need it
Is there a better way of doing this?
Thanks.

## Wednesday, 11 September 2013

### Queries related to browser cache

Queries related to browser cache

I am using browser cache to store my response data, but wanted to know how
feasible it is to store the data in browser cache. Can anyone explain the
following:
1. Is their a guarantee that the data will be cached for specific time, if
I am storing only JSON data(can be huge).
2. What is the maximum size limit of browser cache.
3. Is my data cross domain accessible?If yes is their a way I can protect it?
4.Does the result vary from browser to browser?

### date picker is not hiding after selecting date. I want to hide calandar after selecting date and at the same time i want to call a function

date picker is not hiding after selecting date. I want to hide calandar
after selecting date and at the same time i want to call a function

date picker is not hiding after selecting date. I want to hide calandar
after selecting date and at the same time i want to call a function.
I am calling function at the time of selecting date, because onchange
event is not raising after changing the text box value to new date.
I have written code like this,
$('input:text[id^=ExpireDate]').datepicker({ //- onSelect: function(dateText, inst) {$(this).val(dateText);
fun2(id,expireDate);
}
});
fun2(id,date)
{
//--
}

I have a Google Maps page that I am looking to optimize as it is heavily
used. Currently, the user does the following to search:
Types an address, and clicks submit.
map.php is loaded, and javascript is executed to display the map.
This javascript submits a request to the webserver based on the searched
location, retrieves an xml file, and displays the results on the map.
The xml file request can take a signficant amount of time (a few seconds)
due to external factors (api). I am hoping to request this xml file before
the page has fully loaded to speed up the request. Unfortunately, this
request uses a callback that has not been defined until an external asset
What is the best way for me to prefetch the xml file, and setup a callback
for a function that has not been loaded yet? Basically, I want to load the
xml file at the top of the page, and wait to call the callback function
until it has been retrieved.

### subsetting matrix with id from another matrix

subsetting matrix with id from another matrix

I am just beginning to learn R, so I apologize in advance for the
ambiguity of my syntax as well as the apparent simplicity. Also, if there
is a better way of doing the below, I really appreciate any suggestions
and recommendations.
I would like to subset the data of one matrix using data in a second
matrix. The columns of one matrix is labeled. For example,
area1 <-
c(9836374,635440,23018,833696,936079,1472449,879042,220539,870581,217418,552303,269359,833696,936079,1472449,879042,220539,870581,
833696,936079,1472449,879042,220539,870581)
id <- c(1,2,5,30,31,34,1,2,5,1,2,5,1,2,5,30,31,34,51,52,55,81,82,85)
mat1 <- matrix(area1, ncol=3, byrow=T)
mat2 <- matrix(id, ncol=3, byrow=T)
dimnames(mat1) <-list(NULL, c("a1","a2","a3"))
mat2 contains the ids for mat1, so the dimensions of the matrix are the
same (i.e., mat1[1,1] identifies mat2[1,1]. What I want is to create
submatrices of mat1 when the row with values c(1, 2, 5) shows up in mat2.
In this present mini example, submatrix 1 would have 2 rows of data,
submatrix 2 and 3 have 1 row each, and submatrix 4 would have 4 rows of
data from mat1. The number of rows between subsequent rows with 1,3,5
varies. Does this make sense?
Originally, the matrices were transformed from a dataframe, with id in one
column and area in a second column. I couldn't find a way to subset
variable rows between rows of 1 within a dataframe, which is why I
switched to a matrix.

### C# out of memory exception in wpf application

C# out of memory exception in wpf application

I am creating an application where I am getting live images from camera
and trying to put that on image control of wpf. But after some time it
will start throwing out of memory exception.
here is the code
try
{
imgControl.Dispatcher.Invoke(DispatcherPriority.Normal,
(Action)(() =>
{
using (MemoryStream memory = new MemoryStream())
{
lastImage.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.EndInit();
ImageSource imageSource = bitmapImage;
imgControl.Source = imageSource;
}
}));
}
catch (Exception ex)
{
//exception handling
}
is there a way I can reduce memory consumption and find a work around for
this out of memory exception?
Thanks

### How can I append a leading 0 in MVC 4 DateTime in an EditorFor HTMLHelper?

How can I append a leading 0 in MVC 4 DateTime in an EditorFor HTMLHelper?

I'm running into an issue in my MVC 4 application when using an input mask
in my edit view for a DateTime. The input mask that I'm using forces an
input to be formatted like: "MM/dd/yyyy HH:mm". This works great until an
edit it attempted.
An input of "09/11/2013 07:00" ends up looking like "91/12/0137 30:00" in
my EditorFor helper.
How can I force a "0" to append to a month and hour less than two digits?

### Android:How to show Time Counter in Decimal Format

Android:How to show Time Counter in Decimal Format

This question may make confusion ,so i am explain it below.
I have already create a counter for counting the time(Like how much time
people works).Its working fine with single characters (like 0:0:0), but i
want to display it in decimal (like 00:00:00). I had tried the below code,
but it works like the before .No changes yet.
private void timer() {
int locSec = 0;
int locMin = 0;
int locHr = 0;
DecimalFormat format = new DecimalFormat("00");
String formatSecond = format.format(locSec);
String formatMinute = format.format(locMin);
String formatHour = format.format(locHr);
sec = Integer.parseInt(formatSecond);
min = Integer.parseInt(formatMinute);
hr = Integer.parseInt(formatHour);
Timer T = new Timer();
timeCounter = (TextView) findViewById(R.id.tvDisplayCountDown);
@Override
public void run() {
@Override
public void run() {
timeCounter.setText("time= " + hr + ":"+ min + ":"+ sec);
sec++;
if(sec > 59){
sec = 0;
min = min + 1;
}
}
});
}
}, 1000, 1000);
}
where hr, min and sec are global variables and assigned as 0. But the
output is same as before: 0:0:0
helps and suggestions are appreciable.
Thank You

## Tuesday, 10 September 2013

### Code conversion from MVC to C# asp.net webforms

Code conversion from MVC to C# asp.net webforms

I found a nice code to resize image on server, But code is for MCV.
I have no experience in C# would like to know what change i need to make
to this code so that it i can call from image object of webform it self.
<img src="@Url.Action("ResizeImage", "Controller", new { urlImage =
"<url_image>", width = 35 })" />
public ActionResult ResizeImage(string imageUrl, int width)
{
WebImage wImage = new WebImage(imageUrl);
wImage = WebImageExtension.Resize(wImage, width);
return File(wImage.GetBytes(), "image/png");
}
public static class WebImageExtension
{
TransparencyFormats =
new Dictionary<string,
ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png",
ImageFormat.Png }, { "gif", ImageFormat.Gif } };
public static WebImage Resize(this WebImage image, int width)
{
double aspectRatio = (double)image.Width / image.Height;
var height = Convert.ToInt32(width / aspectRatio);
ImageFormat format;
if (!TransparencyFormats.TryGetValue(image.ImageFormat.ToLower(),
out format))
{
return image.Resize(width, height);
}
using (Image resizedImage = new Bitmap(width, height))
{
using (var source = new Bitmap(new
MemoryStream(image.GetBytes())))
{
using (Graphics g = Graphics.FromImage(resizedImage))
{
g.SmoothingMode =
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, width, height);
}
}
using (var ms = new MemoryStream())
{
resizedImage.Save(ms, format);
return new WebImage(ms.ToArray());
}
}
}
}

### how t o display image from url use pligg cms2.0

how t o display image from url use pligg cms2.0

the modifier $string = preg_replace('/(http://|https://){1}.+?.(jpg|gif|bmp|bnp|png)$/is','<img
src="$0" alt="" />',$string);
return \$string;
How can I write in the link_summary.tpl
thanks

### I don't know how to install ThreeJSExporter.ms

I don't know how to install ThreeJSExporter.ms

I have no idea where I should place this script or how I should execute it?
My end goal is to be able to export 3ds files directly to JSON to be
imported into threejs.
I'm a noob with 3ds so please forgive my ignorance.