Thursday, 3 October 2013

Correct way to serialize data outside of an entity using JMSSerializerBundle

Correct way to serialize data outside of an entity using JMSSerializerBundle

I have an entity, which returns all the data I want (from the entity,
anyway). I also want to return some configuration parameters as well, if I
was in a service, controller or anywhere where I had access to the
container I'd simply do:
$this->container->getParameter('my.setting');
However, I obviously don't have (and rightfully so) access to the
container within an entity.
So my question is: how can I add my parameter to the output of the json
that JMSSerializerBundle generates?

Wednesday, 2 October 2013

Having problems with cocos2d and menus?

Having problems with cocos2d and menus?

I'm having a problem with xcode when making a menu when using the cocos2d
templates. I put this code in:
if( (self=[super init]) ) {
CCMenuItemImage *item = [CCMenuItemImage
itemWithxNormalImage:@"bug.png" selectedImage:@"bug.png" target:self
selector:@selector(doThis:)];
CCMenu *menu = [CCMenu menuWithItems:item, nil];
[self addChild:menu];
}
return self;
-(void)doThis:(id)sender{}
I put the if statement in the -(id) init method in helloworldlayer.m. If
anyone can help that would be greatly appreciated. I'm having the problem
where everything builds correctly, but the picture doesn't show. I have it
copied to my resources, but when I build it, no picture is shown.

Exception on calling getAdapter()

Exception on calling getAdapter()

LinkAdapter is a class which extends the ArrayAdapter.
private static List<LinkData> linkDataList = new ArrayList<LinkData>();
private LinkAdapter la;
la = new LinkAdapter(someLinkDataitmes, getActivity());
ListView lv = (ListView) v.findViewById(R.id.urls);
lv.setAdapter(la);
public class LinkData {
private String name, image, description;
public LinkData(String name, String image, String description){
this.name = name;
this.image=image;
this.description=description;
}
}
Now I later want to update my listview,
ListView lv = (ListView) v.findViewById(R.id.urls);
LinkAdapter mListAdapter = ((LinkAdapter)lv.getAdapter()); // this line is
giving an error.
mListAdapter.add(new LinkData(name_val, image_val, description_val));
mListAdapter.notifyDataSetChanged();
But the code is not working(giving a NullPointerException)
Searched a lot on the internet, but could not find a specific answer to my
problem.

Yii - updating a model and using the model to echo data in the view

Yii - updating a model and using the model to echo data in the view

I have the following code for updating a Yii model:
public function actionSettings($id) {
if (!isset($_POST['save_hostname']) && isset($_POST['Camera']) &&
isset($_POST['Camera']['hostname'])) {
$_POST['Camera']['hostname'] = '';
}
$model = $this->loadModel($id);
$model->setScenario('frontend');
$this->performAjaxValidation($model);
if (isset($_POST['Camera'])) {
$model->attributes = $_POST['Camera'];
unset($model->api_password);
if ($model->save()) {
Yii::app()->user->setFlash('success', "Camera settings has
been saved!");
} else {
Yii::app()->user->setFlash('error', "Unable to save camera
settings!");
}
}
$this->render('settings', array(
'model' => $model,
));
}
This works fine, except in my model I have code like this:
<h1>Settings For: <?php echo CHtml::encode($model->name); ?></h1>
The problem is that, even when the user input fails validation, the h1 tag
is having bad input echoed out into it. If the input fails the validation,
the h1 attribute should stay the same.
I can 'reset' the $model variable to what is in the database before the
view is returned, but this then means I don't get any error feedback /
validation failed messages.
Is my only option to have 2 models, one used for handling the form and the
other for sending data to the page? Or does someone have a more elegant
solution?

Trigger in oracle

Trigger in oracle

account
----------
accno varchar
acctotal number
student
----------
id varchar
fees number
accno varchar
I want to create a trigger which updates 'account' table anytime a record
is deleted from 'student'. It subtracts fees of student from acctotal in
account.
thnx in advance.

Tuesday, 1 October 2013

How to find search criteria2 if criteria1 not displayed in exccel by using VBA

How to find search criteria2 if criteria1 not displayed in exccel by using
VBA

I have a workbook1-->Sheet3 having inputs(Iam providing 24monthdays:110,
125, 210,.......1210, 1225) for Marco.Input will be always Monthdays
regardless of years, on 10th and 25th of every month will receive data. If
mentioned days are not non-business day, suppose if 10th is holiday there
is possibility 11th to till 15th. Same way if 25th is holiday there is
possibility 26th to 30th of every month. Based on above conditions in
sheet1 needs to filter the data Eg: Monthday 110 I will search in sheet1.
Suppose sheet1 don't have data for mentioned "110" there is possibility
till "115"(But Ideally I am providing only 24th days in my input
"sheet3"). Please guide/help me regarding issue make vba.

cleanup tmp directory with carrierwave

cleanup tmp directory with carrierwave

I use carrierwave for my images upload, in my form i added a hidden field
for caching like is described in documentation.
= form_for @user, html: {multipart: true} do |f|
%p
= f.label :photo, "your image"
= f.file_field :photo, id: "img"
= f.hidden_field :photo_cache
but the problem is after uploading images and saving record, tmp directory
still having all temporary/caching files.
there is a way to clean up the tmp directory ?

Calculate tail probabilities from density() call in R – stats.stackexchange.com

Calculate tail probabilities from density() call in R –
stats.stackexchange.com

This question concerns how to implement the following problem in R. x =
rnorm(1000) hist(x,freq=FALSE) lines(density(x)) How would you calculate
the upper (or lower) tail probability for a given …

Where should the balance be between reputation of a question=?iso-8859-1?Q?=2C_and_the_jugment_of_high_rep_users_and_mods_when_in_com?=es to deleting it=?iso-8859-1?Q?=3F_=96...?=

Where should the balance be between reputation of a question, and the
jugment of high rep users and mods when in comes to deleting it? –...

I'm mostly active in Matlab related questions, and recently I checked the
highest votes for that tag (disclaimer, I have a high ranking question
there too). I have found that the #1 question: What can …

Monday, 30 September 2013

"Canonical" representation of SO(3,1)

"Canonical" representation of SO(3,1)

$SO(3,1)$ is a subgroup of $SL(4,C)$ and thus admits a "canonical"
representation on a 4-dimensional complex vector space. Is that
representation irreducible?

Mean of a random variable

Mean of a random variable

Two tire-quality experts examine stacks of tires and assign a quality
rating to each tire on a 3-point scale. Let X denote the rating given by
expert A and Y denote the rating given by B. The following table gives the
joint distribution for X and Y .
Can someone help us understand this chart...

MS Access Overflow Error

MS Access Overflow Error

I am getting an Overflow error in Access when this line runs
intAT = Nz(DLookup("at_ID", "qryAT", "at_sc_ID=" & Me.sc_ID & " AND
at_OT=0"), 0)
If I add Debug.Print Nz(DLookup("at_ID", "qryAT", "at_sc_ID=" & Me.sc_ID &
" AND at_OT=0"), 0) just before that line, it prints the id number just
fine, but still errors during the assignment on the next line.
I can also get it to work by adding a criterion to the query that limits
all the results to those that occur before a certain day and time. It ONLY
works limiting the query to before that particular time, not after an
earlier time. If any of the records after that time are included, it
overflows again. I have looked at the data that was entered after that
time and it all seems fine, but I am not sure what exactly I should be
looking for. The at_ID associated with the first record that causes it to
fail is 32838 if that helps at all.

How to recover deleted system files in MSMQ

How to recover deleted system files in MSMQ

I Unfortunatly deleted the System Files of MSMQ under,
C:\Windows\System32\msmq\storage\lqs
now i unable to send and receive messages from Queue.
HOw to recover the deleted files.
Thanks in Advance

Sunday, 29 September 2013

Alsa - how to do the similar query with alsa tools when Pulseaudio server crash and does not work

Alsa - how to do the similar query with alsa tools when Pulseaudio server
crash and does not work

Pulseaudio server sometimes does not work because the service crash
automatically, because my application depending on PA it fail to execute
following:
pactl list | sed -n '/^Sink/,/^$/p' | grep 'HDA Intel PCH' -B 5 | grep
'Volume:' | head -n1 | cut -d' ' -f2- | tr -d ' '
pactl list sources | grep -A 6 "Name: HDA Intel PCH" | tail -n 1 | perl -p
-i -e 's/.+\\s(yes|no)$/$1/'
pactl set-source-mute STRING 1
How can i do this three commands with Alsa tools (not using Pulseaudio)?
EDIT:
pactl alternative is amixer
$ cat /proc/asound/cards | grep 'HDA Intel PCH' | head -1 | awk '{print
$1}' | sed 's/ //g'
$ amixer -D hw:2
Simple mixer control 'Mic',0
Capabilities: cvolume cvolume-joined cswitch cswitch-joined penum
Capture channels: Mono
Limits: Capture 0 - 6144
Mono: Capture 4608 [75%] [24.00dB] [on]

Total the records using jdbc

Total the records using jdbc

How to iterate each record in employee database and add it to the BigDecimal
Employee
Empid Empsal
1 23.56
2 53.20
3 69.8
Using jdbc, how to iterate above data and total the Empsal records.

How do I check if Windows desktop is locked

How do I check if Windows desktop is locked

Q: In AutoIt, how do I check if Windows desktop is locked
What I have
Let's take this example AutoIt script. It pings an URL in an indefinite
loop and reports the response time in a tray tip.
While 1
$responsetime = Ping("www.google.com")
TrayTip("", $responsetime, 1)
sleep(5000)
Wend
Desired result
The new script should only ping if the desktop is not locked. But I
haven't found a reliable way to check for this
While 1
$isLocked = secretFunctionIdontKnow
If $isLocked Then
Local $responsetime = Ping("www.google.com")
TrayTip("", $responsetime, 1)
EndIf
sleep(5000)
Wend
Hint: The function WinExist("A") seems not reliable enough because a
desktop without any open windows will report back 0 (=false) even when
unlocked

Change URL without transition

Change URL without transition

I have a question concerning the Ember routing system. Hope somebody can
help.
In my Ember-App, I have a simple leaflet fullscreen map. The center and
zoom level of this map are coming from the URL query parameters. Now it
would be nice to have a simple way to keep this query parameters in sync
with the map position. So when somebody moves the map, I would like to
change the url query parameters to the new values.
When I use a simple transitionTo, I start a loop of changing the map and
updating the query parameters changing the map again and so forth.
So my first idea was to get the location implementation from the router
and changing the url manually. But I do not know how to do that. And it
also feals wrong using Ember this way.
Hope it's getting clear.
Thanks in advanced!

Saturday, 28 September 2013

iOS 7 - Play video from photos app

iOS 7 - Play video from photos app

In my application I allow the user to record videos and it saves the
videos to the default photos app. I save the video's URL into core data
and was wondering if there was any way to pull up AVPlayer with the video
from the URL saved without pulling up the UIImagePicker. Here is what I am
using to record and play videos:
record.m
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:
UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
// Handle a movie capture
if (CFStringCompare ((__bridge_retained CFStringRef) mediaType,
kUTTypeMovie, 0) == kCFCompareEqualTo) {
NSString *moviePath = [[info
objectForKey:UIImagePickerControllerMediaURL] path];
NSURL *videoURL = [info
objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory
stringByAppendingFormat:@"/vid1.mp4"];
BOOL success = [videoData writeToFile:tempPath atomically:NO];
NSLog(@"%hhd",success);
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum(moviePath, self,
@selector(video:didFinishSavingWithError:contextInfo:),
nil);
}
}
}
play.m
-(BOOL)startMediaBrowserFromViewController:(UIViewController*)controller
usingDelegate:(id )delegate {
// 1 - Validations
if (([UIImagePickerController
isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]
== NO)
|| (delegate == nil)
|| (controller == nil)) {
return NO;
}
// 2 - Get image picker
UIImagePickerController *mediaUI = [[UIImagePickerController alloc]
init];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
mediaUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *)
kUTTypeMovie, nil];
// Hides the controls for moving & scaling pictures, or for
// trimming movies. To instead show the controls, use YES.
mediaUI.allowsEditing = YES;
mediaUI.delegate = delegate;
// 3 - Display image picker
[controller presentModalViewController:mediaUI animated:YES];
return YES;
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
// 1 - Get media type
NSString *mediaType = [info objectForKey:
UIImagePickerControllerMediaType];
// 2 - Dismiss image picker
[self dismissModalViewControllerAnimated:NO];
// Handle a movie capture
NSURL *assetURL = [info
objectForKey:UIImagePickerControllerReferenceURL];
if (CFStringCompare ((__bridge_retained CFStringRef)mediaType,
kUTTypeMovie, 0) == kCFCompareEqualTo) {
// 3 - Play the video
MPMoviePlayerViewController *theMovie =
[[MPMoviePlayerViewController alloc]
initWithContentURL:[info
objectForKey:UIImagePickerControllerMediaURL]];
MPMoviePlayerViewController *movie = [[MPMoviePlayerViewController
alloc] initWithContentURL:assetURL];
[self presentMoviePlayerViewControllerAnimated:movie];
// 4 - Register for the playback finished notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myMovieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
}
}

