Saturday, 31 August 2013

Yeoman Using AngularJS with php slim

Yeoman Using AngularJS with php slim

Im planning to do a big application with Angularjs and php slim in the
backend for the rest services and I wonder if exist a generator to use
yeoman with angularjs+slim without coffee script just plain javascript. Im
using windows and yeoman now run fine with the angular generator but have
no clue how to integrate the yeoman workflow with php slim and use grunt
to serve slim. thanks in advance.

Needs help in looping and to remove duplication

Needs help in looping and to remove duplication

helo everybody, I developed a code to search "-" and "/" and then to
compare and arrange them .. But unfortunatly, it only works for two
strings to compare and if more than two strings compared by loop, it gives
redundent data .. Help me, Thankx in anticipation ..
for($x=1, $y = 2; $x<$arrlength, $y<$arrlength; $x++, $y++) {
switch ($sort[$x])
{
case (strncasecmp($sort[$x],$sort[$y],strpos($sort[$x],'-')) == 0):
if
(substr(substr($sort[$x],0,strpos($sort[$y],'/')),0,strpos($sort[$y],'-'))
== false ){
echo " <TH class=\"tr1 td26\"><table><caption><P class=\"p16
ft4\">".substr($sort[$y],0,strpos($sort[$x],'-'))."</P></caption></table>";
echo "<P class=\"p12
ft4\">".ltrim(substr($sort[$x],strpos($sort[$x],'-')),"-")."</p></TH>";
echo " <TH class=\"tr1 td26\"><P class=\"p12
ft4\">".ltrim(substr($sort[$y],strpos($sort[$y],'-')),"-")."</P></TH>";
}
else {
echo " <TH class=\"tr1 td26\">";
echo " <table><caption><u><P class=\"p16
ft4\">".rtrim(rtrim((ltrim(substr(substr($sort[$x],strpos(strpos($sort[$x],'-'),'/')),strpos($sort[$x],'/')),"/")),ltrim(substr($sort[$x],strpos($sort[$x],'-')),"-")),"-")."</p><u></caption></table>";
echo "<P class=\"p12
ft4\">".ltrim(substr($sort[$x],strpos($sort[$x],'-')),"-")."</p></TH>";
echo " <TH class=\"tr1 td26\"><P class=\"p12
ft4\">".ltrim(substr($sort[$y],strpos($sort[$y],'-')),"-")."</P></TH>";
}
break;
case (strncasecmp($sort[$x],$sort[$y],strpos($sort[$x],'-')) <= 0):
echo " <TH class=\"tr1 td26\"><P class=\"p12
ft4\">".$sort[$x]."</P></TH>";
break;
case ((strncasecmp($sort[$x],$sort[$y],strpos($sort[$x],'/')) == 0) &&
(substr(substr($sort[$y],0,strpos($sort[$y],'/')),0,strpos($sort[$y],'-'))
!== false )) :
echo " <P class=\"p17
ft4\">".substr($sort[$y],0,strpos($sort[$x],'/'))."</P>";
break;
}
}

haskell program to remove part of list and print the rest

haskell program to remove part of list and print the rest

How do i remove part of a list in haskell. This is what i have done so
far.Please tell me what are the changes that can be made:
enter code here
import Data.Lists
import Data.List.Split
removePrefix :: Eq t => [t] -> [t] => Maybe [t]
removePrefix [][] = Nothing
removePrefix ts[] = Just t's
removePrefix(t:ts)(y:ys) = if inTnFixOf(y:ys)(t:ts) == True
then SrtipPrefix(y:ys)(t:ts)
else Just [(x:xs)]
Example output : input"toyboat" output "boat"

AJAX POST request in JSON login

AJAX POST request in JSON login

I'm trying to create a very simple login form using AJAX for server
comunication and PHP as a server-side script. As a starting point I was
just trying to send the login data to the server via JSON, but it already
gave me issues.
Problem is, when I send the data with a POST request in AJAX my server
doesn't seem to get anything and returns no data at all. Here's the HTML
for the request:
<!DOCTYPE HTML>
<html>
<head>
<title> Login experiment </title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(
function AjaxJSON(){
$("form#loginForm").submit(function() {
var username = $('#username').val();
var password = $('#password').val();
var jsonlogin = "{\"username\" : \"" + username + "\" , \"password\" : \""
+ password + "\"}";
var str='json='+jsonlogin;
$.ajax({
type: 'POST',
url: 'login.php', // URL of my PHP script
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: str,
success:function(data){alert("Data received!"+data);}
}); // ajax
}
)
}
)
</script>
</head>
<body>
<h1> LOGIN: </h1>
<form id="loginForm" name="loginForm" method="post" action="">
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="submit" class="button positive">
</form>
</body>
</html>
This HTML code should simply send the request form (username+password)
coded in a JSON string to the PHP script. The script is something like
this:
<?php
$result = json_decode($_POST['json']);
echo $result->username;
echo " ";
echo $result->password;
?>
Why doesn't it show me any reply? Thank you in advance for your help :)

Is this a bad practice to include the minified jQuery and the plugins in a single file with my script?

Is this a bad practice to include the minified jQuery and the plugins in a
single file with my script?

We are developing a certain plugin that will be used on the websites of
multiple customers, and we won't be able to control the pages where it
will be included. We are using jQuery a lot, with a number of plugins,
and, of course, we do it in the noConflict mode to allow our customers
keep their jQuery version if they are using it. That, however, requires
that jQuery and all the other dependencies are loaded before our plugin,
so that makes for several <script /> tags and several HTTP requests. It's
very tempting to minify all the dependencies (jQuery and jQuery plugins)
and concatenate it with our own plugin into a single file.
Would that be a bad practice or is it the precise way this should be done?

CSS hover off of element should trigger opposite transition

CSS hover off of element should trigger opposite transition

I have a div with a "+" in it which does this on hover:
.removal {
opacity: 0;
filter: alpha(opacity=0);
margin-left: -10px;
display: inline-block;
-webkit-transform: rotate(0deg);
-webkit-transition: -webkit-transform 0.5s ease-in-out;
}
.term:hover .removal {
position: relative;
left: 13px;
opacity: 1;
color: red;
-webkit-transform: rotate(45deg);
-webkit-animation: move 0.4s;
}
@-webkit-keyframes "move" {
from {
left: 3px;
filter: alpha(opacity=0);
opacity: 0;
}
to {
left: 13px;
filter: alpha(opacity=100);
opacity: 1;
}
}
The problem I'm experiencing is when I mouse off of that li, I'd like the
CSS to essentially undo the animation found in move.
Any tips on how to do this? Should I add a transition to .term (which is
the class on the li)?

How to create PHI node in LLVM , make use of the PHINode class and StoreInst class

How to create PHI node in LLVM , make use of the PHINode class and
StoreInst class

Original LLVM IR code
if.then: ; preds = %entry
....
%sub = fsub float %tmp11, %tmp14
store float %sub, float addrspace(1)* %arrayidx4, align 4
br label %if.end
if.else: ; preds = %entry
....
%sub7 = fsub float %tmp19, %tmp22
store float %sub7, float addrspace(1)* %arrayidx4, align 4
br label %if.end
if.end: ; preds = %if.else,
%if.then
ret void
I have stuck here for a long time , i don't know how to make use of the
PHINode class and StoreInst class. I have trace the llvm source code but
still don't know how to do..
Now i want to merge this two store instruction.
Like this ...
if.then: ; preds = %entry
....
%sub = fsub float %tmp11, %tmp14
br label %if.end
if.else: ; preds = %entry
....
%sub7 = fsub float %tmp19, %tmp22
br label %if.end
if.end: ; preds = %if.else,
%if.then
%storemerge = phi float [ %sub, %if.then ], [ %sub7, %if.else ]
store float %storemerge, float addrspace(1)* %arrayidx4, align 4
ret void
Can anyone teach me how to do it ?? Thanks in advance ...

What flaws might be present in my chat database design?

What flaws might be present in my chat database design?

I have designed a chat(in .net) database design(in mysql) and i am not too
sure if its gonna survive in long run. This is meant for a chat which has
features same as facebook have.
My tables and column would be like this: Each table consists 7 default
columns other than the ones mentioned below, and the default columns are
present in all tables, the default column are: 1>timestamp column
2>active/inactive column 3>added by/ modified by 4>added by
datetime/modified by datetime 5>ip_address 6>mac_address 7>identity column
and the tables are
Tables Columns
Chat_session_detail Session_id (Remarks:1 session means when the 1st user
sends the 1st message and the session ends when the user exit the chat
box)
Chat_session_user_detail Session_id member_id(Remarks:all members tagged
in the chat session)
chat_message_detail Session_id message_id message
Chat_attachment_detail message_id attachment_file_type(Remarks:if message
is smiley or audio file or any other files) attachment_path
chat_receiver_detail message_id receiver_id

Friday, 30 August 2013

Convert numbers to alphabet in Python

Convert numbers to alphabet in Python

Hi i'm new to python and i read this thread: Convert alphabet letters to
number in Python about converting alphabet to numbers but i don't
understand how to convert the numbers back into alphabets i would
appreciate if someone could expand on that, more specifically the chr
function described in the thread. I've already tried searching up the chr
function but there aren't alot of tutorials on it. Thanks in advance

Thursday, 29 August 2013

how to make screen capture fast with robot class?

how to make screen capture fast with robot class?

I'm developing screen sharing application using java. The app uses
client-server-client technique to transfer data. I want to know what
should be done to transfer frames fast? I used image compression and video
record and play mechanism so far but yet its slow. please suggest me other
techniques to make transfer faster.

Javascript modification at the browser Interface

Javascript modification at the browser Interface

Is it possible to modify javascript source code on a https connection
before it gets executed by the browser. This modification doesn't have to
necessarily come from a man-in-the middle. It can also come from the
intended recipient of the script. Also, is there a particular type of
request that cannot be made to a PHP server using cURL? In other words,
what are the limitations of cURL?