How To Add Zig Zag Border to a Box contains background image

How To Add Zig Zag Border to a Box contains background image

I already find following perfect CSS snippet which creates zip zag border
at this link.
.h-zigzag {
background:
linear-gradient(-135deg, #333538 5px, transparent 0) 0 5px,
linear-gradient(135deg, #333538 5px, #fff 0) 0 5px;
background-color: #333538;
background-position: left bottom;
background-repeat: repeat-x;
background-size: 10px 10px;
}
As you can see the code create a perfecr zig zag border but I need to add
this border to a box which contains an image as:
.h-zigzag {
background: url(../img/grrenfooter.png) repeat-x top left scroll
transparent;
}
can you please help me to mix them? I already tried several ways but the
image disappears when I mix them!

Form doesn't validate when passing form value to the next view

Form doesn't validate when passing form value to the next view

In my index view I have a ModelChoiceField which allows me to choose
various equipments.
When I have submitted my choice, I keep the selected value in a variable
like this:
if form.is_valid():
form.save()
request.session["eq"] = form.cleaned_data['equipment']
Then I am redirected to a new view(reservation) in which I have a form
with three fields: "equipment", "date" and "reserved_by". Since I have
already chosen the equipment i want in the previous view I want it to be
filled in automatically. I managed this by doing the following in my
reservation view:
form = ReservationForm(initial={'equipment': request.session.get('eq')})
So when I run my site, the equipment field in the reservation view does
get automatically filled in, but now the form suddenly won't
validate(form.is_valid is false).
Been struggling with this for a while now so any help would be highly
appreciative.

Java GUI for cross-platform

Java GUI for cross-platform

Well, I want to develop cross-platform application with GUI on Java. And I
want that my app will look natively as much as possible. So what
GUI-library/framework I need to choose? I plan to develop for Win, Linux
and Mac OS.

Friday, 27 September 2013

chat comet nginx apache

chat comet nginx apache

I hope the gurus can help me.
file php : www.mysite.com/get_activity.php (use comet)
while(true){
$actibity = get_sql_Activity();
flush();
usleep($1000000);
}
file :/chat_view.php
<iframe src="www.mysite.com/get_activity.php"></iframe>
works fine, but when I open a tab in the browser it is locked until I
close the page that has the iframe
I was thinking to use nginx get_activity and the rest worked in apache
IN nginx (I thought about using a subdomain )
www.mysite.com/get_activity.php -> chat.mysite.com/get_activity.php
<iframe src="chat.mysite.com/get_activity.php" ></iframe>
I wanted the subdomain chat receives requests comet and the rest of the
site worked in apache, can help me with the configuration of nginx? thank
you

how to change default location of adding class in visual studio 2012

how to change default location of adding class in visual studio 2012

Is there anyway to change the location to C:\TARC\dx framework\Zero
DirectX Framework sound 0.13\Zero DirectX Framework\Codes instead of the
location as image below?

C# How to Initialize Generic class with object of type "Type"

C# How to Initialize Generic class with object of type "Type"

I recently had this problem.
doSomething(typeof(int));
doSomething(typeof(MyClassA));
doSomething(typeof(MyClassB));
public void doSomething(Type _type)
{
var myGenObj = new MyGenericClass<_type>(); // Error. Really I'd
want MyGenericClass<int>, MyGenericClass<MyClassA>, etc depending on
what's passed in.
myGenObj.doSomeGenStuff();
// more stuff...
}
I think that this can be done with reflection somehow.. Possibly there's
an easier way. I've been somewhat confused on how Type works vs Classes
under the covers. Anyways thanks for any help.
Thanks.

setting created checkbox as checked not working

setting created checkbox as checked not working

thanks for helping... I'm creating a series of html elements in
javascript, including checkboxes. I want to go ahead and mark one of the
checkboxes by default. I cannot get the 'checked' property to exist using
either pure javascript (checkbox.checked = true;) or jquery library (see
below). See my example, thank you:
function createToolbarElements(){
//------topbar-------------
var topbar = document.getElementById("topbar");
topbar.innerHTML = "ZONE: ";
//zone set
ART.regions.unshift("All");
ART.regions.push("osj");
var numRegions = ART.regions.length;
var region;
for(i=0; i<numRegions; i+=1){
region = ART.regions[i];
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = region;
checkbox.value = region;
checkbox.id = "zone"+region;
if(region === "All"){
$("zoneAll").prop("checked", true);
}
topbar.appendChild(checkbox);
var label = document.createElement('label')
label.htmlFor = region;
label.appendChild(document.createTextNode(region));
topbar.appendChild(label);
}
}

PowerShell v2.0 equivalent to "get-job | receive-job -AutoRemoveJob -Wait"?

PowerShell v2.0 equivalent to "get-job | receive-job -AutoRemoveJob -Wait"?

What is the PowerShell v2.0 equivalent to this v3.0 code snippt:
for($i=0; $i -lt $num_jobs; $i++) {
Write-Host -ForegroundColor Darkgreen "[i] Job" $i "starting..."
Start-Job -ScriptBlock $insert_data -ArgumentList 'host', 'user',
'pass', 'db', $i, $log_out[$i] | Out-Null;
}
get-job | receive-job -AutoRemoveJob -Wait
I tried the following without luck
for($i=0; $i -lt $num_jobs; $i++) {
Write-Host -ForegroundColor Darkgreen "[i] Job" $i "starting..."
Start-Job -ScriptBlock $insert_data -ArgumentList 'host', 'user',
'pass', 'db', $i, $log_out[$i] | Out-Null;
}
get-job | receive-job -Wait
get-job | remove-job
It fails on PowerShell v2.0 with:
Remove-Job : The command cannot remove the job with the 3 session
identifier be
cause the job is not finished. To remove the job, first stop the job, or
use th
e Force parameter.

Phproblems i mysql errors

Phproblems i mysql errors

When doing this i got error: "Warning: mysql_result() expects parameter 1
to be resource, boolean given in /home/chatvik/public_html/index.php on
line 17" i cant find any problems. Please help me
Row 11-18
sql = "SELECT id FROM users
WHERE user='{$_POST['user']}'
AND pass='{$_POST['passwd']}'";
$result = mysql_query($sql);
// Sätt sessionen med unikt index
$_SESSION['sess_id'] = mysql_result($result, 1);
$_SESSION['sess_user'] = $_POST['user'];
The meaning is that if there is only 1 row do...

Protect video,audio and jar copying from CD

Protect video,audio and jar copying from CD

I have made Java project. It contains jar, video and audio files. I am
making CD of that project. I want protect my files from copying.

Thursday, 26 September 2013

translate3d's z property not working on ipad (Using Phonegap)

translate3d's z property not working on ipad (Using Phonegap)

I have been working on an ios app using phonegap. I am trying to change
element's z position using -webkit-transform: translate3d property.. here
is my code
.content {
-webkit-transform-style: preserve-3d;
-webkit-transform-origin: 50% 100%;
-webkit-perspective:530;
-webkit-backface-visibility: hidden;
}
.content .activities-item{
-webkit-transform: translate3d(0,0,0) scale3d(1,1,1);
-webkit-transition :all .4s;
-webkit-backface-visibility: hidden;
opacity: 1;
}
and on click , I am adding active class to content container.
.content.active .activities-item{
-webkit-transform: translate3d(0,0,450px) scale3d(1,1,1);
opacity: 0;
}
This code is working fine on webkit browser but not in iPad. On iPad there
is no issue on changing x,y position but z property is not working at all.
Any suggestion..
Not: I'm trying to make zoom script that works on iPad.

Wednesday, 25 September 2013

Issue invoking WatchService inside a singleton bean

Issue invoking WatchService inside a singleton bean

we wanted to watch a file periodically for changes, we are using jboss 7 .
Following is my code snippet. I initialized the watcher in the
postconstruct method of singleton bean and scheduled a method to poll
watch events. I could observe the changes when i modify the file very
first time, however the subsequent modifications to the file are not
recieved . Can anyone please let me know what could be the issue
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@Interceptors(NonThrowingPostConstructInterceptor.class)
@Singleton
@Service
@LocalBinding(jndiBinding=IConciergeHeartBeatProducerService.JNDI_LOCAL_BINDING)
public class HeartBeatProducerService extends EMSingletonService
implements IHeartBeatProducerService{
@EJB(mappedName=IMessageService.JNDI_LOCAL_BINDING)
public IMessageService messageService;
@EJB(mappedName=ICommandExecutionService.JNDI_LOCAL_BINDING)
public ICommandExecutionService commandService;
private final static String LAST_OPERATION_COMPLETED="Last Operation
Completed";
private final static String STATUS="Status";
private WatchService watcher;
private Path dir;
private String concServer;
public static final String TOPIC="foo";
private IMLogger logger = new IMLogger("foo");
private String content=null;
@PostConstruct
@Override
public void init() {
// TODO Auto-generated method stub
super.init();
try {
watcher = FileSystems.getDefault().newWatchService();
dir=Paths.get("/shared/foo");
dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
logger.entering(0,
IHeartBeatProducerService.class.getSimpleName(), "Initializing
Heart Beat", new String[]{"Entered"});
} catch (IOException e) {
e.printStackTrace();
}
}
@Schedule(second="*/10", minute = "*", hour="*")
private void checkStatus()
{
logger.entering(0, IHeartBeatProducerService.class.getSimpleName(),
"Checking Status", new String[]{"Entered"});
final String[] command={"pidof","server"};
commandService.run(command, null, false);
concServer=(commandService.getExitCode()==0)?"UP":"DOWN";
if(concServer.equals("UP"))
{
watch();
}
else
{
content="foo:Failed";
}
produce();
}
public void watch()
{
logger.entering(0,
IHeartBeatProducerService.class.getSimpleName(), "Entering
watch()", new String[]{"Entered"});
WatchKey key = null;
try
{
key = watcher.take();
}
catch (InterruptedException e)
{
logger.error(HeartBeatProducerService.class.getSimpleName(),"Interupted
Exception " + e.getMessage());
}
for ( WatchEvent<?> event: key.pollEvents())
{
WatchEvent.Kind kind = event.kind();
logger.info(HeartBeatProducerService.class.getSimpleName(),"Watch
Event :" + kind.name());
if(kind.name().equals("OVERFLOW"))
{
continue;
}
if(kind.name().equals("ENTRY_MODIFY"))
{
Path concLog = (Path) event.context();
logger.info(ConciergeHeartBeatProducerService.class.getSimpleName(),"Modified
File Name:" + concLog.getFileName());
if(concLog.endsWith("current_status.txt"))
{
logger.info(HeartBeatProducerService.class.getSimpleName(),
"Reading Status");
readStatus();
}
}
}
boolean valid = key.reset();
if ( !valid)
{
logger.error(HeartBeatProducerService.class.getSimpleName(),"Key
Unregistered");
}
}
private void parse(String output)
{
// parse file contents
}
private void readStatus() {
//read status and parse()
}
private void produce()
{
try {
messageService.publish(TOPIC, content, PublishType.ASync);
} catch (MessageException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There is already a link explaining the same with @Asynchronous tag (EJB
3.1 and NIO2: Monitoring the file system) . however I need to know what
could be wrong in this approach.

Thursday, 19 September 2013

Play 2/Ebean ManyToMany JSON Results

Play 2/Ebean ManyToMany JSON Results

I'm using Play! 2.1.4 framework with Ebean/MySQL.
The system basically keeps track of courses, and their requirements. Eg,
if you want to take Advanced Art, you must first take regular Art. This is
a ManyToMany Relationship, as I understand, but I could be wrong.
Here's my model: @Entity public class Course {
public static Model.Finder<Long,Course> find = new
Model.Finder<Long,Course>(Long.class, Course.class);
@Id
private Long id;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable( name = "course_course",
joinColumns = @JoinColumn(name = "course_id1"),
inverseJoinColumns = @JoinColumn(name = "course_id2"))
private Set<Course> courseRequirements = new HashSet<Course>();
private String availability;
private Long category;
@Lob
private String description;
@Lob
private String otherRequirements;
private Long bucketId;
// Getters and setters...
Here's how I return the JSON to my frontend:
List<Course> courses =
Ebean.find(Course.class).fetch("courseRequirements").findList();
JsonContext jsonContext = Ebean.createJsonContext();
return ok(jsonContext.toJsonString(courses));
However, in the "courseRequirements" key in the JSON, it opens up a new
array with full course objects in it. I just want to get an array of the
course IDs it requires, for example: courseRequirements: [3, 5] means
that: this course requires you to take courses with ID 3 and 5 first.
I rewrote my getter to this: public Set getCourseRequirements() { Set
requiredCourseIds = new HashSet();
for(Course course : courseRequirements)
{
requiredCourseIds.add(course.getId());
}
return requiredCourseIds;
}
because I thought that Ebean will pull that when trying to fill in the
JSON key, but that's not the case.
How can I change it so that it only returns an array of course IDs for the
courseRequirements key, instead of full objects?
Thanks!

Subtract two CHARINDEX values

Subtract two CHARINDEX values

This works fine..
SELECT CHARINDEX(CHAR(10), AFIELD)[first]
,CHARINDEX(CHAR(10), AFIELD,CHARINDEX(CHAR(10), AFIELD)+1)[second]
FROM SOMETABLE
But when I try to subtract the two, the results are empty..
I have followed the information posted here and at -
http://phelabaum.com/archive/tag/charindex/
SELECT SUBSTRING(AFIELD,
CHARINDEX(CHAR(10),AFIELD)+1,
CHARINDEX(CHAR(10),AFIELD,CHARINDEX(CHAR(10),AFIELD)+1) -
CHARINDEX(CHAR(10),AFIELD)) as [first_length]
FROM SOMETABLE
When I run this, I get: the message:
Msg 537, Level 16, State 3, Line 1 Invalid length parameter passed to the
LEFT or SUBSTRING function.
The field is CHAR(10) or Line Feed delimited.

Getting exception on second call to web service

Getting exception on second call to web service

I have a service that I call (using cxf to create the client code). After
deploying I can make my first service call with no problem. However on my
second call I get the following error:
javax.net.ssl.SSLHandshakeException: SSLHandshakeException invoking
https://ifsy-soa-dev01.oracleoutsourcing.com:443/soa-infra/services/Publishers/ItemAddSyncMasterItemListEBMPublisher/item-add-dev-send-to-PS:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
What is strange is that on my local development Weblogic server I don't
see this issue. Has anybody resolved this issue before?
Much thanks in advance!

function doesn't display the return value?

function doesn't display the return value?

Why it doesn't return any value? The output should be 155 but it always
display 0. why?
int main()
{
int i=5;
printf("%d",fun(fun(fun(fun( fun(i))))));
return 0;
}
void fun(int i)
{
if(i%2) return (i+(7*4)-(5/2)+(2*2));
else return (i+(17/5)-(34/15)+(5/2));
}
But if I change
void fun(int i) // It doesn't work, case 1
to
int fun(int i) //It works fine, case 2
If fun doesn't return any value in case 1 ( void fun(int i) ), then how come
fun(fun(fun(fun( fun(i)))))); this statement is working?

Setting up SDL2 with MinGW and Sublime Text

Setting up SDL2 with MinGW and Sublime Text

I keep getting the error "undefined reference to WInMain@16" when I
include SDL2/SDL.h in my C file. It's a simple "Hello" program with the
SDL include, and if I remove the SDL include it compiles just fine (as
expected).
The problem is I'm new with the compile flags for C (and SDL) and I'm not
sure how I link(?) the files together (or if that's necessary). I'm coding
using Sublime Text 3.
(D:\CODE\Privata Projekt\C\test.c)
#include <stdio.h>
#include "SDL2/SDL.h"
int main(int argc, char *argv[]) {
printf("hello\n");
return 0;
}
My paths to MinGW and SDL2 is:
C:\MinGW\include\SDL2 (all my sdl header files reside in here too)
C:\MinGW\include\SDL2\bin
C:\MinGW\include\SDL2\lib
C:\MinGW\include\SDL2\share
And I build the program with
gcc test.c -o test

SVN: status of svn import

SVN: status of svn import


in my PHP-Script I create folders and files locally which I want to put in
my SVN. I use a .cmd-file containing svn import
PATH/TO/MY/FOLDERS/AND/FILES, which works without problem. After the svn
import was successfull, I want to delete the folders I just put into SVN
locally with the same .cmd-script. So I have to say something like
(pseudocode)
if(svn import PATH/TO/FOLDERS == successful){delete PATH/TO/FOLDERS locally}
Is such a thing even possible? I don't know much about .cmd-scripting, so
please forgive my question if it is stupid.

Applying javascript to check file size and extension

Applying javascript to check file size and extension

here is my script. What I am trying to do is to trigger it using onchange
event. But it seems does not work very well. I have tried edit here and
there but still facing problems. As for my latest edit below, the problem
is, there is 2 files to be uploaded, but only the second one will display
alert message, while the first one will just receive any file.
<script>
function checkFile()
{
var node_list = document.getElementsByTagName('input');
for (var i = 0; i < node_list.length; i++)
{
var node = node_list[i];
if (node.getAttribute('type') == 'file')
{
var sFileName = node.value;
var sFileExtension =
sFileName.split('.')[sFileName.split('.').length - 1];
var iFileSize = node.files[0].size;
var iConvert=(node.files[0].size/10485760).toFixed(2);
}
if (sFileExtension != "pdf" && sFileExtension != "doc" &&
sFileExtension != "docx" && iFileSize>10485760)
{
txt="File type : "+ sFileExtension+"\n\n";
txt+="Size: " + iConvert + " MB \n\n";
txt+="Please make sure your file is in pdf or doc format and
less than 10 MB.\n\n";
alert(txt);
}
}
}
</script>
my form,
<input type="file" name="file" id="confirm" onchange="checkFile()">
<input type="file" name="file" id="approveletter" onchange="checkFile()">

Wednesday, 18 September 2013

how to make an installer with SQL Server database

how to make an installer with SQL Server database

I have an inventory system and an export of a SQL Server database and I
want to make an installer of it. But the problem is how can I install an
SQL Server database? Can I join it in the installer maker in visual studio
or is there any other way?

Invoke another Worklight app page from an Worklight app

Invoke another Worklight app page from an Worklight app

All,
I would like to know if it is possible to make interactions among
Worklight apps in the same device(phone/tablet). For example, if an
enterprise plans to launch a bunch of Worklight apps in their local app
store and wanted to show a common page in all the Worklight apps they
publish, how we can approach this with making a call to another Worklight
app from an worklight app.
Thanks Paul

C# Regular Expression filtering characters

C# Regular Expression filtering characters

I am having a string in C# and I would like to filter out (throw away) all
characters except for digits i.e. 0 to 9. For example if I have a string
like "5435%$% r3443_+_+**¨i¨e¡û", then the output should be 54353443. How
can this be done using regular expression or something else in C#?
Thanks

g++: error: unrecognized option ‘--as-needed’

g++: error: unrecognized option '--as-needed'

I am using Ubuntu 12.10 with a gcc version 4.6.3. I am trying to build my
code and getting an error when using 'make' command
g++: error: unrecognized option '--as-needed'
My Makefile looks as follows:
LFLAGS = -Wl,-rpath,. -Wl,-rpath-link,../bin --as-needed
LDFLAGS = $(RPATH) $(RPATHLINK) -L$(USRLIB) --as-needed
Previously this code was successfully building on RedHat Linux. But now I
need to run this code on Ubuntu.
If anyone knows about this. Please help
Regards Gaurav

Debug Assertion Failed File, tokenScanner, and text files

Debug Assertion Failed File, tokenScanner, and text files

I have written a program that processes text files one at a time and
extract relevant information. My program works well with some of the text
files and not others. There is no obvious difference between the files
that run seamlessly through my program and those that don't.
As far as the problematic files are concerned: 1) the program opens the
file 2) it reads in and processes a good chunk of the lines one at a time
as it should but then it reaches a problem line and gives the error
message:
"Debug Assertion Failed File: f:/dd/vctools/crt_bld/self_x86/src/isctype.c
Line: 56 Expression: (unsigned)(c+1) <= 256"
When I enter the debugger mode the problem seems to arise from the
"while(tokenScanner)" loop in my code below. I pulled up the content of
the problem line being processed and compared that across a couple of
problem files and I found that the Assertion Failure message pops up at ""
where the last token being processed is ">". It's not clear to me why this
is a problem. This particular token in the original text file is
contiguous with "
Here is the relevant portion of my code:
#include <string>
#include <iostream>
#include <fstream> //to get data from files
#include "filelib.h"
#include "console.h"
#include "tokenScanner.h"
#include "vector.h"
#include "ctype.h"
#include "math.h"
using namespace std;
/*Prototype Function*/
void evaluate(string expression);
Vector<string> myVectorOfTokens; //will store the tokens
Vector<string> myFileNames;
/*Main Program*/
int main() {
/*STEP1 : Creating a vector of the list of file names to iterate over for
processing*/
ifstream infile; //declaring variable to refer to file list
string catchFile = promptUserForFile(infile, "Input file:");
string line; //corresponds to the lines in the master file containing
the list files
while(getline(infile, line)){
myFileNames.add(line);
}
/* STEP 2: Iterating over the file names contained in the vector*/
int countFileOpened=0; //keeps track of number of opened files
for (int i=1; i< myFileNames.size(); i++){
myVectorOfTokens.clear(); //resetting the vector of tokens for
each new file
string fileName;
string line2;
ifstream inFile;
fileName= myFileNames[i];
inFile.open(fileName.c_str()); //open file convert c_str
if (inFile){
while(!inFile.eof()){
getline(inFile, line2);
evaluate(line2);
}
}
inFile.close();
countFileOpened++;
}
return 0;
}
/*Function for Extracting the Biographer Name*/
void evaluate(string line){
/*Creating a Vector of Tokens From the Text*/
TokenScanner scanner(line); //the constructor
while (scanner.hasMoreTokens()){
string token=scanner.nextToken();
myVectorOfTokens.add(token);
}
}

Navigate to subdirectory(windows) using wildcard character

Navigate to subdirectory(windows) using wildcard character

If suppose I need to navigate to a subfolder using wildcard character what
is the command
Example
My current directory is c:\Users\Test
I have only one sub folder as 3(only one folder)
I want to navigate to c:\Users\Test\3
cd * //doesn't work
cd *. * //doesn't work
What is the command to navigate?

Not sure about where clause of this SQL query

Not sure about where clause of this SQL query

My goal is to return a list of the names of companies that have employees
living in both San Fran and LA. Here is my query so far, along with the
schema:
select distinct company_name
from Works natural join Employee
where city = 'San Fran' or city = 'LA';
create table Employee(
Lastname varchar(10),
FirstName varchar(10),
MidInitial char(1),
gender char(1),
street varchar(10),
city varchar(10),
primary key(Lastname, FirstName, MidInitial));
create table Works(
Lastname varchar(10),
FirstName varchar(10),
MidInitial char(1),
company_name varchar(20),
salary numeric(8,2),
primary key(Lastname, FirstName, MidInitial, company_name),
foreign key(Lastname, FirstName, MidInitial) references Employee,
foreign key(company_name) references company);
I understand that right now, my query is returning a list of all the
companies with employees that either live in San Fran or LA, or both...
What would be the way to go about using both an AND and an OR on the where
clause so as to get only the companies that have employees living in BOTH
cities?
Thanks!

updating page content after submitting

updating page content after submitting

i am using bootstrap modal with a form but i face problem with updating
the page content after submitting and alerting by a message.
$(function(){
$("button#submit").click(function(){
$.ajax({
type: "POST",
url: "customers.php",
data: $('form.customers').serialize(),
success: function(msg){
$("#message").html(msg)
$("#newcustomer").modal('hide');
},
error: function(){
alert("failure");
}
});
return false;
});
});

Tuesday, 17 September 2013

Compiler not throwing error message for wrong usage of variable as array

Compiler not throwing error message for wrong usage of variable as array

I came across the below problem in a book and on my system result is
always "True" . As per my understanding, the reason for this is "int c" is
optimized by compiler, hence the if() statement has no effect but i was
under the impression that this would generate a error message for using
c[a][b] as 'c' is not an array.
1 #include<stdio.h>
2
3 int main()
4 {
5 int a[2] = {0,0};
6 int b[1] = {0};
7 int c;
8 getchar();
9 if(a[b[c]] == c[b][a])
10 printf("True");
11 else
12 printf("False");
13 }
Can anyone please help me clear my understanding?

SQL Sum sub-query with joined tables?

SQL Sum sub-query with joined tables?

I have a forum site with posts (gems) and file attachments (gemdetail)
along with replies (gems) to the posts and the replies can also have file
attachments (gemdetail). Since both posts and replies are stored in the
same table, it makes for an interesting left join which selects all posts
with associated replies and detail.
I want to add another table to the mix (rating) which allows the user to
rate each post. I then want to be able in the same query to get the sum
total rating for each post. How to add sum(rating) so each row of the
output will have the sum for the gemid. I know I need a sum sub-query
(derived table w/ ad-hoc result sets) similar to the one found here, but
it is above my skill set. Thanks in advance.
The table structure is as follows
table: gems
gemid title replygemid
----- ----- ----------
220 map NULL
223 inhabitants NULL
403 reply to map 220
table: gemdetail
gemid filename
------ --------
220 uganda-map.jpg
220 mozambique-map.jpg
223 uganda-inhabitants.jpg
223 kenya-inhabitants.jpg
403 mona-lisa-x8.jpg
table: rating (to be added)
gemid rating
----- -------
220 1
220 5
223 3
403 -1
My current (simplified) query
SELECT g.gemid as ggemid, g.title as gtitle, gemdetail.filename as
gfilename, r.filename as rfilename
FROM (SELECT gems.* FROM gems ) g
LEFT JOIN
(SELECT title, x.gemid, x.replygemid, x.userid, y.filename from gems x
LEFT JOIN gemdetail y ON x.gemid = y.gemid ) r ON g.gemid = r.replygemid
LEFT JOIN gemdetail ON g.gemid = gemdetail.gemid
Results may look like this
ggemid replygemid gtitle gfilename rfilename
220 403 Map uganda-map.jpg
mona-lisa-x8.jpg
220 403 Map mozambique-map.jpg
mona-lisa-x8.jpg
223 NULL Inhabitants uganda-inhabitants.jpg NULL
223 NULL Inhabitants kenya-inhabitants.jpg NULL
223 NULL Inhabitants kenya-inhabitants.jpg NULL

Set console properties in another class

Set console properties in another class

I have this weird problem where I have to set the console parameters like
the title, backcolor, forecolor... and don't want to do it over and over.
So I want to make a class that has a method that does it for me in another
project. The why is not so important, I basically want to make common code
to share between projects.
Something like :
// Console type project :
public static class Program
{
public static void Main()
{
SetConsoleParameters(this.Console);
}
}
// Class library
public class SomeLibrary()
{
public Console SetConsoleParameters(Console console)
{
console.Title = "Nice title";
console. // Etc...
}
}
I know you can't pass a static class like the console as a parameter and
you can't access the console by with this but is it somehow possible to
set things up like above ? (In a class that is not in the Console Project.

IndexError: too many indices when working with pandas data

IndexError: too many indices when working with pandas data

wrote a function that finds the peaks and troughs a signal and outputs to
two Sjects from the pandas library called mintab and maxtab.
I want to plot this data as a scatter plot so i wrote this:
xMax = maxtab[:,0]
yMax = maxtab[:,1]
xMin = mintab[:,0]
yMin = mintab[:,1]
mpl.rc('figure', figsize=(20, 2)) # configure plot
window size
plt.scatter(xMax, yMax, color='g', alpha=1)
plt.scatter(xMin, yMin, color= 'r', alpha = 1)
But i keep getting an error that says: IndexError: too many indices and
points to the line xMin = mintab[:,0]
I don't understand why this is happening and i can't find anything on
google about it.

Creating dynamic object names-- Java

Creating dynamic object names-- Java

Hey i need to dynamically name an object
something like this:
for (int i = 0; i<5; i++)
{
Object i = someobject();
}
Im using apache POI and it requres the sheet names to be different and
since im doing a loop I cant hardcode the sheet name
SXSSFSheet sheet

New date to string shows as day before because of time zone

New date to string shows as day before because of time zone

How can I display a date to behave like that day regardless of the users
time-zone?
>>> new Date('2013-09-17')
Date {Mon Sep 16 2013 20:00:00 GMT-0400 (Eastern Standard Time)}
I'm trying to use the jquery datepicker formater, however when I pass the
date object it's off by a day. How can I make sure that the users timezone
is disregarded?

Sunday, 15 September 2013

Building a project with Maven in Codenvy

Building a project with Maven in Codenvy

I am new to Maven and Codenvy. Trying to build a simple Jar project there.
The build fails everytime, although I seem to include all necessary
dependencies in pom.xml file.
Here's the project:
https://codenvy.com/factory?v=1.0&pname=simplejar&wname=ivantsoft&vcs=git&vcsurl=http%3A%2F%2Fcodenvy.com%2Fgit%2F16%2F81%2F89%2Fworkspacepyk15s4hwbfabmg6%2Fsimplejar&idcommit=2af3588e343317907905b306d7faa3db5674d068&action=openproject&ptype=Jar
In my pom.xml I have:
<repositories>
<repository>
<id>biojava-maven-repo</id>
<name>BioJava repository</name>
<url>http://www.biojava.org/download/maven/</url>
</repository>
</repositories>
...
<dependency>
<groupId>org.biojava</groupId>
<artifactId>biojava3-core</artifactId>
<version>3.0.6</version>
<scope>test</scope>
</dependency>
...
And in my java file I have: ...
import org.biojava3.core.sequence;
...
What am I doing wrong here?

JSON Parse: Not parsing with javascript

JSON Parse: Not parsing with javascript

I get json data with jquery.ajax and dataType is "json" But I have some
problem
That is my json data :
{"stock":{"head":["name","est","date"],"body":[{"row":["TEST","10.58","2013-09-05
13:37:20"]}]},"year":{"head":["name","est","date"],"body":[{"row":["TEST","0","2013-09-05
13:37:35"]}]}}
And that is my javascript code:
var getdata = $.ajax({
type : 'POST',
url : 'testjson.php',
data : data,
dataType : 'json'
});
getdata.done(function(result){
var queryHead = result.stock.head; // That is return with data
var queryBody = result.stock.body; // But that is not return . empty
});
Json data return successfully but not correctly parsing queryHead is work
but queryBody not work

Buiding category tree with PHP

Buiding category tree with PHP

I have that kind of table
ID | NAME | PARENT_ID
1 a0 0
2 b0 0
3 a1 1
4 a2 1
5 a11 3
....
$categories[]={$id,$name,$parent_id}
And i need to build array-tree of these categories...
May someone help me with such task? Would be great.
Thanks.

Singleton With Arguments

Singleton With Arguments

Is it a good idea having a Singleton that accepts an argument in its
static constructor? Can I have concurrency problem?
public class DataHelper {
private static DataHelper singleton = null;
private Listener<Object> listener;
public static DataHelper getInstance(Listener<Object> listener) {
if(singleton == null) {
singleton = new DataHelper();
}
singleton.listener = listener;
return singleton;
}
}

Java wrap text to polygon

Java wrap text to polygon

I am using Java Graphics2D to draw basic and complex polygons which will
have text of varying lengths and fonts in it. What I'm trying to achieve
is that the text drawn is perfectly wrapped and clipped to fit within the
polygon.
The code I have so far is this:
int[] xp = { x + width /2, x + width -1, x };
int[] yp = { y, y + height - 1, y + height - 1 };
g.setColor(fill.color1);
g.fillPolygon(xp, yp, xp.length);
g.setColor(border.color);
g.setStroke(new BasicStroke((float) (border.width * zoom),
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
g.drawPolygon(xp, yp, xp.length);
// Later on in the method..
g.drawString(text, textx, texty);
This draws the shape and text fine but the text is just one long line. I
want it to fit neatly into the polygon.

MySQL error when i add apostraphe in form

MySQL error when i add apostraphe in form

When I add a apostraphe into a form that saves to a MySQL database i get
the below error
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near 'We are one of
the UKs leading suppliers of hotel toiletries and ame' at line 1
Here is my code:
$result = mysql_query("UPDATE admin SET aboutcontent='$aboutcontent',
abouttitle='$abouttitle', aboutside='$aboutside',
aboutsidetitle='$aboutsidetitle'")
Is there a way round this?

How to add Spring libs using Maven

How to add Spring libs using Maven

I learned Spring via Spring In Action 3 few month ago. I downloaded Spring
libraries from official site (list was like in SIA3(aop, asm, aspects,
beans ...)), added them to my project and everything worked fine. Now I
want to use Maven, but I am getting a lot of errors and sinking in
searching what library to add.
I am newby, dont know all Spring dependencies(within it libs) and the
question is not about my errors, but about the way to add all Spring
libraries to my project via Maven. How do you usually add Spring libs
using Maven?

Saturday, 14 September 2013

can html canvas draw uploaded images?

can html canvas draw uploaded images?

I am trying to create an uploading image resizing function using
javascript. However, using filereader to convert upload files into base64,
gives no image on canvas. Rather, if I use an external image, and convert
that into base64, the function works like a charm. How would that be? What
is the problem?
Here is my code, it's pretty long.
//When changes are made to our input field
$ ('#input-file').change (function (evt) {
//The selected file is recovered
var file = evt.target.files [0];
//And processFiles function that will resize and send the file to the
server is started
processFiles (file);
});
processFiles = function (file) {
var reader = new FileReader ();
//When the file has been completely read, the function will be
executed ResizeImage
reader.onloadend = function (evt) {
//Reader.result represents our base64 encoded file
ResizeImage (reader.result, file);
};
//Allows you to play the file
reader.readAsDataURL (file);
};
ResizeImage = function (data, file) {
var fileType = file.type,
maxWidth = 960
maxHeight = 960;
//The file is loaded in a <img>
var image = new Image ();
image.src = data;
//Once the image is loaded, the following operations are performed
image.onload = function () {
//The ImageSize function calculates the final file size keeping the
proportions
var size = ImageSize (image.width, image.height, maxWidth, maxHeight)
ImageWidth = size.width,
imageHeight = size.height,
//We create a canvas element
//canvas = document.createElement ('canvas');
canvas=document.getElementById('hahaha')
canvas.width = ImageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext ("2d");
//DrawImage will allow resizing the image
//This is our image here
var img=document.getElementById('haha')
ctx.drawImage (img, 0, 0, ImageWidth, imageHeight);
//Allows you to export the contents of the canvas element (our
resized image) base64
data = canvas.toDataURL(fileType);
alert(data)
//All the elements used for resizing is suppressed
delete image;
delete canvas;
//SubmitFile (data);
}
};
//Function to resize an image keeping the proportions
ImageSize = function (width, height, maxWidth, maxHeight) {
var newWidth = width,
newHeight = height;
if (width> height) {
if (width> maxWidth) {
newHeight = maxWidth / width;
newWidth = maxWidth;
}
else {}
if (height> maxHeight) {
newWidth = maxHeight / height;
newHeight = maxHeight;
}
}
return {width: newWidth, height: newHeight};
};

Javascript variable assignment of object returns string

Javascript variable assignment of object returns string

I am trying to run the following code:
var status = null;
$.ajax({
type: "GET",
url: "/status",
success: function(data, textStatus, jqXHR){
status = data;
},
error: function(jqXHR, textStatus, errorThrown){
console.error(textStatus + ": " + errorThrown);
}
});
The interesting part is the following line: status = data;
In the debugger I can see that data has the value Object {7100665: 0,
8800798: 0}. jQuery correctly parses the JSON-string returned from the
server into an object.
However, one line later the global variable status has the value "[object
Object]" and behaves like a string object - string does not have the
object assigned to it as expected.
It looks like there was an implicite typeof call in the assignment going
on, which cannot be, right? Is there some more going on that I am not
aware of? The Content-Type of the ajax call is application/json.
What am I missing/doing wrong?

avoiding a duplicate $(document).ready(function() tag

avoiding a duplicate $(document).ready(function() tag

I am at a loss to explain why this snippet of code only works for the
first function. The image swap fails to execute.
$(document).ready(function() {
$(function(){
// tip
$("#tip").fancybox({
'width' : 420,
'height' : 300,
'autoScale' : true,
'autoDimensions' : true,
'transitionIn' : 'elastic',
'transitionOut' : 'fade',
'overlayColor' : '#111',
'type' : 'iframe'
});
});
// image swap
$("#image1, #image2").click(function(){
switch(this.id)
{
case 'image1':
_(this.id,"../../img/answers.png","../../img/b13a(AC)ans.png");
break;
case 'image2':
_(this.id,"../../img/answers(biggest4).png","../../img/b13b(AC)ans.png");
break;
}
function _(id,main, alt){
if($("#"+id).attr("src") == main) $("#"+id).attr("src", alt);
else $("#"+id).attr("src", main);
}
});
If I place the second function within a separate
$(document).ready(function(), both routines work, but I'm trying to avoid
the duplication.

access object method from another class

access object method from another class

I'm new to Java and oriented-object and I'm trying to create a chat
program. Here's what I'm trying to do:
Somewhere in my Main.java
Window window = new Window;
Somewhere in my Window.java
History history = new History()
Somewhere in my History.java:
public History()
{
super(new GridBagLayout());
historyArea = new JTextArea(15, 40);
historyArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(historyArea);
entryArea = new JTextField(20);
entryArea.addActionListener(this);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(scrollPane, gbc);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(entryArea, gbc);
}
public void actionPerformed(ActionEvent event)
{
String text = entryArea.getText();
historyArea.append(text + newline);
entryArea.selectAll();
historyArea.setCaretPosition(historyArea.getDocument().getLength());
}
public JTextArea getHistoryArea()
{
return historyArea;
}
public void addToHistoryArea(String pStringToAdd)
{
historyArea.append(pStringToAdd + newline);
historyArea.setCaretPosition(historyArea.getDocument().getLength());
}
Now that I'm in Server.java, I want to use the method addToHistoryArea.
How can I do that without making my historyArea static? Because if I
understand well how static works, I couldn't have different historyArea
even if I create a new History...
Thanks for your help and tell me if I got it all wrong!

how actually tcp protocol works?

how actually tcp protocol works?

So i started to learn tcp/ip protocol stack. But in all sources tcp
protocol is described too blurry. The main think i want to know how
actually tcp protocol programly implemented. how applyed protocols
communicate with tcp protocol. what is interface of this communication.
For now i think that applied protocols are implemented directly in applied
program: lets say browser implement HTTP protocol and this protocol
communicate with centralized implementation of tcp protocol which is
implemented in OS. IS it correct i have lack of sources from which i can
learn this.please recomend me something to read.

Entity Framework - Linq : how query to take 2 first ordered and grouped list

Entity Framework - Linq : how query to take 2 first ordered and grouped list

I have a large table with 6000000 record like this
format(Acc,sDate,Serial,Amount,...)
Acc,date,serial is PKey
To show my problem, created small code
public class Cheque
{
public string Account{ get; set; }
public string Serial{ get; set; }
public string StartDate { get; set; }
// ... public string Amount { get; set; } ...
}
var list = new List<Cheque>();
list.Add(new Cheque() { Account = "1", Serial = "1", StartDate =
"20080120" });
list.Add(new Cheque() { Account= "1", Serial= "2", StartDate =
"20080120" });
list.Add(new Cheque() { Account= "1", Serial= "3", StartDate =
"20080120" });
// each acc have 100 to 300 record per date ,for simplicity 3 obj added
list.Add(new Cheque() { Account= "1", Serial= "1", StartDate =
"20110120" });
list.Add(new Cheque() { Account= "1", Serial= "2", StartDate =
"20110120" });
list.Add(new Cheque() { Account= "1", Serial= "3", StartDate =
"20110120" });
list.Add(new Cheque() { Account= "1", Serial= "1", StartDate =
"20120120" });
list.Add(new Cheque() { Account= "1", Serial= "2", StartDate =
"20120120" });
list.Add(new Cheque() { Account= "1", Serial= "3", StartDate =
"20120120" });
list.Add(new Cheque() { Account= "2", Serial= "1", StartDate =
"20090320" });
list.Add(new Cheque() { Account= "2", Serial= "2", StartDate =
"20090320" });
list.Add(new Cheque() { Account= "2", Serial= "1", StartDate =
"20100417" });
list.Add(new Cheque() { Account= "2", Serial= "2", StartDate =
"20100417" });
list.Add(new Cheque() { Account= "2", Serial= "1", StartDate =
"20120314" });
list.Add(new Cheque() { Account= "2", Serial= "2", StartDate =
"20120314" });
expected list only tow set with nearest date from each AccountNumber
Acc Serial Date
"1", "1", "20120120" //first resultSet with AccountNumber= 1
"1", "2", "20120120"
"1", "3", "20120120"
"1", "1", "20110120" //second resultset with AccountNumber= 1
"1", "2", "20110120"
"1", "3", "20110120"
"2", "1", "20120314" //first resultSet with AccountNumber= 2
"2", "2", "20120314"
"2", "1", "20100417" //second resultset with AccountNumber= 2
"2", "2", "20100417"
plz help me how can query this with linq how group by (or distinct ) and
take tow first set, like this

How to change the response.redirect URL value?

How to change the response.redirect URL value?

I send value to another page by response.redirect the URL have the value
and it is very too long :
=">http://x.elarabygroup.com/SiteLogin.aspx?token=CAACgVEYG6y4BAPpCA576tZCOVTaiStohQHcFMj8TnkYDiIBWnuQjoMSRMSjmTlZCK0JhdyWP8MYiFQELLGUMht07vKZCVLaxz7gBASydeG5PqBB9dypqvEh7tyTR1nZCRvZBITNEcnkDj00pFxNGKfi9v8U5UkVAjQlLuY08aVANUgZC9dZAi852216uCsTgpcZD#=
I want to hide or display another url as http://x.elarabygroup.com/playgame/
Response.Redirect("http://x.elarabygroup.com/SiteLogin.aspx?token=" +
respnse);

Test including redirect_to fails with rspec but application is working as expected. Chapter 9.6.6 of Michael Hartl book (v 4.0)

Test including redirect_to fails with rspec but application is working as
expected. Chapter 9.6.6 of Michael Hartl book (v 4.0)

I'm trying to solve a problem 6 of chapter 9.6 of Michael Hartl book Rails
v 4.0.
Though everything looks fine in rspec test:
describe "should redirect a logged in user to root url if user tries to
hit new in users controller" do
let(:user) {FactoryGirl.create(:user)}
before do
sign_in user
get new_user_path
end
specify{expect(response).to redirect_to(root_url)}
end
describe "should redirect a logged in user to root url if user tries to
hit create in users controller" do
let(:params) do {user: {name: "Tester", email: "test@example.com",
password: "password",
password_confirmation: "password"}}
end
let(:user) {FactoryGirl.create(:user)}
before do
sign_in user
post users_path, params
end
specify{expect(response).to redirect_to(root_url)}
end
And here is my controller snippet:
class UsersController < ApplicationController
before_action :is_signed_in, only: [:new, :create]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
sign_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
private
def is_signed_in
redirect_to(root_url) if signed_in?
end
end
sign_in method in utilities.rb
def sign_in(user, options = {})
if options[:no_capybara]
# Signin when not using capybara
remember_token = User.new_remember_token
cookies[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
else
visit signin_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign In"
end
end
But my testcases are failing with following errors:
Failures:
1) Authentication signin with valid information should redirect a logged
in user to root url if user tries to hit create in users controller
Failure/Error: specify{expect(response).to redirect_to(root_url)}
Expected response to be a redirect to <http://www.example.com/> but was
a redirect to <http://www.example.com/users/2>.
Expected "http://www.example.com/" to be ===
"http://www.example.com/users/2".
# ./spec/requests/authentication_pages_spec.rb:69:in `block (5 levels) in
<top (required)>'
2) Authentication signin with valid information should redirect a logged
in user to root url if user tries to hit new in users controller
Failure/Error: specify{expect(response).to redirect_to(root_url)}
Expected response to be a <redirect>, but was <200>
# ./spec/requests/authentication_pages_spec.rb:55:in `block (5 levels) in
<top (required)>'
Finished in 5.22 seconds
95 examples, 2 failures
Failed examples:
rspec ./spec/requests/authentication_pages_spec.rb:69 # Authentication
signin with valid information should redirect a logged in user to root url
if user tries to hit create in users controller
rspec ./spec/requests/authentication_pages_spec.rb:55 # Authentication
signin with valid information should redirect a logged in user to root url
if user tries to hit new in users controller
Randomized with seed 58509
I tried to debug, but not able to figure out exact problem. Can anyone
help me on this ?

Friday, 13 September 2013

Xcode 4.6 Debugger: What does the blue italic text mean?

Xcode 4.6 Debugger: What does the blue italic text mean?

Here's a screenshot:

Clearly it indicates that the x coordinate of my struct differs from the y
coordinate, however their values are the same. How do they differ?
While we're at it... This one should be easier... What does the capital L
icon indicate?

Fixed header still disappears when webpage is scrolled

Fixed header still disappears when webpage is scrolled

Hi everyone I am having trouble getting to stay in place while I scroll,
essentially making it 'fixed'. I have set the CSS to fixed, as you can see
below, but the header still disappears when I scroll.
HTML PAGE
<title>Final Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script>
window.open = function(){};
window.print = function(){};
// Support hover state for mobile.
if (false) {
window.ontouchstart = function(){};
}
</script>
<body>
<link href="../Documents/Unnamed Site 2/stylesheet2.css"
rel="stylesheet" type="text/css">
**<div class="fixed">
<h1>Packit<br>
<style>
.col-group {
overflow: hidden;
}
.col-group > div {
padding: 1em;
}
@media screen and (min-width: 44em) {
.col-group > div {
float: left;
width: 50%;
}
.col-group > div:nth-child(odd) {
clear: left;
}
}
@media screen and (min-width: 50em) {
.col-group > div {
float: left;
width: 33.3333333%;
}
.col-group > div:nth-child(3n+1) {
clear: left;
}
.col-group > div:nth-child(odd) {
clear: none;
}
}
@media screen and (min-width: 70em) {
.col-group > div {
width: 20%;
}
.col-group > div:nth-child(odd), .col-group > div:nth-child(3n+1) {
clear: none;
}
}body h1 {
font-size: 12em;
}
body h1 {
font-size: 3em;
}
body h1 {
font-size: 16em;
}
body h1 {
font-size: 16px;
}
body h1 {
font-size: 12px;
}
</style>
Hi there. We are here to help.</h1>
</div>**
CSS PAGE
/*
colors
red: #e51837; rgb(229,24,55)
gray: #808080;
*/
/************Reset**************/
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html, body, div, object, iframe, fieldset {
margin: 0;
padding: 0;
border: 0;
}
input, select
{
width: 120px;
}
ol, ul {
list-style: none;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
header, footer, nav, section, article, hgroup, figure {
display: block;
}
legend {
display: none;
}
/************End Reset**************/
/************Global**************/
.fixed
{ position:fixed;
top:0;
left:0;
width:100%;
margin:0 auto;
}
.form
{ position:fixed;
margin: auto;
width: auto;
line-height: 1;
}
body {
background: #fff;
color: #000;
font: 100%/1.4 "HelveticaNeue", "Helvetica", "Arial", sans-serif;
padding: 0;
-webkit-text-size-adjust: none;
}
a {
color: #808080;
text-decoration: none;
}
a:hover, a:focus {
color: #e51837;
}
p {
margin: 0 0 1em;
}
img, object, video {
max-width: 100%;
border: 0;
}
a img {
border: 0;
outline: 0;
}
h1 {
font-size: 3em;
line-height: 1;
letter-spacing: -0.02em;
margin-bottom: 0.2em;
}
h2 {
font-size: 2em;
line-height: 1.1;
margin-bottom: 0.2em;
}
h3 {
font-weight: normal;
line-height: 1.1;
padding-bottom: 0.4em;
border-bottom: 1px solid #ccc;
}
h1 a, h2 a, h3 a {
display: block;
color: #000;
}
h1 a:hover, h2 a:hover, h3 a:hover {
color: #e51837;
}
blockquote {
border-left: 0.5em solid #ddd;
padding-left: 1em;
margin-left: 1em;
}
small {
color: #e51837;
}
input[type=search] {
-webkit-appearance: none;
border-radius: 0;
}
::-webkit-input-placeholder {
color: #808080;
}
:-moz-placeholder {
color: #808080;
}
/************End Global**************/
/************Classes**************/
.inactive {
color: #ddd;
}
/************End Classes**************/
/************Structure**************/
.container {
max-width: 70em;
margin: 0 auto;
padding: 0 1em;
overflow: hidden;
}
div[role=main] {
padding-bottom: 1em;
}
/*Footer*/
footer[role=contentinfo] {
color: #fff;
background: #000;
margin: 0 -1em;
position: fixed;
z-index: 2;
}
footer[role=contentinfo] > div {
max-width: 70em;
padding: 0 1em;
margin: 0 auto;
overflow: hidden;
}
footer[role=contentinfo] p {
margin: 0;
}
footer[role=contentinfo] .nav li a {
display: block;
border-bottom: 1px solid #808080;
padding: 1em;
margin: 0 -1em;
}
footer[role=contentinfo] a {
display: inline-block;
padding: 0.5em 0;
}
footer[role=contentinfo] a.nav-home {
color: #fff;
}
footer[role=contentinfo] .f-rga {
padding: 0.6em 0;
}
footer[role=contentinfo] img {
max-width: 4.4em;
display: inline-block;
margin-bottom: -0.22em;
}
/*End Footer*/
/*Grid*/
.grid {
margin: 0 -1em;
overflow: hidden;
}
.grid:target {
-webkit-animation: fadeout 5s 1 ease-out;
-moz-animation: fadeout 5s 1 ease-out;
-o-animation: fadeout 5s 1 ease-out;
animation: fadeout 5s 1 ease-out;
}
.grid > h2 {
margin-left: 0.45em;
}
.grid > section {
padding: 1em 1em 0.5em;
}
.grid > section:target {
-webkit-animation: fadeout 5s 1 ease-out;
-moz-animation: fadeout 5s 1 ease-out;
-o-animation: fadeout 5s 1 ease-out;
animation: fadeout 5s 1 ease-out;
}
.grid ul {
overflow: hidden;
}
.grid ul li {
margin-bottom: 0.3em;
}
.featured:after {
content: "*";
color: #e51837;
}
/*Fluid*/
.fluid {
display: block;
margin: 0 auto;
max-width: 40em;
}
/*Homepage*/
.home h1 {
margin-bottom: 0.2em;
}
.intro {
font-size: 1.8em;
line-height: 1.2;
margin: 0 auto;
}
.intro a:hover ,.intro a:focus {
color: #000;
border-bottom-color: #000;
}
.ani {
position: relative;
height: 15em;
margin: 1em 0 0;
width: 100%;
z-index: 0;
}
.ani div {
width: 100%;
}
.ani div b {
display: block;
position: absolute;
top: 5%;
right: 5%;
bottom: 5%;
left: 5%;
background: rgba(229,24,55,0.22);
}
/*Patterns*/
.mod {
padding: 1em;
}
.pattern {
background: #f7f7f7;
border-bottom: 1px solid #808080;
margin-bottom: 1em;
overflow: hidden;
}
.pattern-description h1 {
font-size: 3.4em;
margin-bottom: 0.5em;
}
.pattern-description {
max-width: 40em;
margin: 0 auto;
}
.pattern-description ul, .pattern-description ol {
margin-bottom: 2em;
}
.pattern-description li {
margin-bottom: 1em;
}
/*Blog*/
/*Blog Header*/
.blog .container {
max-width: 62em;
}
.blog header[role=banner] {
overflow: hidden;
margin-bottom: 2em;
padding: 2em 0 1em;
border-bottom: 1px solid #000;
}
.blog-logo {
font-weight: normal;
font-size: 1.2em;
margin: 0 0 1em;
}
.blog-logo img {
width: 3.3em;
}
.blog-logo a {
color: #000;
}
.search-form {
width: 100%;
margin-bottom: 1em;
}
.search-field {
width: 100%;
padding: 0.5em 0;
border: 0;
border-bottom: 1px solid #808080;
outline: none;
}
.search-field:focus {
background: #e51837;
color: #fff;
}
.search-field:focus::-webkit-input-placeholder {
color: #fff;
}
.search-field:focus :-moz-placeholder {
color: #fff;
}
.blog .nav {
clear: both;
}
.blog .nav a {
display: block;
font-weight: bold;
color: #000;
}
.blog .nav a:hover {
color: #e51837;
}
/*Posts*/
.posts ol > li {
padding-bottom: 1em;
border-bottom: 1px solid #ccc;
margin-bottom: 1em;
overflow: hidden;
}
.posts h2 {
font-size: 1.4em;
margin: 0.28em 0 0.1em;
font-weight: normal;
}
.posts h2 a {
color: #000;
}
.posts h2 a:hover, .posts h2 a:focus {
color: #e51837;
}
.permalink {
display: block;
font-size: 0.8em;
margin-bottom: 1.2em;
}
.post-body a {
border-bottom: 1px solid #ccc;
}
.posts blockquote {
margin: 0 0 1em;
color: #666;
border-left: 0.25em solid #ccc;
padding-left: 1em;
}
.tags {
float: left;
}
.tags li {
display: inline-block;
font-size: 0.8em;
margin-right: 0.5em;
}
.posts ol > li .tags a, .permalink {
color: #ccc;
-webkit-transition: color 0.3s ease-out;
-moz-transition: color 0.3s ease-out;
-ms-transition: color 0.3s ease-out;
-o-transition: color 0.3s ease-out;
transition: color 0.3s ease-out;
}
.posts ol > li:hover .tags a, .posts ol > li:hover .permalink {
color: #808080;
}
.blog-nav {
text-align: center;
overflow: hidden;
padding: 1em 0;
}
.posts .blog-nav a {
border: 0;
}
.nav-next {
float: right;
}
.nav-prev {
float: left;
}
/* Sidebar */
.sidebar {
font-size: 0.8em;
padding-bottom: 1.4em;
}
.sidebar div {
margin-bottom: 2em;
}
.sidebar h3 {
font-weight: bold;
font-size: 0.9em;
line-height: 1;
border-bottom: 1px solid #000;
}
.sidebar a {
color: #808080;
}
.sidebar a:hover, .sidebar a:focus {
color: #e51837;
}
.social-links {
overflow: hidden;
}
.social-links li {
float: left;
margin-right: 1.2em;
}
.social-links li a {
display: block;
height: 17px;
width: 16px;
text-indent: -99999em;
background: url(images/sprite_social.png) no-repeat;
}
.social-links li a.s-fb {
background-position: -0px -76px;
}
.social-links li a.s-fb:hover {
background-position: -16px -76px;
}
.social-links li a.s-twitter {
background-position: -0px -37px;
}
.social-links li a.s-twitter:hover {
background-position: -16px -37px;
}
.social-links li a.s-linkedin {
background-position: -0px -113px;
}
.social-links li a.s-linkedin:hover {
background-position: -16px -113px;
}
.social-links li a.s-rss {
background-position: -0px -0px;
}
.social-links li a.s-rss:hover {
background-position: -16px -0px;
}
.top {
clear: both;
display: block;
padding: 1em 0;
}
.top:before {
content: '£';
}
/******Media Queries*******/
/* Medium Screens*/
@media all and (min-width: 35em) {
.blog-logo {
float: left;
font-size: 2em;
margin: 0 0 1em;
}
.blog-logo img {
width: auto;
}
}
@media all and (min-width:40em) {
h1 {
font-size: 5.6em;
}
.container {
padding-bottom: 4em;
}
footer[role=contentinfo] {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
margin: 0;
}
footer[role=contentinfo] .nav {
float: left;
}
footer[role=contentinfo] .nav li {
display: inline-block;
margin-right: 0.8em;
}
footer[role=contentinfo] .nav li a {
border: 0;
}
footer[role=contentinfo] .f-rga {
float: right;
}
.grid ul li {
width: 50%;
float: left;
}
.grid ul li:nth-child(odd) {
padding-right: 1em;
clear: left;
}
.ani {
position: absolute;
top: 0;
right: 0;
bottom: 4em;
left: 0;
width: 100%;
height: 90%;
margin: 0;
z-index: 0;
}
.home {
position: absolute;
top: 0;
right: 0;
bottom: 5em;
left: 0;
z-index: 1;
width: 100%;
height: 90%;
display: table;
text-align: center;
color: #fff;
color: rgba(255,255,255,0.7);
}
.home > div {
display: table-cell;
vertical-align: middle;
}
.home .intro a {
color: #fff;
color: rgba(255,255,255,0.8);
border-bottom: 1px solid rgba(255,255,255,0.8);
}
.home .intro a:hover, .home .intro a:focus {
color: #000;
border-bottom-color: #000;
}
/*Blog*/
.search-form {
float: right;
width: 30%;
max-width: 16em;
padding-left: 0.8em;
margin-top: 0.4em;
}
.posts {
float: left;
width: 64%;
}
.sidebar {
float: right;
width: 30%;
max-width: 21em;
margin: 0 0 1em;
padding-left: 0.8em;
}
}
/* Large Screens */
@media all and (min-width: 54em) {
h1 {
font-size: 6.4em;
}
.grid > section {
float: left;
width: 33.3333333%;
}
.grid > section:nth-of-type(3n+1) {
clear: left;
}
.grid ul li {
width: auto;
float: none;
}
.grid ul li:nth-child(odd) {
padding-right: 0;
}
}
/* CSS Animations */
@-webkit-keyframes fadeout {
0% { background: #fff; }
10% { background: #eee; }
100% { background: #fff; }
}
@-moz-keyframes fadeout {
0% { background: #fff; }
10% { background: #eee; }
100% { background: #fff; }
}
@-o-keyframes fadeout {
0% { background: #fff; }
10% { background: #eee; }
100% { background: #fff; }
}
@keyframes fadeout {
0% { background: #fff; }
10% { background: #eee; }
100% { background: #fff; }
}

Select within select for MYSQL

Select within select for MYSQL

I am trying to SELECT specific lines of data from a MYSQL database
The database is as follows
Count id Startstation stp
1 A1234 Nottingham o
2 A1234 Nottingham p
3 B2345 Nottingham p
4 C6789 Leeds o
I would like to select all the Nottingham stations but not repeat the same
id. Also an stp code of o takes priority over an stp of p.
So I am looking for an output as follows:
A1234 Nottingham o
B2345 Nottingham p
Here is the code I have been trying to use but I cannot get it to work
require('connect_db.php');
mysqli_select_db($mysql_link,"timetable");
$q="select * from (SELECT id,startstation, stp, ROW_NUMBER() OVER
(PARTITION BY id ORDER BY stp DESC) rnk FROM railtest WHERE
startstation="Nottingham") where rnk = 1";
$r=mysqli_query($mysql_link,$q);
if ($r)
{
while ($row=mysqli_fetch_array($r,MYSQLI_ASSOC))
{
echo $row['startstation'] . " " . $row['id']." ".$row['stp'];
echo "<br>";
}
}
else {echo '<p>'.mysqli_error($mysql_link).'</p>' ;}
mysqli_close($mysql_link);
I am getting a Parse error with my select statement
Hope some one can help
Thanks

templated friend function of templated class with private constructor

templated friend function of templated class with private constructor

I have a templated class Obj and a make_obj function. Obj has a single
constructor defined, which takes a reference to it's templated type to
bind to.
template <typename T>
class Obj {
private:
T & t;
Obj (T & t) : t(t) { }
Obj() = delete;
};
template <typename T>
Obj<T> make_obj(T t) {
return Obj<T>(t);
}
As you can see, this constructor is private. What I want is to declare the
make_obj function a friend so that it can create Obj's, but no one else
can (except via the copy ctor).
I have tried several friend declaration including
friend Obj make_obj(T &);
and
template <typename T1, typename T2>
friend Obj<T1> make_obj(T2 &);
The latter being a less than desirable attempt at making all template
instantiations of make_obj friends of the Obj class. However in both of
these cases I get the same error:
error: calling a private constructor of class
'Obj<const char *>'
return Obj<T>(t);
^
note: in instantiation of function template specialization
'make_obj<const char *>' requested here
auto s = make_obj("hello");
^
trying to do make_obj("hello"); for example purposes.
How can I allow only make_obj access to Obj's value contructor?

How do I dynamically create a list of controls or labels that have the same properties of a pre-existing one VB.net

How do I dynamically create a list of controls or labels that have the
same properties of a pre-existing one VB.net

When I try to create a list of labels with the same properties as a
pre-existing one using the code below, while I end up with a list 10 items
long, they all end up having the same name and there ends up only being
one label displayed.
I suspect that I am ending up with a list of 10 "pointers" to the same
label. (But I'm using the word "New" every chance i get :) )
Dim lblList As New List(Of Label)
For I = 0 To 9
lblList.Add(New Label)
lblList(I) = lblExistingLabelWithDesiredProperties
lblList(I).Name = "lblName" & I.ToString
lblList(I).Left = 30 + I * 10
Next
As I say I seem to end up with only one label.
Thanks in advance.

Thursday, 12 September 2013

ajax send strange data? $_POST not working the usual way

ajax send strange data? $_POST not working the usual way

if(name.val().length > 3){
var username=name.val();
$.post('validate.php',{names: username},function(data){
//do some stuff
});
}
my php work only by using
$name = &$_POST['names'];
$email = &$_POST['emails'];
but not the usual way:
$name = $_POST['names'];
$email = $_POST['emails'];

How to have text delete itself in prompt window in Batch

How to have text delete itself in prompt window in Batch

So I want to put a command in between two echo strings so that when the
other appears, it is on the top row and the first one dissapears.
Something like this:
echo Stuff that gets deleted when the second print comes choice /C X /T 3
/D X > nul deletepreviousecho echo New Words.

Can I use ravendb in a javascript SPA

Can I use ravendb in a javascript SPA

I am developing a application that is using backbone.js for most of the
front end logic and was thinking of using sqlite for storage, but i have
run into a few complications with it and need to switch to another NoSQL
database.
I see on ravendb's site that it was created in C# and you need a .net
compiler. Most of the docs are for ASP MVC type application. I can not go
this root because we are developing this as a tablet application with no
microsoft based technologies on the client side ( because we want it to
work with android and apple )
The server however will be .NET and so i figured this might be do able.
Just wondering if this is worth pursuing and if anyone has had any
experience using ravendb? Or should i go for mongodb?

remove search query after pressing on search button

remove search query after pressing on search button

I used android search widget in action bar, when I write my query and
press on search button or done, everything works in my search part, but I
want to remove that query in search field,
For example : (if I write "test" after pressing search button I don't want
to have this "test" in my search filed) would you please let me know how
can I remove my search query!
Thanks in advance!

Method Of Retrieving Random Value Depending on Type

Method Of Retrieving Random Value Depending on Type

I was wondering what would be the most appealing way of achieving this goal.
I have a blackbox. I give it a supported type and it returns a random
value base off of the type.
For my supported types, I have an enum defined as follows:
public enum Types
{
INTEGER,
DOUBLE,
BIGINTEGER,
BIGDECIMAL,
STRING,
BOOLEAN,
CHAR
}
I thought the easiest way would be to create a static function which
returns an Object based off of the Type
public static Object getRandomValue(Types type)
{
switch(type)
{
case INTEGER:
return randomInt();
case DOUBLE:
return randomDouble();
case BIGINTEGER:
return randomBigInt();
case BIGDECIMAL:
return randomBigDecimal();
case STRING:
return randomString();
case BOOLEAN:
return randomBool();
case CHAR:
return randomChar();
}
}
The problem is that an additional cast would have to be made each time
that I want to retrieve a random value based off of this method.
I've looked into the design patterns abstract factory and factory, and I
can't decide if there's an advantage into implementing either of those. Or
if there's a different design pattern that seems to be more appropriate.
Assume that all my random methods are defined.

Get value from hashmap based on key to JSTL

Get value from hashmap based on key to JSTL

I want to get the value of HashMap based on key.

HashMap<String, ArrayList<String>> map
= new HashMap<String, ArrayList<String>>();
ArrayList<String> arrayList = new ArrayList<String>();
map.put("key", arrayList);
request.setAttribute("key", map);
What i did is

<c:forEach var="map" items="${requestScope.key}">
<c:forEach var="hash" items="${map.value}">
<option><c:out value="${hash}"/></option>
</c:forEach>
</c:forEach>
But it seems it's printing everything, what i want to do is to get the
value depends on key like: hash.key or something
UPDATE:
I did something like this but it still doesn't work
<c:forEach var="map" items="${requestScope.key}">
<c:forEach var="hash" items="${map['key']}">
<option><c:out value="${hash}"/></option>
</c:forEach>
</c:forEach>
and the StackTrace: Property 'External' not found on type
java.util.HashMap$Entry
I'm pretty sure that there is really that kind of key.

Wednesday, 11 September 2013

CocoaPods podspec lint failure - file not found

CocoaPods podspec lint failure - file not found

I'm trying to distribute my pod, but I'm having issues with it's validation.
When I'm trying to lint against my .podspec I'm getting:
- ERROR | [iOS] [xcodebuild] path/to/my/source/file.m:14:9: fatal error:
'KeyValueObjectMapping/DCKeyValueObjectMapping.h' file not found
I tried to preserve the path to their framework with different variations
like
s.preserve_paths = 'KeyValueObjectMapping.framework/*'
or
s.preserve_paths =
'${PODS_ROOT}/Vendor/KeyValueObjectMapping/KeyValueObjectMapping.framework'
& other variations but that way I'm getting one more error:
- ERROR | [iOS] The `preserve_paths` pattern did not match any file.
I also tried different other things which I saw on other issues like:
s.xcconfig = { 'HEADER_SEARCH_PATHS' =>
'"${PODS_ROOT}/Vendor/KeyValueObjectMapping/KeyValueObjectMapping.framework"','FRAMEWORK_SEARCH_PATHS'
=> '"$(PODS_ROOT)/Vendor/KeyValueObjectMapping/*"' }
s.framework = 'KeyValueObjectMapping'
The project builds fine with Xcode5 & with xcodebuild with it's default
setup, I'm getting this issue only when validating it for Cocoapods.