Crystal Report column font set Dynamically based on a condition

Crystal Report column font set Dynamically based on a condition


I am using Crystal Report for generating Reports.
I have to set the font size and color of "Test Result" column based on
"Noramal Range" column.
if "Test Result" (12) is in range of "Normal Range"(12-13) then
size =15 and color =red
else
size =10 and color =Green
Both Columns are in Details section of Crystal Report and i have assigned
value to it using set data source property of Crystal (
rpt.SetDataSource(ds1.Tables[0]))
I have used
FieldObject field;
field = rpt.ReportDefinition.ReportObjects["TestResult1"] as FieldObject;
Font fo = new Font("Arial Black", 15F, FontStyle.Bold);
field.ApplyFont(fo);
field.Color = Color.Red;
But this gets applied to the whole column and not to a particular Row.
Please Help.

Wednesday, 28 August 2013

Using dllmap on monomac

Using dllmap on monomac

I'm trying to use a custom build of sqlite with MonoMac, effectively as
per this question.
However, using dllmap doesn't seem to be working.
My custom dylib is being deployed into
[myapp.app]/Contents/Frameworks/mycustomlib.dylib
Output of otool -L mycustomlib.dylib looks correct:
@executable_path/../Frameworks/mycustomlib.dylib (compatibility version
0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version
169.3.0)
My myapp.exe.config file looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<dllmap dll="sqlite3"
target="@executable_path/../Frameworks/mycustomlib.dylib"
os="!windows" />
</configuration>
And I have verified that it is being copied alongside myapp.exe in
[MyApp.app]/Contents/MonoBundle.
I can force this to work by recompiling Mono.Data.Sqlite and directly
replacing the reference to sqlite3 with mycustomlib. However, the dllmap
route is much nicer.
What am I missing? How can I debug this?

In Symfony2, how to use Multiple Routes in Default Controller

In Symfony2, how to use Multiple Routes in Default Controller

I've been trying to map multiple routes to the default controller, and it
doesn't seem to be working as expected.
I'm using annotations in my controller:
/**
* @Route("/", name="index_controller");
* @Template("SeoSlinkyBundle:Default:index.html.twig");
*/
public indexAction() {}
but I want to do this:
/**
* @Route("/", name="index_controller");
* @Route("/{timeoption}", name="index_controller");
* @Template("SeoSlinkyBundle:Default:index.html.twig");
*/
public indexAction($timeoption = "today") {
echo $today;
exit;
}
That actually works, and if I go to:
http://myapp/hello
The controller echoes "hello"
but if I go to
http://myapp/
The controller should echo "today"
but instead I'm getting this error:
Cannot import resource "/usr/share/www/myapp/src/MyAppBundle/Controller/"
from "/usr/share/www/myapp/app/config/routing.yml".
These are the contents of routing.yml
my_app:
resource: "@MyAppBundle/Controller/"
type: annotation
prefix: /
imag_ldap:
resource: "@IMAGLdapBundle/Resources/config/routing.yml"
Any help would be greatly appreciated!

Pushing SKB to the network stack

Pushing SKB to the network stack

I have net_device which has the ndo_start_xmit function implemented.
When ndo_start_xmit function called I have an skb that contains the IP
packet. I'll need to overt the packet with IP+UDP headers and send it back
to the routing system.
The problem is that when I call the dst_input(skb) or dst_output(skb) I'll
catch the NULL pointer dereference error. It seems that I can't use this
functions to push the encapsulated packet into the network stack.
Can anybody helps me with the solution?

regex to add hypen in dates

regex to add hypen in dates

In R I have a character string that looks like the following
x <- c("20130603 00:00:03.102","20130703 00:01:03.103","20130804
00:03:03.104")
I would like to to look like the following by using a single gsub command
(rather than using substr and paste, but my limited regex knowledge is
frustrating me in working out what i need to do to do so:
y <- gsub([REGEX PATTERN TO MATCH],[REPLACEMENT PATTERN TO INSERT HYPHEN] ,x)
> y
[1] "2013-06-03 00:00:03.102" "2013-07-03 00:01:03.103" "2013-08-04
00:03:03.104"
In my actual example, x has a length of several million, so any
microbenchmarking for speed improvements would be helpful.
As always, any help would be greatly appreciated.

Tuesday, 27 August 2013

Ajax post in oscommerce

Ajax post in oscommerce

I'm trying to update my database on the event of a change in my select
box. The php file I'm calling on to process everything, works perfectly.
Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I
cannot connect to the database because: ' . mysql_error());
mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry
will be updated under the products table, ex:
www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name +
'=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time
I've ever used anything other than serialize, so any pointer would be
appreciated!

Console use CAPS for user input

Console use CAPS for user input

im creating a tic tac toe game with c# console application (still
learning) and wanted to know if it is possible to change the user input
from an "x" to an "X" ? Because it looks better ...
Thank you for your help

Unity3d drawing sector of texture by deg

Unity3d drawing sector of texture by deg

I am using unity3d. I want to draw sector of texture by deg. How to show
sector of texture using Shader?

Don't raise OnPropertyChanged when deserializing

Don't raise OnPropertyChanged when deserializing

Let's say I have this class :
[XmlType]
public class TestModel : BindableBase
{
private int _id;
[XmlElement(Order = 7)]
public int Id
{
get
{
return _id;
}
set
{
SetProperty(ref _id, value);
}
}
}
I am doing a lot of serialization and deserialization (from/to Json with
newtonsoft and from/to byte arrays with protobuf) and I would like to
avoid calling the SetProperty method when setting the property during the
deserialization.
Basically I would like to have something along the line with:
[XmlElement(Order = 7)]
public int Id
{
get
{
return _id;
}
set
{
if(!serializing)
SetProperty(ref _id, value);
else
_id = value;
}
}
The reason I want to do this is because first I don't need the event
OnPropertyChanged to be raised during deserialization and secondly because
it is costly in terms of performance.
I tried using the OnDeserializing and OnDeserialized to set a flag but
while OnDeserialized lets me know when the deserialization is over
(methods decorated with OnDeserializing are not called just before the
deserialization but during the operation).
This code is in a Portable Class Library assembly so I cannot use
SerializationContext.
Any clues/hints are welcome!

Refering app config kept at different layer

Refering app config kept at different layer

I am trying to implement the onion architecture. I want two clarity as I
am not getting the sure shot reason and way to do so:
Why we should use the Infrastructure layer and what all exactly should be
present in this layer?
Can we keep app.config in this layer. If yes then how entity will refer
the app.config?

Slow speed on Realtek PCIe FE Family Controller - HP Pavilion 64 bit

Slow speed on Realtek PCIe FE Family Controller - HP Pavilion 64 bit

I recently upgraded my internet speed to 90 mbs but when I run a speedtest
on my computer, it never gets over 50 mbs. I've had the ISP company over
here a few times, they've tested everything and have shown that the
internet speed is in fact 90 mbs and sometimes even 100 mbs but their
thought is that my ethernet and wireless ports on my HP can't accept or
run at those faster speeds. Also, just to confirm my speed, I connected
the ethernet to a dell laptop and sure enough, it's running at the 90 and
100 mbs.
I've tried playing around with the settings on the network adapter Realtek
PCIe FE Family Controller, adjusting to auto, 100/Full Duplex, 100/Half
Duplex, 10/full, 10/half but my internet speed never changes. So, is there
a setting or some other update for this issue?

Monday, 26 August 2013

Is there a free web based tool to view the database schema and its properties

Is there a free web based tool to view the database schema and its properties

Is there a free web based tool (I prefer Microsoft because I have an MSDN
account) to view the database schema and its properties? I'm currently
using Visio but I dont know if it's possible in Visio to do the following:
View the database schema that I will upload in a Sharepoint workspace.
If I click the name of the Database table, it will either pop up a small
window with its database properties and column description or another
window will pop up with its database properties and column description.
For example I have a Schema table interface composed of a profile and time
tables.
THESE ARE JUST EXAMPLES.
ProfileDim table
Profile ID number(10)
FirstName varchar (20)
MiddleName varchar (20)
LastName varchar (20) TimeDim Table
DateHired datetime---------------EmployeeStartDate datetime,
Date_Name nvarchar(50),
Year datetime,
If I click the name "TimeDim" it will take me to another page where I can
see the database properties written below and the description of each
column. I prefer not to use MS excel or word. I want a tool that I could
edit, delete in case I want to add another column, change the data type
and change the name etc.
TimeDim table
COLUMN NAME DATA TYPE ALLOW NULLS DESCRIPTION
EmployeeStartDate datetime, Unchecked "START DATE OF THE
EMPLOYEE"
Date_Name nvarchar(50), Checked "CURRENT DATE NAME"
Year datetime, Checked "NAME OF THE CURRENT
YEAR"

forloop in python pig latin translator

forloop in python pig latin translator

I've been trying to work on a pig latin translator in python and I had
setup a forloop to loop through each character of a user-entered string.
To test that the forloop is successfully catching all the consonants that
follow the initial consonant until it hits a vowel(e.g. "str" in the word
"string"), I had written a print statement to print out all of these
consecutive consonants in a word that begins with a consonant.
Unfortunately, the forloop only omits the letter "a" but allows the vowels
"e" "i" "o" and "u" to be printed.
So my question here is how can I fix this code so that only the first
string of consonants until the first vowel of the entered word?
I'm not particularly equipped with the language to describe the process by
which I'm doing this but hopefully this plea is a close enough
approximation that helps express the nature of the problem. Thanks.
code:
def translate():
print("Welcome to the Pig Latin Translator")
original=raw_input("What word would you like to translate?")
length=len(original)
move_letters=""
index=0
for i in range(length):
if original[i]!=("a" or "e" or "i" or "o" or "u"):
print(original[i])
move_letters=move_letters+original[i]
index+=1
translate()

Swap images with single button JavaScript function using %

Swap images with single button JavaScript function using %

Fellow Programmers! A wonderful afternoon (or whatever the case) to you!
With some assistance of fellow users I was able to manage getting an image
to change back and forth between a second image every couple seconds. It's
awesome! So I counted out some of the math with the % operator, and sure
enough when the image first displays, I get the default broken link image
of the browser, but after the 2 seconds everything goes as planned. So
begins this investigative experiment. I decided instead of swapping
automatically, lets make the swap with a button as to be able to
investigate the page as long as I would like. But who want's to do the
exact same thing again, why not learn another cool trick along the way.
That trick is to display both of the images at the same time, such that
when the button is clicked they swap places. Same math, different effect
for the user. Isn't that awesome!
The goal: display two images and below them one button. When the button is
clicked the images are to swap places. The images that was on the left
should be on the right, the one on the right ought now be on the left. Use
no jQuery, this is after all a JavaScript experiment (and I have yet to
learn much jQuery but I can't wait to get there!)
Browser error console messages: Interestingly enough firefox give me
nothing. I open the browser, load the page in it from VS 2012 clear the
error conslole, refresh the page. And nothing. In chrome (my default
browser) however, I get a localhost pic src 404 not found. I find this
strange because this code is on a page that happens to have other code
which references those same pictures and works fine. The 2 second auto img
flip thing being some of that other code.
debugging:I'm to much of a noob to know what's going on with that. I get
the basic Idea and looked into it some. On the VS site there's all this
info about setting breaking points and running multiple instance of VS to
do something with another engine. I will soon be on youtube to hammer that
out. I apologize however, if there is some simple debug fix to this and I
should have witnessed it. Hammering through my 2nd web class and that
topic has not been covered :(
Here are articles that I found similar to my question. This was helpful to
see how they had set up the if else: Swap Image with onclick not
responding all in all that turned out to be more that I could read,
clearly the writer is more advanced than I. a second: javascript swap text
block onclick anchor link a bit of an information overload I think. There
was a lot going on with that, but I never managed to change any of my code
after reading through it.
If your curious here is the VS article I briefly mentioned:
http://blogs.msdn.com/b/visualstudioalm/archive/2013/06/28/javascript-native-interop-debugging-in-visual-studio-2013.aspx
And here is my code:
<script type="text/javascript">
function swap_pics() {
var c = 1
//I had:
//var andy_arr = ["andy_white.jpg","andy_black.jpg"];
var andy_src1 = "andy_left.jpg";
var andy_src2 = "andy_right.jpg";
c = ((c + 1) % 2);
if (c == 0) {
//I was using an array which looked like:
// document.getElementById('andy_left').src =
"andy_arr[0]";
// document.get ... _right').src =
andy_arr[Math.abs(c-1)];
//0-1 abs = 1
//1-1 = 0, so It looks like it should now toggle.
document.getElementById('andy_left').src = andy_src1;
document.getElementById('andy_right').src = andy_src2;
}
else {
document.getElementById('andy_left').src = andy_src2;
document.getElementById('andy_right').src = andy_src1;
}
}
</script>
<div id="mini_lab_5">
<img src=""
id="andy_left"
height="100"
width="100"
/>
<img src=""
id="andy_right"
height="100"
width="100"
/>
<br />
<input type="button" value="Swap"
onclick="swap_pics();
"/>
</div>
Thanks for being a part of the community and making it great!

List of common sources and destinations

List of common sources and destinations

I have a class for representing a source file and a destination of where
it will be copied:
public class SourceDestination
{
public string Source { get; set; }
public string Destination { get; set; }
}
I created a list of SourceDestination and I'm attempting to find sub-lists
from this list where multiple source files go to the same destination and
multiple destinations receive the same source files.
For example, if file A and B go to destination C, D and E and file F and G
go to destination C and D, then A, B, F and G share two of the same
destinations, C and D.
Since the SourceDestination class is a source and destination pairing, how
would I achieve this sort of set operation in Linq?

How to nest monad transformers correctly?

How to nest monad transformers correctly?

Imagine I have a function
calc_set :: Context
-> Term
-> StateT FreshName (EitherT String Identity) (Type, Set)
The intuition is that this function will take a context, a term, a
generator of fresh names, and will produce some complex result. However, I
can't seem to write it! One case for terms would look like this:
calc_set ctx (TmVar i) = return (getTypeFromContext ctx i, emptySet)
However, it won't typecheck because getTypeFromContext has type
getTypeFromContext :: Context -> Index -> Either String Type
Okay, I re-write it as
calc_set ctx (TmVar i) = do
a <- getTypeFromContext ctx i
return (a, emptySet)
and it doesn't work, because the compiler Couldn't match expected type
'StateT String (EitherT String Identity) t0' with actual type 'Either
String Type'... and I have no idea how to turn Either String Type into
EitherT String Identity. What do I do?
I am not even sure I have the order of transformers correct. May someone
recommend an elaborated tutorial on monad transformers?

sed insert line with spaces to a specific line

sed insert line with spaces to a specific line

I have a line with spaces in the start for example " Hello world". I want
to insert this line to a specific line in a file. for example insert "
hello world" to the next file
hello
world
result:
hello
hello world
world
I am using this sed script:
sed -i "${line} i ${text}" $file
the problem is that i am getting my new line with out the spaces:
hello
hello world
world

Sunday, 25 August 2013

Spring MVC session Attribute set intially

Spring MVC session Attribute set intially

I have used the Spring MVC. I set the Session Attribute value like
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String initHome(Model model) {
if (!model.containsAttribute("clientObject")) {
model.addAttribute("clientObject", createDefaultClient());
}
return "homeMenu";
}
It is working fine if i click the home menu url(/home). but if i did not
go the home means it says error as 'session attribute clientObject is
required'
so i decided to set sessionattibutes in constructor of controller
@Autowired
public MyController(Model model) {
if (!model.containsAttribute("clientObject")) {
model.addAttribute("clientObject", createDefaultClient());
}
}
it also says error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'myController'
I tried to set using the RequestMapping also like
@RequestMapping(value = "/", method = RequestMethod.GET)
public void initController(Model model) {
if (!model.containsAttribute("clientObject")) {
model.addAttribute("clientObject",
createDefaultClient());
}
}
this method is also not called intially my cointroller look like
@RequestMapping("/sample")
public class MyController {
..
..
is it possible to set the sessionAttribute value in the constructor of
controller? or any other way to set the session Attribute initially?
Thanks in advance for your help.

Can't get text from another class to print out on another one (noob)

Can't get text from another class to print out on another one (noob)

I posted this code earlier, and I got alot of helpful answers and the
majority was that I need to change my code completely. Which I understand,
and I will do tomorrow! But right now, this is eating away at me at why
this won't work.
I am trying to get the sendText from the ChatBox class, to my
MessageWindow class and output in the messagePane. That's it. It seems so
simple, and it probably is...but I have literally been at this for 10
hours straight. I just want it to output what I put in the ChatBox to the
MessageWindow, without completely changing my code. Please help :(
public class ChatBox extends JPanel {
private JScrollPane scrollPane;
private String sendText;
public ChatBox() {
final JTextArea chatPane = new JTextArea();
scrollPane = new JScrollPane(chatPane,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scrollPane);
scrollPane.setMinimumSize(new Dimension(550, 50));
scrollPane.setPreferredSize(new Dimension(550, 50));
chatPane.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if( e.getKeyCode() == KeyEvent.VK_ENTER ) {
sendText = chatPane.getText();
setText(sendText);
chatPane.setText(null);
// System.out.println(sendText); // I can see this in console
}
}
@Override
public void keyTyped(KeyEvent e) {
}
});
}
public String getText() {
return sendText;
}
public void setText(String sendText) {
this.sendText = sendText;
}
}
In my head, I am setting the sendText -> whatever I input. Then in the
MessageWindow class, I am trying to use the getter to get the text and
output in the messagePane.
public class MessageWindow extends JPanel {
private ChatBox box = new ChatBox();
public MessageWindow() {
JTextArea messagePane = new JTextArea();
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = 1;
gc.weighty = 1;
gc.fill = GridBagConstraints.BOTH;
gc.insets = new Insets(5, 5, 5, 5);
add(new JScrollPane(messagePane), gc);
System.out.println(box.getText()); // Getting null in the console.
messagePane.append(box.getText()); // Not getting anything on
messagePane.
}
}
I know I need to use ActionListeners and a JTextField, instead of a
JTextArea. And I promise I will start that tomorrow. I will scrap this
whole program as it is, I just need to know why this basic things fails me
:( I knew while I was learning Java that getters/setters were going to be
a problem for me to completely understand, and I guess I am right about
that lol...
Thanks for any help!!!

Free Timsh in The Brigmore Witches?

Free Timsh in The Brigmore Witches?

In The Knife of Dunwall, I decided to have Barrister Arnold Timsh arrested
(the dastard had it coming).
Now, I'm in Coldridge Prison and Timsh is asking me to get him out,
telling me that this is the chance of my life.
Although I'm financially self-sufficient, I guess a little extra coin
couldn't hurt, but I don't really trust Timsh to uphold his end of the
bargain, and I'm worried about my reputation too; also, it would be
pointless to free him, if he's just going to get himself killed by the
guards.
What are the consequences of freeing Timsh? Will I have to expect
retaliation from his niece, Thalia? What about Wiles Roland?
Will Timsh ever find out it was me who sent him there in the first place?

why the gcc user the Absolute path for inc and lib

why the gcc user the Absolute path for inc and lib

I am build a arm cross compile use gcc + eglibc.I build it success.and can
use it build kernel and app. But when I move the cross compile tools to
another dir.it can't working. like this program: enter code here#include
enter code hereint main(void) enter code here{ enter code herereturn 0;
enter code here} user arm-grg-linux-gnueabi-gcc compile this, it is out
can't find stdio.h
I just mv tools/{cross compile} to tool/{cross compile}
so I want somebody help me how modify the gcc default dir to Relative
path. so i can copy this tools to my parter.
thanks!

Saturday, 24 August 2013

Objective-C: Accessing int value from another class

Objective-C: Accessing int value from another class

I am having trouble accessing an int property from another class. I know
this question has been asked quite a few times however none of the
solutions posted in previous questions seem to work. My knowledge in xcode
is basic, and I am using this project to develop my skills.
The two classes I have are: HelloWorldLayer and ClassOne. Where ClassOne
states the value of int. Both are Cocos2d CCLayer classes (probably not
the best class to practice inter-class value access).
ClassOne.h
@interface ClassOne : CCLayer {
int ageClass;
}
@property (nonatomic, readwrite)int ageClass;
@end
ClassOne.m
@implementation ClassOne
@synthesize ageClass = _ageClass;
-(id)init{
if((self=[super init])){
_ageClass = 10;
}
return self;
}
@end
HelloWorldLayer.h
#import "ClassOne.h"
@interface HelloWorldLayer : CCLayer <...> {
ClassOne *agePointer;
}
@property (nonatomic,assign)ClassOne *agePointer;
+(CCScene*)scene;
@end
HelloWorldLayer.m
#import "HelloWorldLayer.h"
#import "AppDelegate.h"
#import "ClassOne.h"
@implementation HelloWorldLayer
@synthesize agePointer = _agePointer;
+(CCScene*)scene...
-(id)init{
if((self=[super init])){
_agePointer.ageClass = self;
NSLog(@"ClassOne int = %@",_agePointer);
}
return self;
}
...
@end
Output Result:
"ClassOne int = (null)"
or "0" if i use "%d" token and "int = x", where the line "int x
=_agePointer.ageClass;"
is used.
The result I am after is for the HelloWorldLayer NSLog to display "10",
the int value defined in ClassOne.
Any wisdom and corrections on my use of language is greatly appreciated.

Are discrete sets open?

Are discrete sets open?

Iff a metric space $M$ has the property that every intersection of open
sets is open, prove M is discrete.

How to get a segment of file on http, in Clojure using libraries like clj-http or http-kit?

How to get a segment of file on http, in Clojure using libraries like
clj-http or http-kit?

To get a portion of a file on a http server, one can send a GET message
with range headers -- well assume you know the server supports that. To
implement this in Java code, I know can use Java's HttpURLConnection api
or Apache's HttpClient library, so technically I can do that in Clojure
too, using Java interop. However, I want to implement this in a Clojure
way. People on SO recommended me using Clojure libraries like clj-http or
http-kit, since these provide more Clojure-like apis.
I have searched on documentations of both libraries, and google as well,
but I couldn't find any information about sending range headers with GET
message. I wonder if these libraries even support that functionality or
not.
I also tried to guess the usage by sending these code to the REPL, but
none of them was working:
>(client/get link {:range [0 9]})
;; the server sent me response message with whole file, not the bytes from
0 to 9
>(client/get link {:range 0-99})
;; just didn't work; got error from REPL
Anybody know how to do that with these libraries?

Python calling a function

Python calling a function

I am trying to do one of the exercises from learn python the hard way and
am stuck on something. I created a function and in case one of the
statements is fulfilled I would like to put that in another function. This
is the outline of how I'm trying to do it:
def room_1():
print "Room 1"
button_push = False
while True:
next = raw_input("> ")
if next == "1":
print "You hear a click but nothing seems to happen."
button_push = True
elif next == "2":
print "You enter room 2"
room_2()
def room_2():
print "Room 2"
while True:
next =raw_input("> ")
if next == "1" and button_push:
print "You can enter Room 3"
room_3()
If button_push is fulfilled then I would like to see that in room_2. Could
anyone please help me with that?

Xcode: Temporarily disable indexing/auto-compilation?

Xcode: Temporarily disable indexing/auto-compilation?

Judging just from the amount of heat given off by the laptop, the
auto-indexing feature of Xcode is very CPU-intensive. It very often spikes
way above 100% on Activity Monitor, so it's clearly doing some things in
parallel as well. I'd like to do some C++/ObjC programming on the go, but
the machine won't last very long if the CPU is being thrashed like this.
Is there a mode I can throw it into so that it will be less aggressive
about this? If I disable it, I want to also be able to re-enable it easily
when I do get plugged in.

What to pass into file I/O method as Context argument?

What to pass into file I/O method as Context argument?

Feeling really stupid, and somehow I have a feeling I'm supposed to pass
"this" as the argument for "Context", but honestly this whole concept is
new to me and as confused as it has me I'd rather know 100% what and why
before I start my endless hunt of syntactical errors.
I had asked a question a few days ago about how to use a file input/output
stream to write the contents of an ArrayList of class objects to file to
be retrieved when the app starts. Basically, I wanted to save entered
values. I was feeling pretty confident in my code until I realized I have
to pass a Context when calling my save and retrieval methods. It was then
the realization I had no idea what a context was hit me... So yeah.
These are my methods: Create the file (I guess?):
private static void updatePickThreeList(Context mC){
FileOutputStream stream = null;
try{
stream=mC.openFileOutput(PICK_THREE_NUMBERS,Context.MODE_PRIVATE);
ObjectOutputStream dout = new ObjectOutputStream(stream);
dout.writeObject(pickThreeNumbers);
stream.getFD().sync();
stream.close();
dout.flush();
}catch(IOException e){
e.printStackTrace();
}
}
Retrieve the data (I hope):
private static void getPickThreeList(Context mC){
FileInputStream stream = null;
try{
stream=mC.openFileInput(PICK_THREE_NUMBERS);
ObjectInputStream din = new ObjectInputStream(stream);
pickThreeNumbers = (ArrayList<PickThreeNumbers>) din.readObject();
stream.getFD().sync();
stream.close();
din.close();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e1){
e1.printStackTrace();
}
}
And I assume I can call the first method to save the ArrayList to file,
then call the second method to simply load the saved values to the array.
By the way, the arrays and other values used are:
static List<PickThreeNumbers> pickThreeNumbers = new ArrayList();
final static String PICK_THREE_NUMBERS="pick_three_numbers";
So, per the response to my original question, both of these methods are
required to be passed in a context, and Java is being fairly adamant about
getting that context (go figure), so when I call
updatePickThreeList(Context);, what exactly goes in as the "Context"?
Thanks in advance - I'm one very appreciative programming noob.

How to force application to connect over SOCKS Proxy

How to force application to connect over SOCKS Proxy

I'm looking for idea how to connect client application over SOCKS server
on Windows XP
This client application don't have proxy support.
How to do it without proxifier,proxycap and other similar programs ?
(Application detect that programs and automatically closing)
My Proxy server is 127.0.0.1:54321
"Route" command work only for network adapters but not work for my socks
proxy. e.g.
route ADD 200.200.213.100 MASK 255.255.255.255 127.0.0.1 METRIC 30 IF 1
where 200.200.213.100 is server IP for application
code 1 is my main network adapter
This route command dont work for me

How do I power park?

How do I power park?

I've seen achievements, statistics and even the in game radio host mention
"Power Parking", but nowhere have I actually found instructions on how do
it. I have found carparks, and have launched myself off some of the roofs,
but this doesn't seem to have anything to do with Power Parking.
So how do you power park, and how is it scored?

Should learn angularjs without jquery?

Should learn angularjs without jquery?

I am newbie with client-side JavaScript. In one web project, I found about
angularjs and use some basic on this. Should I learn Jquery or just use
Angularjs for other project?

Friday, 23 August 2013

how to encode each link of my static website

how to encode each link of my static website

I have a normal static website which was earlier in html but I converted
it to php. I have some menu in header.php of my website where hyperlinks
are present to navigate to different pages. I want that when my website
run on server no one can see the navigated pages i.e. I want to encode my
url. how can I do it.
e.g home I want to encode the href part so that no one knows the name of
the files I used.

Python dict deserialization works in python2.7, fails in 3.3

Python dict deserialization works in python2.7, fails in 3.3

I'm using a sqlite3 table to store python dicts (utf8 content) and
serialization is done with JSON. It works fine in python2.7 but fails in
3.3.
Schema:
CREATE TABLE mytable
(id INTEGER, book TEXT NOT NULL, d JSON NOT NULL, priority INTEGER NOT
NULL DEFAULT(3),
PRIMARY KEY (id, book))
When inserting values, the dict is serialized with json.dumps(d). The
faulty part is retrieving the previously saved values.
import sys
import sqlite3
import json
filename = 'mydb.db'
sqlite3.register_converter('JSON', json.loads)
conn = sqlite3.connect(filename,
detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
c = conn.cursor()
c.execute('''SELECT book, id, d, priority FROM mytable''')
print(c.fetchall())
The above script works fine when executed with python2.7. However, using
3.3 a TypeError occures:
Traceback (most recent call last):
File "tests/py3error_debug.py", line 15, in <module>
c.execute('''SELECT book, id, d, priority FROM mytable''')
File
"/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/__init__.py",
line 319, in loads
return _default_decoder.decode(s)
File
"/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/decoder.py",
line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: can't use a string pattern on a bytes-like object
I can't spot an essential difference between the 2.7 and 3.3 JSON modules
(especially regarding json.loads) and I'm running out of ideas.

Rspec/FactoryGirl: NoMethodError: undefined method 'description' for true:TrueClass

Rspec/FactoryGirl: NoMethodError: undefined method 'description' for
true:TrueClass

exchange communidad. I am trying to write a feature test for my RoR
program, but am getting the following error when I run rspec:
Failure/Error: page.should have_content entry.description
NoMethodError:
undefined method `description' for true:TrueClass
Here is the context in which the error is being thrown:
entries.each do |entry|
page.should have_content entry.description
end
where entries is defined earlier in the same test as follows:
entries = 5.times.map do
FactoryGirl.create(:entry, project_id: proj.id, :date => 9/10/13,
:type_of_work => 'chump', :description => 'chumpin',
:phase => 'Draft', :status => 'Draft' ,
:on_off_site => 'off', :user_id => 1, :start_time
=> now,
:end_time => later).should be_valid
end
Entry is a model which has an attribute of type string called description
which is what I am testing against and what is returning the
true:TrueClass nonsense.
Any leads? Thank you kindly!

Apache 2 rewrite URL to SSL based on domain name

Apache 2 rewrite URL to SSL based on domain name

I use apache 2 on Debian 7.
I have an online tool installed at - let's say - tool.myurl.net I do have
a certified wildcard SSL certificate for *.myurl.net
I also configured the vhost in Apache to listen to tool.anotherurl.com
using ServerAlias But I do not have a valid SSL certificate for that url
SO: I need a rewrite rule that redirect http://tool.myurl.net to BUT NOT
when people visit http://tool.anotherurl.com
Is this possible?
thanks in advance!

How to check if Backbone view exists?

How to check if Backbone view exists?

I have the following situation: - I initialize VIEW_1 on Application
startup. - VIEW1 Render function loads VIEW2. - on menu CLICK event in
VIEW2 i render VIEW3.
The problem is that, when click event happens, it always initializes VIEW3
with another ID which means that i have a GHOST VIEW situation.
any solution ?

gtk menu popup not showing when calling it inside a clutter actor?

gtk menu popup not showing when calling it inside a clutter actor?

im trying to show a gtk menu popup when a Clutter Actor is right-clicked.
For some reason, the menu is not showing. Here is my code (not all, only
the handler)
button_press_event.connect((event) => {
if (event.click_count < 2 && event.button == 1) {
debug("Icon simple click\n");
} else if (event.click_count < 2 && event.button == 3) {
debug("Showing Pop Up menu\n");
var popup_menu = new PopupMenu();
popup_menu.add_menu_item("Prueba 1");
popup_menu.show_all();
popup_menu.show_popup();
return true;
}
return false;
});
PopupMenu is a litle wrapper of gtk.menu I did
public class PopupMenu : Gtk.Menu {
public PopupMenu.from_gtk_widget (Gtk.Widget parent) {
parent.button_release_event.connect((event) => {
if(event.button == 3) this.show_popup();
return true;
});
}
construct {
}
public Gtk.MenuItem add_menu_item (string label) {
var item = new Gtk.MenuItem.with_label(label);
this.append (item);
return item;
}
//Draw the popup at the mouse position
public void show_popup() {
debug("Popup Showing\n");
this.popup(null, null, null, 2, 0);
}
}
The actor is inside an actor with flowlayout. This actor is inside a gtk
window which is transparent. Debug messages are shown.
Why is this not working? thanks

Thursday, 22 August 2013

Convert Expression to Expression

Convert Expression to Expression

I have a method that takes an IOrderedQueryable and Expression> which uses
as a filter and page records from a SQL database.
var query = contexBills.AsNoTracking().Where(x =>
x.Complete==true).OrderBy(x => x.BillID);
var reader = new BulkReader<Bill>(query, x => x.BillId, 10000);
the bulk reader is used extensively throughout the code to page large
volumes of records and process them in batches and is defined like this
public BulkReader(IOrderedQueryable<T> queryable, Expression<Func<T,
Object>> selector, int blockSize = 1000)
For optimisation paging starts at the minimum value found in the table and
ends at the maximum value. As there are many millions of records per month
in the database using a Skip().Take() approach degrades to around 13
seconds a page when you get to to the high millions in the table and
processing the whole months data can then take many hours.
Given that there a very few records in the set that are marked as complete
== false then just selecting records >= [Page Start] AND < [Page End]
works very quickly at about a million records a minute. In some cases you
process slightly less than the blockSize passed in but all records between
min and max get processed.
As the months progress the minimum value increases so assuming 0 as
minimum wastes a lot of SQL calls that return nothing at all.
So what I have to get these values is
var min = queryable.Select(selector).DefaultIfEmpty(0).Min();
var max = queryable.Select(selector).DefaultIfEmpty(0).Max();
Which produces SQL that looks like this
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MIN([Join1].[A1]) AS [A1]
FROM ( SELECT
CASE WHEN ([Project1].[C1] IS NULL) THEN 0 ELSE
[Project1].[PrintSummaryID] END AS [A1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN (SELECT
[Extent1].[PrintSummaryID] AS [PrintSummaryID],
cast(1 as tinyint) AS [C1]
FROM [dbo].[tblPrintSummary] AS [Extent1] ) AS [Project1] ON 1 = 1
) AS [Join1]
) AS [GroupBy1]
GO
If I hand code (as a test) to make calls like this
var min = queryable.Min(x =>(int?)x.BillID) ?? 0;
var max = queryable.Max(x =>(int?)x.BillID) ?? 0;
then the SQL produced is
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MIN([Extent1].[PrintSummaryID]) AS [A1]
FROM [dbo].[tblPrintSummary] AS [Extent1]
) AS [GroupBy1]
GO
The same can be achieved by declaring the following instead:
Expression<Func<Bill, int?>> selector2 = x => x.BillID;
Which gives the benefit of the simpler and faster SQL execution and allows
the code to become:
var min = queryable.Select(selector2).Min() ?? 0;
var max = queryable.Select(selector2).Max() ?? 0;
Taking the approach of explicitly redefining all the selectors and
providing overrides for them would mean significant duplication and
recoding across the entire application
How could I take a the original selector and do a conversion to the
nullable version equivalent generically rather then having to explicitly
code each one.
var selector2 = selector.NullableExpression();
I'd like to to this as an extension method NullableExpression() on
Expression> so that I return a Expression>> and that way I could use it in
other locations throughout my code to.
I'm struggling with how I can convert the V to a Nullable or V? in an
expression.

Error when I am using getJson.

Error when I am using getJson.

I wrote a javascript code to get a Json object from a url. And my code is
like this:
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON('url_address', {}, function(data) {
// do something
});
});
});
});
</script>
And I am using Google Chrome browser. And I can get the json data
correctly if I just enter the url in my browser.
But when I debug this code, I got an error message:
XMLHttpRequest cannot load 'url_address'. Origin null is not allowed by
Access-Control-Allow-Origin.
I don't know what's wrong with it.

No route matches [POST] "/sessions/user"

No route matches [POST] "/sessions/user"

I just installed Devise on my app, I had previously done it by scratch
like Michael Hartl tutorial.
Currently I can sign up and log out. But when I do log in it gives an error:
No route matches [POST] "/sessions/user"
it happens when I click on the sign in/log in button with or without the
(correct) password.
My route file is:
SampleApp::Application.routes.draw do
devise_for :users, path_names: { sign_in: "login", sign_out: "logout"}
resources :users do
resources :bookings, only: [:show]
end
resources :bookings
resources :sessions
# match '/signup', to: 'devise/registrations#new', via: :get
# match '/signin', to: 'devise/sessions#new', via: [:post, :get]
# match '/signout', to: 'devise/sessions#destroy', via: :delete
match '/admin', to: 'admin#new', via: :get
match "bookings/new", to: 'bookings#new', via: [:post, :get]
devise_scope :user do
root to: 'static_pages#home'
end
Thanks in advance!

Doubts about JSF : how to close a Backing Bean and Writing a filter for Glassfish Webserver

Doubts about JSF : how to close a Backing Bean and Writing a filter for
Glassfish Webserver

Im developing a webapp in JSF and i have some doubts. My app is growing
day by day, and as it grows, i started receiving some trouble messages. I
am currently developing in my notebook, not a big server with illimitate
resources, so my problem is that the application is too heavy for my pc
and connection capabilities. I ve read about it searching in google, and i
found some solutions. One of this solutions, is "tuning glassfish". I ve
read something about creating filters, and configuring glassfish server
for production mode. Does someone have an example of filter for web
server? My purpose is to store all js, css and png images in client's web
browser cache. The second question is : if i use a viewscoped backing
bean, for example in signup page, when i navigate to another page, is that
bean automatically erased ? or i keep it in memory? Third and last
question, creating more small tables instead of few big tables (i m
talking about the number of columns, not rows ) is convenients in terms of
performances? thank you and sorry bad english

Add PART to the table of contents

Add PART to the table of contents

I want to have a table of contents as follows:
Introduction
Part 1: the partition function
section 2
section 3
Part 2: theta function
section 4
How can I do this? Thanks in advance!

Why is _GNU_SOURCE macro required for pthread_mutexattr_settype()?

Why is _GNU_SOURCE macro required for pthread_mutexattr_settype()?

I have written a multithread server program in C, which echoes back all
the data that a client sends.
Initially, I used poll() function in my program to detect POLLRDHUP event,
for that I defined _GNU_SOURCE macro (This event is defined here).
Later I updated my code & removed poll() function, however I forgot to
remove _GNU_SOURCE macro.
Now my code is finally complete (and a little long to post, more than 250
lines). Before removing macro I was compiling my program using:
gcc multi_thread_socket_v4.c -Wall -Werror -g -lpthread -o
multi_thread_socket
and it worked fine: No errors, no warnings
After I removed the macro definition, and compiled using same
command-line, the output of gcc was:
multi_thread_socket_v4.c: In function 'main':
multi_thread_socket_v4.c:194: warning: implicit declaration of function
'pthread_mutexattr_settype'
multi_thread_socket_v4.c:194: error: 'PTHREAD_MUTEX_ERRORCHECK' undeclared
(first use in this function)
multi_thread_socket_v4.c:194: error: (Each undeclared identifier is
reported only once
multi_thread_socket_v4.c:194: error: for each function it appears in.)
I have included all the required libraries as it worked fine initially.
I peeked into pthread.h at /usr/include/pthread.h and found out this:
/* Mutex types. */
enum
{
PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_ADAPTIVE_NP
#ifdef __USE_UNIX98
,
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL

Wednesday, 21 August 2013

List of Top 10 security tools

List of Top 10 security tools

I have gone through documentation of many security test tools both paid
and free, but I am confused that which tool can serve the most of OWASP
top 10 vulnerabilities. Can anyone list me the TOP 10 Pentest (security)
tools to test the websites, both paid and free. Thanks in advance.

Unable to create datacontext object for IndexedDB provider using JayData Framework 1.3.1

Unable to create datacontext object for IndexedDB provider using JayData
Framework 1.3.1

I'm unable to create datacontext object for IndexedDb provider using
Jaydata framework 1.3.1 and getting "FailedProvider fallback failed!"
message for $todo.context.onReady().
What is the syntax to define dataprovider for IndexedDB? I found below
code in Jaydata documentation, but it doesn't work because "
$data.types.storageProviders" API doesn't showing up "indexedDb" class in
it.
$news.context = new $news.Types.NewsContext({ name: "indexedDb",
databaseName: "NewsReader", dbCreation:
$data.types.storageProviders.indexedDb.DbCreationType.DropStoreIfOlderVersion,
version: 1 });

Visual Studio 2010/2012 have to rebuild instead of build

Visual Studio 2010/2012 have to rebuild instead of build

When I hit build or start in visual studio to start my Asp.Net 4.0 web
application, it fails to compiles and gives me the following errors:
Error 152 The type 'System.Net.Http.HttpResponseMessage' is defined in
an assembly that is not referenced. You must add a reference to assembly
'System.Net.Http, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
If I hit ReBuild in the Build drop down, it compiles fine. Happens in both
2010 and 2012 versions of visual studio. Any ideas?
It all started when I added a reference to System.Net.Http.

How can I combine values of checkboxes with values of text in php?

How can I combine values of checkboxes with values of text in php?

I'm new with PHP, and I'm making a html form which consist basically in
two options: First, the client select a series of checkboxes (parts from
an equipment) and then write the amounts of each selected checkbox...
<td><input id="11.11.015.0002" name="pecas[]" type="checkbox"
value="11.11.015.0002 - BATERIA CHUMBO ACIDO 6V/4AH" /></td>
<td><input name="qntd[]" size="7" type="text" /></td>
and in php:
if(isset($pecas))
{
$mensagem .= "Peças Selecionadas:<br /><br />";
}
else {
echo "<script>alert('Selecione as Peças Desejadas!');
location.href='http://www.lyuz.com.br/pecas/erro';</script>";
exit;
}
foreach ($pecas as $pecas_s) {
} $mensagem .= " - ".$pecas_s."<br />";
That gave me all the selected checkboxes (parts), now I'm trying to get
only the input_text (amounts) associate with these selected checkboxes..
I'm stuck. Help.

Google Maps API V3 pinch-to-zoom does not work with IE 11 on Windows 8.1 preview

Google Maps API V3 pinch-to-zoom does not work with IE 11 on Windows 8.1
preview

Trying to use pinch-to-zoom on multitouch screen with Windows 8.1 preview
and Internet Explorer 11 (IE later on) does not work with Google Maps API
V3 (none of the latest versions: 3.12, 3.13 and 3.14). The expected
behaviour is map zooming in and out.
The same feature is working just fine with Windows 8 and IE 10.
There seem to be two exceptions for the case:
https://maps.google.com
https://developers.google.com/maps/documentation/javascript/examples/map-simple
(any example being embedded in the docs pages; when viewed in a standalone
tab or window by pressing the view "full screen" pinch-to-zoom does not
work)
Does anyone know how that is achieved so that it could be used until the
issue is fixed?

Cannot run exe file from wpf application

Cannot run exe file from wpf application

..and I have no idea why. I can run exe output file from debug folder
(application created in wpf), but I cant run file I need to send products
into ethernet connected weight. This exe file reads .plu file (product by
product) and adding them into weight memory.
Code im using:
using (StreamWriter sw = new StreamWriter(appPath + "\\Wagi\\" +
cbi.Content.ToString() + "\\Kasa1.plu"))
{
sw.WriteLine("[MT_STAND_FIRE,PLU,WRITE,0,0,0,0]");
foreach (DataRowView item in prodDG.Items)
{
//write lines about products
}
sw.WriteLine("[MT_STAND_FIRE,Extra Text,WRITE,0,0,0,0]");
sw.WriteLine("[MT_STAND_FIRE,Preset Key,Write,0,0,0,0]");
}
string ExecutableFilePath = appPath + @"\Wagi\" +
cbi.Content.ToString() + @"\bComScale.exe";
if (File.Exists(ExecutableFilePath))
{
Process.Start(ExecutableFilePath);
}
Any ideas?

LINK : fatal error LNK1181: cannot open input file 'libclamav.lib'

LINK : fatal error LNK1181: cannot open input file 'libclamav.lib'

I am using Microsoft Visual Studio 2010, and i am working on open source
Clamav, my code is given below which is generating an error
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <clamav.h>
int main(int argc, char **argv)
{
int fd, ret;
unsigned long int size = 0;
unsigned int sigs = 0;
long double mb;
const char *virname;
struct cl_engine *engine;
if(argc != 2) {
printf("Usage: %s file\n", argv[0]);
return 2;
}
if((fd = open(argv[1], O_RDONLY)) == -1) {
printf("Can't open file %s\n", argv[1]);
return 2;
}
if((ret = cl_init(CL_INIT_DEFAULT)) != CL_SUCCESS) {
printf("Can't initialize libclamav: %s\n", cl_strerror(ret));
return 2;
}
if(!(engine = cl_engine_new())) {
printf("Can't create new engine\n");
return 2;
}
/* load all available databases from default directory */
if((ret = cl_load(cl_retdbdir(), engine, &sigs, CL_DB_STDOPT)) !=
CL_SUCCESS) {
printf("cl_load: %s\n", cl_strerror(ret));
close(fd);
cl_engine_free(engine);
return 2;
}
printf("Loaded %u signatures.\n", sigs);
/* build engine */
if((ret = cl_engine_compile(engine)) != CL_SUCCESS) {
printf("Database initialization error: %s\n", cl_strerror(ret));;
cl_engine_free(engine);
close(fd);
return 2;
}
/* scan file descriptor */
if((ret = cl_scandesc(fd, &virname, &size, engine, CL_SCAN_STDOPT)) ==
CL_VIRUS) {
printf("Virus detected: %s\n", virname);
} else {
if(ret == CL_CLEAN) {
printf("No virus detected.\n");
} else {
printf("Error: %s\n", cl_strerror(ret));
cl_engine_free(engine);
close(fd);
return 2;
}
}
close(fd);
/* free memory */
cl_engine_free(engine);
/* calculate size of scanned data */
mb = size * (CL_COUNT_PRECISION / 1024) / 1024.0;
printf("Data scanned: %2.2Lf MB\n", mb);
return ret == CL_VIRUS ? 1 : 0;
}
the following error is generated LINK : fatal error LNK1181: cannot open
input file 'libclamav.lib'
kindly guide me

Tuesday, 20 August 2013

Android.mk - build all source file in a directory

Android.mk - build all source file in a directory

I am using Android NDK to build my cocos2dx project, within the
Android.mk, there is a definition for LOCAL_SRC_FILES where each of the
cpp file are listed. Whenever I added a new source file, I'd need to add
it there as well... it looks like this:
LOCAL_SRC_FILES := hellocpp/main.cpp \
hellocpp/myclass.cpp \
hellocpp/mynextclass.cpp \
../../Classes/Screens/LaunchScreen.cpp \
the header file, however, can specify the entire directory to include, it
looks like this:
LOCAL_C_INCLUDES := $(LOCAL_PATH)/hellocpp
LOCAL_C_INCLUDES += $(LOCAL_PATH)/../../Classes/Screens
I have tried various ways to include the whole directory instead of single
file for the LOCAL_SRC_FILES so that I don't need to modify the Android.mk
build script whenever I add a new file, however, so far all my attempts
failed.
I have tried this:
#SRC_PATH_HELLOCPP := $(wildcard hellocpp/*.cpp)
#SRC_PATH_CLASSES += $(wildcard ../../Classes/*.cpp)
#LOCAL_SRC_FILES := $(SRC_PATH_HELLOCPP:$(LOCAL_PATH/%=%)
#LOCAL_SRC_FILES += $(SRC_PATH_CLASSES:$(LOCAL_PATH/%=%)
as well as this:
#LOCAL_SRC_FILES += hellocpp/*.cpp
#LOCAL_SRC_FILES += ../../Classes/*.cpp
both are not working...
I have another project that works well with the first option though, I
really do not understand why it doesn't work in the cocos2dx project...
does anybody know why or know the solution? Or maybe I should just leave
it as is and take the trouble, since everybody is doing that., but it is
really troublesome, hope somebody can help so that all of us can be more
productive..
Thanks!

Scanner not working?

Scanner not working?

I am new to Java and I am trying to make a Java app where it asks you to
spell "Java" and if you spelled it correctly it will type "yes", however,
it is typing "no", what am I doing wrong:
package quiz;
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner kirill = new Scanner(System.in);
System.out.println(kirill.next());
String kirill2 = "Java";
if (kirill.equals(kirill2)){
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(kirill);
kirill.close();
}
}
Running code: Java
Java
no
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=4][match
valid=true][need input=false][source closed=false][skipped=false][group
separator=\,][decimal separator=.][positive prefix=][negative
prefix=\Q-\E][positive suffix=][negative suffix=][NaN
string=\Q?\E][infinity string=\Q?\E]

Fastest Truck in ETS 2?

Fastest Truck in ETS 2?

Now that the 90kmph Speed limit is gone after the 1.4.12 patch, does
anybody know which is the fastest truck in the game and what speeds it can
achieve?

Kernel Panic after Fedora 19 Update

Kernel Panic after Fedora 19 Update

After installing updates on Fedora 19 (kernel 10.3.7-200.fc19.x86_64) the
DE freezes whenever I log in. Using the virtual consoles doesn't work. One
time I even got this kernel panic:
http://i.stack.imgur.com/h5q5n.jpg
I have other kernels to try (10.3.5 and 10.3.3) and on them I don't get
the freezes or the kernelpanics.
Can you help me?

Message ordering in distributed system

Message ordering in distributed system

I want to build a distributed system where I have "threads" (a collection
of messages with it's own ID, not a system process) that are distributed
across many servers. These threads must have two critical properties:
Each message in thread must have an order number that reflects it's
position in thread based on time. For example by saying
"thread1/message10" I can get to message #10 in thread #1
Once new message gets added to thread a system must be able to assign it
an order number that is consistent for all instances of thread on all
servers and this number must never change.
I want to know if there's any known solution, library or algorithm that
can help me implement a second option because now I see it as a big
problem because due to many factors different servers can get the same
message at different times and that might affect it's order number.
Just to outline my thoughts on a problem so far say I have 3 servers with
my distributed thread which already contains 5 messages and each server
sends a new message to it's own thread and to remaining two.
Naive ordering. Each server think it's own message number is 6 and the
remaining two messages from other servers will get their numbers on
arrival depending on network latency and many other random factors so
order numbers are not consistent across servers. This is unacceptable
right away.
UTC timestamp based ordering. When each thread gets a new message I take
say 10 preceding messages that already have correct order numbers, extract
their timestamps and determine a new message's order number by finding
it's timestamp place in a list of last 10 timestamps. This might work I
guess but it does require that some message's order number can be assigned
and then changed at some point which is unacceptable. Also I'm not sure if
this will work right when a number of incoming messages is huge.
Thanks for all the help.

Using GetDiskFreeSpaceEx on CIFS share (C#)

Using GetDiskFreeSpaceEx on CIFS share (C#)

I'm trying to use WIN Api function GetDiskFreeSpaceEx() to get available
disk space on CIFS share. I discovered that this function return different
values after the disk have been formatted.
So here are my steps: 1. Create the CIFS shared folder. 2. Call
GetDiskFreeSpaceEx(). It returns correct value. 3. Format the disk with
shared folder. 4. Recreate folder on the disk. (Sharing wasn't be stopped)
5. Call GetDiskFreeSpaceEx(). It returns 0. 6. Call GetDiskFreeSpaceEx()
again. Now it returns correct value. And all next calling of this function
returns right value.
I also discovered that when I stop sharing the folder after formatting the
disk and than begin to share it again, the GetDiskFreeSpaceEx() always
return correct value.
Do you have any ideas about such situation? Thanks.

giving initial value raises 'value for field is required' error in django

giving initial value raises 'value for field is required' error in django

Django form trips me many times...
I gave initial value to a ChoiceField
self.fields['thread_type'] = forms.ChoiceField(choices=choices,
widget=forms.Select,
initial=thread_type)
The form which is created with thread_type with the above code doesn't
pass is_valid() because 'thread_type' isn't provided.
(The error message is not in english so I can't give the exact error in
english)
What should I do to pass the is_valid() call?

Monday, 19 August 2013

Invalid Expression 'String' C#

Invalid Expression 'String' C#

I'm trying to make a program that when a button is pressed, the program
takes the words typed in the text box and adds it to a notepad file. This
is what I have so far:
private void textBox1_TextChanged(object sender, EventArgs e)
{
File.WriteAllText(path, string());
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
File.WriteAllText(path, string());
}
}
The String keeps coming up with error code CS1525. I haven't been able to
find any help elsewhere, so if you can offer help, thanks!

ASP.NET / C# - Can't use SQL Server CE in VS2012

ASP.NET / C# - Can't use SQL Server CE in VS2012

I'm developing a web application and was trying to use a local database
file to store some information. However, when I add the .sdf file, I get
an error. Below are some screenshots detailing my problem.
I've been trying to figure what's wrong for several hours. I've seen
similar issues, but have yet to find a fix. I used to be able to use
SqlServerCe connections before with .sdf files, though that was a
different development environment. I have tried reinstalling everything
SQL several times, including downloading everything I could find on MSDN.
Can anyone help me out?
Below is my Solution Explorer View. I've just added Database1.sdf to the
project.

I get an error as soon as I add it:

If I try to open the .sdf file, I get this error:

Here is my list of references:

And, finally, all of the relevant SQL-related installations on my local
machine:

How to access and make use of html data in django?

How to access and make use of html data in django?

I am having a hard time figuring out the right logic for my problem, i
have 3 models,
class Item(SmartModel):
name= models.CharField(max_length=64,help_text="Name for this item e.g
Hamburger")
price=models.DecimalField(max_digits=9,decimal_places=2)
optionalitems =
models.ManyToManyField('optionalitems.OptionalItemCategory',null=True,blank=True)
class OptionalItems(SmartModel):
"""Optional items that belong to an item e.g topping that belongs to
a pizza"""
name = models.CharField(max_length=20, help_text="Item name.")
price = models.DecimalField(max_digits=9, decimal_places=2,
null=True,blank=True)
class OptionalItemCategory(SmartModel):
"""Category to which optional items belong"""
title = models.CharField(max_length=20,help_text="Category name")
optional_items = models.ManyToManyField(OptionalItems)
in my template,
{%for optionalcategory in optionalcategories %}
<h5 id="blah"> </h5>
{% for optionalitem in optionalcategory.optional_items.all %}
<ul>
<input type="radio" value="radio" name="optional" value="op"><li
id="item_appearence"></span></li><a/>
</ul>
{% endfor %}
{% endfor %}
So for example an Item like a burrito will have an OptionalItem steak or
chicken.I am able to access the Item like so item =
get_object_or_404(Item, pk=obj.id) but my problem is i cannot figure out
how to capture the OptionalItem. I want to be able to access the
OptionalItem steak and its other fields like price

Getting more than one Legend object in LegendCollection to stack vertically when chart renders

Getting more than one Legend object in LegendCollection to stack
vertically when chart renders

I'm trying to learn the mschart control. I want to create a histogram
chart that has a stat panel to the right that displays statistics about
the chart. I tried doing this by creating a Legend object docked to the
right.
I would like the boxes to stack vertically to the right of the chart.
Currently each box represents a Legend object in the LegendsCollection.
Code:
private void CreateStatPanel( Chart chart ) {
var legend = new Legend
{
Title = "Basic Stats",
TitleAlignment = StringAlignment.Near,
TitleBackColor = Color.LightGray,
Docking = Docking.Right,
BorderColor = Color.LightGray,
BorderWidth = 1,
BorderDashStyle = ChartDashStyle.Solid,
};
var item = new LegendItem();
var column = new LegendCell
{
CellType = LegendCellType.Text,
BackColor = Color.White,
ForeColor = Color.Black,
Text = "54 Data Values ",
Alignment = ContentAlignment.MiddleRight
};
var item2 = new LegendItem();
var column2 = new LegendCell
{
CellType = LegendCellType.Text,
BackColor = Color.White,
ForeColor = Color.Black,
Text = "Maximum \t 14",
Alignment = ContentAlignment.MiddleRight
};
var box = new Legend
{
Title = "Subgroup Stats",
TitleAlignment = StringAlignment.Near,
TitleBackColor = Color.LightGray,
BorderColor = Color.LightGray,
BorderWidth = 1,
BorderDashStyle = ChartDashStyle.Solid
};
var boxRowOne = new LegendItem();
var boxRowCell = new LegendCell
{
CellType = LegendCellType.Text,
BackColor = Color.White,
ForeColor = Color.Black,
Text = "n=6",
Alignment = ContentAlignment.MiddleRight
};
var boxRowTwo = new LegendItem();
var boxRowTwoCell = new LegendCell
{
CellType = LegendCellType.Text,
BackColor = Color.White,
ForeColor = Color.Black,
Text = "Estimated Sigma",
Alignment = ContentAlignment.MiddleLeft
};
var boxRowTwoCellTwo = new LegendCell
{
CellType = LegendCellType.Text,
BackColor = Color.White,
ForeColor = Color.Black,
Text = "1.82",
Alignment = ContentAlignment.MiddleLeft
};
item.Cells.Add( column );
item2.Cells.Add( column2 );
boxRowOne.Cells.Add(boxRowCell);
boxRowTwo.Cells.Add(boxRowTwoCell);
boxRowTwo.Cells.Add(boxRowTwoCellTwo);
box.CustomItems.Add(boxRowOne);
box.CustomItems.Add(boxRowTwo);
legend.CustomItems.Add( item );
legend.CustomItems.Add( item2 );
chart.Legends.Add( legend );
chart.Legends.Add( box );
chart.Series[ 0 ].IsVisibleInLegend = false;
}

What is the range of ECM jammer in Payday 2?

What is the range of ECM jammer in Payday 2?

What is the range of ECM jammer in Payday 2? Let's say I put it in the
middle of the jewelry store's shopping room in the Jewelry Store Heist
mission, how far it will reach?

Sunday, 18 August 2013

Skip first line while reading CSV file in Java

Skip first line while reading CSV file in Java

Hey guys I am writing a parser code to read a .csv file and parse it to
XML. This is the code I have and it works fine except I would like it to
skip the first line in the file. So I decided to set up a HashMap but it
does seem to work:
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".csv")){
System.out.println("File Found: " + file.getName());//Prints
the name of the csv file found
String filePath = sourcepath + "\\" + file.getName();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int n = 1;
Map<Integer,String> lineMap = new HashMap<Integer,String>();
int k=2;
while ((line = br.readLine()) != null) {
System.out.println(n + " iteration(s) of 1st While Loop");
lineMap.put(k, line);
fw.write(" <ASSET action=\"AddChange\">\n");
fw.write(" <HOSTNAME>\n");
hostName=line.substring(0, line.indexOf(","));
fw.append(hostName);
fw.write("</HOSTNAME>\n");
fw.write(" <HOSTID>\n");
hostID=line.substring(line.indexOf(",")+1, nthOccurrence(line, ',', 1));
fw.append(hostID);
fw.write("</HOSTID>\n");
fw.write(" <MACMODEL>\n");
machineModel=line.substring(nthOccurrence(line, ',', 1)+1,
nthOccurrence(line, ',', 2));
fw.append(machineModel);
fw.write("</MACMODEL>\n");
fw.write(" <PROMODEL>\n");
processorModel=line.substring(nthOccurrence(line, ',', 2)+1,
nthOccurrence(line, ',', 3));
fw.append(processorModel);
fw.write("</PROMODEL>\n");
fw.write(" <CORE>\n");
core=line.substring(nthOccurrence(line, ',', 3)+1, nthOccurrence(line,
',', 4));
fw.append(core);
fw.write("</CORE>\n");
fw.write(" <PROC>\n");
proc=line.substring(nthOccurrence(line, ',', 4)+1, nthOccurrence(line,
',', 5));
fw.append(proc);
fw.write("</PROC>\n");
fw.write(" <TIER>\n");
tier=line.substring(nthOccurrence(line, ',', 5)+1, nthOccurrence(line,
',', 6));
fw.append(tier);
fw.write("</TIER>\n");
fw.write(" <PRODNAME>\n");
productName=line.substring(nthOccurrence(line, ',', 6)+1,
nthOccurrence(line, ',', 7));
fw.append(productName);
fw.write("</PRODNAME>\n");
fw.write(" <VERSION>\n");
version=line.substring(nthOccurrence(line, ',', 7)+1,
nthOccurrence(line, ',', 8));
fw.append(version);
fw.write("</VERSION>\n");
fw.write(" <SCRIPTDATA>\n");
scriptData=line.substring(nthOccurrence(line, ',', 8)+1, line.length());
fw.append(scriptData);
fw.write("</SCRIPTDATA>\n");
fw.write(" </ASSET>\n");
k++;
}n++;
This is a snippet of the main part of the code. Any Ideas or Solutions???

interfaces in multiple inheritance in java, modelling issue

interfaces in multiple inheritance in java, modelling issue

I have the following scenario:

As you can see, I have two classes that are Lecturers and Students. The
class Teacher Assistants are a mix between Lectures and Students, that is
because they can enrolled into courses, but they can also lecture some
basic topics (without being considered Lecturers). I came with the idea to
model this situation using Interfaces because I will program in in Java.
Is this modelling correct?

So that the TA class will implement the Interface Teaches, which contains
an array of the courses assigned to this student to teach.
But if I model in that way I realize that I am loosing the class Lecturers
at all. How I can model this situation of multiple inheritance, but not
loosing the class Lecturers? I mean if I program Lecturers as an interface
it would not have any methods that I would need further, for example,
calculus of its wage benefits and so on. Any recommendation?

jQuery custom checkbox - graphic update not working

jQuery custom checkbox - graphic update not working

Trying to set a custom checkbox value when the form loads. Debug tells me
the checkbox reflects the value loaded from a source but the custom
graphic won't update.
In my form I have
<input class="checkbox" type="checkbox" name="uitem_autorenew"
id="uitem_autorenew" />
Style I have:
.checkbox {
display: none;
}
.toggle {
background: url("toggle.png") bottom left;
display: block;
width: 70px;
height: 22px;
}
.toggle.checked {
background-position: top left;
}
Code includes the following
$(document).ready(function() {
$('.checkbox').after(function() {
if ($(this).is(":checked")) {
return "<a href='#' class='toggle checked' ref='" +
$(this).attr("id") + "'></a>";
} else {
return "<a href='#' class='toggle' ref='" +
$(this).attr("id") + "'></a>";
}
});
...into the dialog which has an open event... definitely setting the check
or uncheck feature according to the data
var ar=$(this).data('renew');
console.log("Value of ar = " + ar); // which is Y
if (ar =="Y"){
$("#uitem_autorenew").prop('checked',true); // tried
this
$("#uitem_autorenew").toggleClass("checked");
//tried this too
}
console.log ("Is checkbox checked?");
console.log ($("#uitem_autorenew").prop('checked')); //
yes it is but the graphic has not toggled. Top left of
toggle.png is has word "YES"
I'm just wondering what I am missing in the case that the style has not
changed. Any clues welcomed and thanks in advance. Kevin

How to reload JS script after making any changes in Google DevTools?

How to reload JS script after making any changes in Google DevTools?

I'm new in Google DevTools, and I've got one question: 1) My test page has
got one JS script "func.js" with the following code:
$(function() {
console.log('123');
});
It works without any problems.
2) When I open DevTools in Chrome (Ctrl + Shift + I in Windows) DevTools
panel is coming 3) I open "Sources" -> "func.js" and JS console; it works,
I see "123" in console. 4) I do some changes. For example,
$(function() {
console.log('123');
console.log('456');
});
Is it possible to reload this updated code without saving in the original
file? I see no reload/refresh/remake buttons for this feature. I've got
the last Google Chrome version. Please, tell me, how can I do it? Is it
possible?

Thread C# windows 8

Thread C# windows 8

[DllImport("kernel32.dll")] public static extern bool
SetWaitableTimer(IntPtr hTimer, [In] ref long pDueTime, int lPeriod,
TimerAPCProc pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool
fResume);
[DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
public static extern Int32 WaitForSingleObject(IntPtr handle, int
milliseconds);
public static uint INFINITE = 0xFFFFFFFF;
private IntPtr handle;
private void shutdownToolStripMenuItem_Click(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
dt.AddSeconds(30.0);
long duetime = dt.ToFileTime();
handle = Win32.PowerManagement.CreateWaitableTimer(IntPtr.Zero, true,
"");
Win32.PowerManagement.SetWaitableTimer(handle, ref duetime, 0, null,
IntPtr.Zero, true);
Thread t = new Thread(new ThreadStart(this.NewThread));
t.Start();
}
private void NewThread()
{
int ret = Win32.PowerManagement.WaitForSingleObject(handle,
(int)Win32.PowerManagement.INFINITE);
MessageBox.Show("Wait object"); // ret = 0x00000000L here
}
How to implement this code in C# windows 8? That is, only this part:
Thread t = new Thread(new ThreadStart(this.NewThread));
t.Start();
Thanks!

Zend 2 adapter in Controller works fine but not in Model

Zend 2 adapter in Controller works fine but not in Model

I am new in Zend 2. I have made a controller and Model.
I am getting the following error:
Fatal error: Call to a member function get() on a non-object in
C:\websites\zend2\module\Pages\src\Pages\Model\PagesTable.php on line 25
What do i do wrong?!?!
controller:
namespace Pages\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class IndexController extends AbstractActionController {
function indexAction() {
$test = new \Pages\Model\PagesTable();
$test->pages();
print_r($test);
}
}
Model:
namespace Pages\Model;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\ResultSet\ResultSet;
class PagesTable extends AbstractActionController{
function pages() {
$db = $this->getAdapter();
$sql = 'select * from pages';
$stmt = $db->query($sql);
$result = $stmt->execute();
$resultSet = new ResultSet;
$resultSet->initialize($result);
$viewObj = new ViewModel(array('result' => $resultSet));
print_r($viewObj);
}
public function getAdapter() {
if (empty($this->adapter)) {
$sm = $this->getServiceLocator();
$this->adapter = $sm->get('Zend\Db\Adapter\Adapter');
}
return $this->adapter;
}
}

Can I pass an array into a Google App Script method from a Google Spreadsheet?

Can I pass an array into a Google App Script method from a Google
Spreadsheet?

Can I pass an array into a Google App Script method from a Google
Spreadsheet?
Suppose I have an App Script function that expects a list with two
elements (note: this example is just an example so please do not tell me
that my problem would be solved if I simply passed each element as a
separate argument). How do I call this function from a Google Spreadsheet
cell?
I've tried both: '=myFunc([1,2])' and '=myFunc((1,2))' and both give me a
Parse Error.

Saturday, 17 August 2013

trouble with multiple select in stored procedure zend framework 2.2 tablegateway

trouble with multiple select in stored procedure zend framework 2.2
tablegateway

well. sorry about my english.
i'm working with stored procedures in PDO-mysql with zend framework 2.2,
and tablegateway library.
this is an generic exmaple of my sp.
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_proc`(IN id SMALLINT)
BEGIN
SELECT * FROM TABLE_A WHERE ID_TABLE=ID;
SELECT * FROM TABLE_B WHERE ID_FK=ID;
END
and this is function from model
public function __construct(Adapter $adapter = null, $databaseSchema =
null, ResultSet $selectResultPrototype = null)
{
return parent::__construct('', $adapter, $databaseSchema,
$selectResultPrototype);
}
public function listaServicio()
{
$dbAdapter=$this->getAdapter();
$stmt = $dbAdapter->createStatement();
$stmt->prepare('CALL sp_proc(:id)');
$id=15;
$stmt->getResource()->bindParam(':id', $id, \PDO::PARAM_INT);
$resultado=$stmt->execute();
while ($resultado->next()) {
var_dump($resultado->current());
}
}
but i just have result from the "first" select (table_a), but could not
get the result from "second"(table_b).
i dont know if its problem with my stored procedure or the way ive worked
in the model..