Thursday, April 19, 2012

Check database for similar value , MySQL

I have a table server like this;



Model | Brand
-------------------
M4000 | Dell
S4000 | Hp
S3500 | Hp
S6500 | Sun


I want to display different data from the 'Brand' field which means I don't want the second 'Hp' data to display again. How do I do that?





Access textboxes dynamically created at runtime

I add textboxes dynamically at runtime. How do I access them later in the program?





Css rounded images with border and some padding

enter image description here



Hope this image speaks everything...!!! Need to do this in html + css .. Note: I want the border inside the image.





Convert general regex to bash proof regex

I have the following regex that checks for a password policy. it is validated to work:



(^([zZ]\d{3})*$)|((?=.{9,})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*)



I want to use the regex in a bash script to validate a psssword the following way :



echo $password | grep "(^([zZ]\d{3})*$)|((?=.{9,})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*)"
if [[ $? -eq 0 ]] ; then


This does not work in bash.
My question is :



How do i convert this "pure" regex to a one that work in bash ? which characters do i need to escape, what is the correct way to pass the regex to grep ? are there any other things i need to look out for ?



Thanks





Wpf MVVM UI do not update implementing modularity,eventaggregator

i'm currently experimenting wpf communication between two views of different modules using prism IEventAggregator. publishing module and subscribing module is working fine, for some reason i can't understand why the subscriber UI is not updating.i place a button to display a msgbox at the subscriber module just to be sure that it receives it and it does. and i think i properly implement the INotifyPropertyChanged.



if i place subscribe in subscriber view's code-behind it works as i want it to be....do i do it the wrong way? please correct me. thanks.



Public Class SendServices
Public Shared Property SendMessage As EventAggregator

Shared Sub New()
SendMessage = New EventAggregator
End Sub
End Class


Publisher :



Public Class Module1ViewModel

Private _msgsend As String
Public WriteOnly Property MessageSend As String
Set(value As String)
_msgsend = value
End Set
End Property

Public Sub Send()
SendServices.SendMessage.GetEvent(Of SendStringEvent).Publish(New SendString With {.Name = _msgsend})
End Sub
End Class


Subscriber :



Public Class Module2ViewModel
Implements INotifyPropertyChanged

Private _receivedMSG As String
Public Property ReceivedMSG As String
Get
Return _receivedMSG
End Get
Set(value As String)
_receivedMSG = value

OnPropertyChanged("ReceivedMSG")
End Set
End Property
'Binded to subscriber View button using interactions
Public Sub Received()
MsgBox(ReceivedMSG)
End Sub

Private Sub ReceivedMessage(msg As SendString)
_receivedMSG = msg.Name
End Sub

Public Sub New()
SendServices.SendMessage.GetEvent(Of SendStringEvent)().Subscribe(AddressOf ReceivedMessage, ThreadOption.UIThread, False)
End Sub

Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Sub OnPropertyChanged(ByVal name As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
End Sub
End Class


Subscriber View code-behind



Public Class Module2View
Sub New()
InitializeComponent()
Me.DataContext = New Module2ViewModel
End Sub
End Class


and the binding part to display the message



<TextBox Height="23" HorizontalAlignment="Left" Margin="111,39,0,0" Name="TextBox1" VerticalAlignment="Top" Width="158" Text="{Binding Path=ReceviedMSG}"/>




Get date of last successful job run?

I have a single step job that executes a stored procedure. I would like get the date of the last successful job execution time so that I can just update a delta instead of the whole set of data.



Right now I have the job setup to run once every day, so I have a default parameter that if it's null I set it to GETDATE() - 1 so I'm still updating a delta but what I'd like to do is set the date to the last successful execution of the job.



exec dbo.usp_UpdateFrom @LastSuccessfulExecutionTime


Current procedure is something like



CREATE PROCEDURE dbo.usp_UpdateFrom
@FromDate datetime = NULL --would like to pass last successful execution time of the job
AS
IF @FromDate IS NULL
SET @FromDate = GETDATE() - 1

-- do stuff
END




UPDATE : Most Samsung Androids have "Settings" button too in soft keyboard. How to intercept or disable that?

I have a full screen activity with a ExitText. When edit text is clicked(gets focus) a softkeyboard shows up.



Now, on some samsung android phones(atleast two that I have used), the keypad also has a small "Settings" button which will close your activity and take you to phone's system settings button.



I want to intercept when a user click's this "Settings" soft button and then take some decision before my activity gets pushed back to the stack.



Is it possible? If yes, how?



EDIT



I know that in normal circumstance its a bad user experience and should be avoided. However, I am more interested in the solution (technology side). I am not going to launch an app in the market with such a thing for regular user, so please dont comment saying I should not do this.



I know that developers put such comments in the benefit of the users who are still learning but in some cases, "Its more about HOW to do it?". This scenario is just one of them. Hope nobody takes what I said in a wrong sense. Thnx!





Please someone fix the bug [closed]

I have a Android file whose code is follwed..I had problems with Spinners...



public class first extends Activity  {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


Spinner spincity;
String[] citynames={"select","Ahmedabad","Vadodara","Surat","Gandhinagar","Himatnagar",
"Surendranagar","Navsari","Valsad","Viramgham"};
spincity=(Spinner) findViewById(R.id.spincity);
ArrayAdapter<String> a=new ArrayAdapter<String>(this.getApplicationContext(), android.R.layout.simple_spinner_item,citynames);
a.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spincity.setAdapter(a);

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});
}
}


The layout file .xml is as below:



<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/city"
android:text="City :"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="left"
/>
<Spinner
android:id="@+id/spincity"
android:layout_width="220dp"
android:layout_height="wrap_content">
</Spinner>
</LinearLayout>
</RelativeLayout>
</ScrollView>


This code gives a NullPointerException. I have tried my best but couldn't resolve it.
The Logcat is as follow::



02-23 16:04:19.554: ERROR/AndroidRuntime(1154): FATAL EXCEPTION: main
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.spinners.changeimage/com.spinners.changeimage.first}: java.lang.NullPointerException
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.os.Handler.dispatchMessage(Handler.java:99)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.os.Looper.loop(Looper.java:123)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at java.lang.reflect.Method.invokeNative(Native Method)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at java.lang.reflect.Method.invoke(Method.java:507)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at dalvik.system.NativeStart.main(Native Method)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): Caused by: java.lang.NullPointerException
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at com.spinners.changeimage.first.<init>(first.java:17)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at java.lang.Class.newInstanceImpl(Native Method)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at java.lang.Class.newInstance(Class.java:1409)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
02-23 16:04:19.554: ERROR/AndroidRuntime(1154): ... 11 more




Ensure if it is Mutual Exclusion or not

int turn =1


Process 1



If (turn != 0)                                      
{
Critical_Region()
noncritical_region()
turn = 0
}


Process2



if (turn !=1) {
Critical_Region()
noncritical_region()
turn =1
}


Kindly tell me that if these two processes ensures that they are mutually exclusive or not?





My whole delete method() is executing successfully and there is no error,but the records are not being deleted

When debugger is applied the query-line shows no data in textBox1.Text.my code is following:



namespace SeparateConnection
{


class clsGridView
{

Connection co2 = new Connection();
//display our global varaible for connection
SqlConnection myconn3 = new SqlConnection("data source=M-SULEMAN-PC;initial catalog=dbmsLogin;integrated security=sspi");
public void Delete()
{
co2.setconn();
try
{
DialogResult result = MessageBox.Show("Are you sure you want to delete ?", "Message",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//myconn3.Open();
DataTable table2 = new DataTable();
frmGridView gd = new frmGridView();
SqlDataAdapter myadd2 = new SqlDataAdapter("Delete from tblLogin where UserName ='" + gd.textBox1.Text + "'", myconn3);
myadd2.Fill(table2);

//Sqlcommandbulider to allow changes to database
SqlCommandBuilder mybuild = new SqlCommandBuilder(myadd2);

//Update the database
myadd2.Update(table2);

//Close the connection
myconn3.Close();

}
else
return;

}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}


----------when I use the same class for calling and defining the method..there is no problem





Kohana 3.2 ORM with columns based on DB::expr()

In my current app, I have a list of plays and it is almost universally sorted by the play's name in queries. Currently, it is built simply using DB::select() statements, but while we're doing a lot of refactoring, we want to begin using Kohana's ORM library. The problem comes from the fact that we don't typically sort by the actual play name, but rather a processed version, stripping out articles and the like and sorting by that (so that The Book of Mormon appears with the Bs, rather than the Ts). I don't know how to carry that over into the ORM model definition.



The select code looks like this (abridged):



DB::select(column, column,
DB::expr("CASE WHEN SUBSTRING_INDEX(show_name, ' ', 1) IN ('a', 'an', 'the')
THEN SUBSTRING(show_name, INSTR(show_name, ' ') + 1)
ELSE show_name
END AS show_name_sort")


Is there a way to create a fake show_name_sort column that Kohana will ignore on save, but that I can still use in an order_by call? Or do I just need to create an actual column with the sorted version of the name in it?





Dynamically reducing FontSize to avoid overflow

I have written a toy WPF application with a Button and an ItemsControl. Each time you click the Button, the string "AnotherWord" gets added to the ItemsControl. Now, the ItemsControl is displayed as horizontally oriented StackPanel with a fixed width (500 pixels). This means that when you click the button a certain number of times (actually six times), the newly added string gets clipped, like this:



"AnotherWord AnotherWord AnotherWord AnotherWord AnotherWord AnotherWo"



This happens when the FontSize is 13; if you lower it to 12.7 then there's room for the sixth occurence of "AnotherWord". My question is: Is there a way to make this adjustment at runtime so that you avoid the overflow?



EDIT:



In the context of the question, the fixed width of the StackPanel is obligatory - we cannot use more than the 500 pixels we have.



Here is all the code I wrote:



<!-- MainWindow.xaml -->
<Window x:Class="FontSize.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<DataTemplate x:Key="labelTemplate">
<Label FontSize="13" Content="AnotherWord"></Label>
</DataTemplate>
<ItemsPanelTemplate x:Key="panelTemplate">
<StackPanel Orientation="Horizontal" Width="500" Height="50" />
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ItemsControl Grid.Row="0" ItemsSource="{Binding Path=MyStrings}" ItemTemplate="{StaticResource labelTemplate}"
ItemsPanel="{StaticResource panelTemplate}" />
<Button Grid.Row="1" Click="Button_Click"></Button>
</Grid>
</Window>

// MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;

namespace FontSize
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
MyStrings = new ObservableCollection<string>();
}

public ObservableCollection<string> MyStrings
{
get { return (ObservableCollection<string>) GetValue(MyStringsProperty); }
set { SetValue(MyStringsProperty, value); }
}

private static readonly DependencyProperty MyStringsProperty =
DependencyProperty.Register("MyStrings", typeof (ObservableCollection<string>), typeof (Window));

private void Button_Click(object sender, RoutedEventArgs e)
{
MyStrings.Add("AnotherWord");
}
}
}




Need help to implement multithreading in C#

I am making an app in which for some reason when I click on a button I have to initiate a new form and at the same time create a new document in the google docs.
I've successfully implemented the above but while the app is busy making creating a new doc at google docs for that time being the newly loaded form's UI freezes.
I read somewhere that this can be avoided if I use multi threading.
So now I wanna ask should I create two threads and in one of them I should place the code for creating new form and in the other one I should place the code to create a document in google doc.
Or I should just create on thread in which I should place the code to create new google doc and let the new form creating code be in the main process??
Also What would be the easiest way to implement threading in an already written code?? Pleaseprovide with some reference reading material if possible.





What is REST? Slightly confused

I was under the assumption that REST was a web service but it seems that I am incorrect in thinking this - so, what is REST?



I've read through Wikipedia but still cant quite wrap my head around it. Why to do many places refer to API's as REST API's?





How to remove extra path from img src by jquery

now i am getting that path in every img src



<img alt="test" src="http://www.wsoradio.com/wp-content/uploads/http://www.wsoradio.com/wp-content/files/acbreviews/a4/B001THPA4Y/smallimage.jpg">


but i need output



<img alt="test" src="http://www.wsoradio.com/wp-content/files/acbreviews/a4/B001THPA4Y/smallimage.jpg">


i want to remove this extra path from every img src by jquery



http://www.wsoradio.com/wp-content/uploads/


plz guide me how to do it, thanks





I am getting an undefined variable

I am trying to retrieve a file name from the server of the file that has just been uploaded. The problem is that I am getting an undefine index on my php variable below:



 Undefined index: fileimagename in /web/stud/xxx/Mobile_app/QandATable.php on line 19


What I am trying to do is that user uploads the form which is done by the php script (imageupload.php), Now when uploading stops it uses the javascript function which is on a seperate page (QandATable.php, same page as the ) to display the message if upload is successful and this would append the name of the file uploaded.
So my question is how can I fix the undefined variable and how can I get the javascript function in the QandATable.php to retireve the file name from imageupload.php?



Below is code which consists the undefined variable and javascript function (QandATable.php):



            <?php
session_start();

$fileimagename = $_SESSION['fileimagename'];

?>

<script type="text/javascript">

function stopImageUpload(success){

var fileimagename = <?php echo $fileimagename; ?>;
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append(fileimagename + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}

return true
};
</script>


Below is php script which uploads the file into the server: (imageupload.php)



 <?php

session_start();

if (isset($_POST['fileimagename'])) {

$_SESSION['fileimagename'] = $_SESSION[' $_FILES['fileImage']['name']'];

}

if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;

while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;

move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;

}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;

}

?>

<script language="javascript" type="text/javascript">

window.top.window.stopImageUpload(<?php echo $result;?>,'<?php echo $fileimagename;?>');

</script>




C++11 Convenience wrapper for std::reverse()

Is the right way to use C++11 rvalue-references and move semantics to implement a convenience wrapper for std::reverse()?



template <class BIDirContainer> inline BIDirContainer&& reverse(BIDirContainer a) {
std::reverse(begin(a), end(a));
return std::move(a);
}


The code works in my test case but I am unsure its about performance: should I use && here or is it unneccesary?





'r' in Python commands

This has probably answered somewhere at sometime but the titles I have seen don't connect so here it goes. I have seen python commands that read os.listdir(r".\bootstrapper"). What is the 'r' doing?



Cheers...





hibernate: update a column based on another

i have a table with 2 main columns: name and name without accent.
i would like hibernate to update the 2nd one when 1st one is changed:



@Column(name = "name")
public String getName() {
return this.name;
}

public void setName(String s) {
this.name = s;
this.noAccentName = RemoveDiacritics(name); //remove diacritics from name
}

@Column(name = "noaccent_name")
public String getNoAccentName() {
return this.noAccentName;
}

public void setNoAccentName(String s) {
this.noAccentName = s;
}


This is working but it has an overhead: setter of the name sets object to dirty, and hibernate wants to update it all the time... :(



How can i ask hibernate to update 'noAccentName' when 'name' was changed in a clean way?



Thanks a lot,





EXTJS How to upload image to hsql database from extjs client side in json object

I have image upload field like



{
xtype: 'textfield',
fieldLabel: 'Image',
labelSeparator: '',
name: 'newPic',
id:'newPic',
anchor:'100%',
inputType: 'file',
allowBlank: false
}


When i submitting form, Im encoding all form data in a json object.All textfields data are coming in json object but not image is passing to server side . How to pass image so as to save it in server side



var form=Ext.getCmp('empPersonal');
var formdata=Ext.JSON.encode(form.getValues());
alert(""+formdata);
if(Ext.getCmp('empPersonal').getForm().isValid()) {
Ext.Ajax.request({
url:'ws/employees/create/'+formdata,




Bit-wise AND and a Normal AND [closed]


Possible Duplicate:

Why && and not &






I would just want to know, when would i use a Bit-wise AND a normal AND.
I read the a Bit-wise AND is good for applications that has a memory limit.



Which 1 will be the best to use then, overall?



if (true & false)
{

}


or



if (true && false)
{

}


Wouldn't it be better to always use a Bit-wise AND then?





How to write a javascript funcion to check that my text box is containg special character or not?

I want to check that my text box is containing special character or not, using java script.
for this i am using following code



function CheckUserId() {
var txt = document.getElementById('<%=TextBox1.ClientID%>').value;
var regexp = "/^[a-zA-Z0-9]+$/";
if (regexp.match(txt)) {
alert("No special character ");
return true;
}
else {
alert("Special character");
return false;
}
}


I am calling this java script function on textbox onblur. TextBox code is following



  <asp:TextBox ID="TextBox1" runat="server" onblur="CheckUserId()" ></asp:TextBox>


but it is showing always alert message "special character" .Whats wrong with my code?
Please help me





JUNG: placing tree nodes in order

When adding nodes to my DelegateTree, they don't appear visually in the order I added them.
I've been looking for a solution, but haven't found anything yet.
Is there anyone who might know how to change this?



Thanks in advance!



EDIT: My code



/**
* Generate a visualization of the decision tree.
*
* @param tree
* The decision tree
* @return A component to be placed inside a JPanel
*/
public static GraphZoomScrollPane generateTree(Tree tree,
GraphicalUserInterface gui) {

/* Create a new tree */
DelegateTree<Node, Edge> graphTree = new DelegateTree<Node, Edge>();

/* Add all nodes and vertices to the tree */
graphTree.addVertex(tree.getRoot());
addChildren(tree.getRoot(), graphTree);

/* Create the visualization */
DynamicTreeLayout<Node, Edge> treeLayout = new DynamicTreeLayout<Node, Edge>(graphTree, 100, 100);
VisualizationViewer<Node, Edge> vv = new VisualizationViewer<Node, Edge>(
treeLayout);
vv.setDoubleBuffered(true);
vv.setBackground(Color.WHITE);
vv.getRenderContext().setEdgeLabelTransformer(
new ToStringLabeller<Edge>());
vv.getRenderContext().setEdgeShapeTransformer(
new EdgeShape.Line<Node, Edge>());
vv.getRenderContext().setVertexLabelTransformer(
new ToStringLabeller<Node>());
vv.getRenderer().getVertexLabelRenderer()
.setPosition(Renderer.VertexLabel.Position.S);

vv.addGraphMouseListener(new ClickNode(gui, vv));

final DefaultModalGraphMouse<Node, Edge> graphMouse = new DefaultModalGraphMouse<Node, Edge>();

graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);

vv.setGraphMouse(graphMouse);

final GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);

return gzsp;
}

/**
* Recursively add all nodes and edges to the tree.
*
* @param node
* The parent node
* @param tree
* The tree visualization
*/
private static void addChildren(Node node, DelegateTree<Node, Edge> tree) {
for (int i = 0; i < node.getChildren().size(); i++) {
tree.addChild(new Edge(node.getChildren().get(i).getEdgeLabel()), node, node
.getChildren().get(i));
addChildren(node.getChildren().get(i), tree);
}
}




Jquery autocomplete combobox button click event

Weird behavior of my autocomplete Jquery plugin, the click event show clearly that if input.autocomplete("widget") is visible, that is if it has display:block, then close the widget. But if I change focus from input element to widget itself and lets say scroll a bit, then when i click again on buton , the widget is created again.



My solution wolud be in closing the widget even if focus is transfered to widget itself and not the input element?



Any ideas how to modify this code so it beahaives this way?



 this.button = $("<button type='button'>&nbsp;</button>")
.attr("tabIndex", -1)
.attr("title", "Show all items")
.insertAfter(input)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function () {

// when i put breakpoint here, and my focus is not on input,
// then this if steatment is false????

if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}

// work around a bug (likely same cause as #5265)
$(this).blur();

// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});




s:SpriteVisualElement and "component declarations are not allowed here"

Take a look at the following code.



<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:view="client.view.*" minWidth="955" minHeight="600">
<s:Panel x="10" y="10" height="100%" title="CTW" borderColor="#008040" fontFamily="Arial" fontWeight="bold" fontSize="13">
<s:HGroup>
...
<s:Scroller id="canvasGroup" width="650" height="500">
<s:Group>
<s:SpriteVisualElement>
<view:PNGCanvas id="canvas" /> <!-- error is thrown here -->
</s:SpriteVisualElement>
</s:Group>
</s:Scroller>
</s:HGroup>
</s:Panel>
</s:Application>


PNGCanvas extends flash.display.Sprite. I'm getting an error component declarations are not allowed here (on line marked with error is thrown here). What's wrong here?



Thank you in advance!!!





JPA @ElementCollection @Enumerated not inserting

I am trying to implement basic user/roles



A user can have zero to many roles.



public enum Role {
ROLE_USER,
ROLE_ADMIN;
}

@Entity
@Table(name = "USERS")
public class User implements Serializable {

private static final long serialVersionUID = 2936736450886451500L;
private Long id;
private Set<Role> roles = new HashSet<Role>();

@Id
@Column(name = "ID")
@GeneratedValue
public Long getId() {
return id;
}

@SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}

@ElementCollection(targetClass=Role.class)
@JoinTable(name = "USER_ROLES", joinColumns = @JoinColumn(name = "USER_ID"))
@Enumerated(EnumType.STRING)
@Column(name = "role", nullable = false)
public Set<Role> getRoles() {
return roles;
}

public void setRoles(Set<Role> roles) {
this.roles = roles;
}

public void addRole(Role role) {
roles.add(role);
}

}


My Unit Test



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/META-INF/spring/resources/resource-context.xml", "classpath:/META-INF/spring/services/persistence-context.xml"})
public class UserDaoJpaImplTest {

@Autowired
UserDao userDao;

@Transactional
@Test
public void testCreate() {
User user = new User();
user.addRole(Role.ROLE_USER);
user.addRole(Role.ROLE_ADMIN);
userDao.create(user);

Assert.assertNotSame(user.getId(), 0);
}


the problem is, that jpa (backed by hibernate), is not doing the insert on the USER_ROLES table (it is creating it correctly, with the correct composite PK (ROLE, USER_ID), and FK to user.



I can see in the console, that only a single insert is being done, on the user



Hibernate: insert into USERS values ( )


I assume I am just missing something simple.





Replace special characters in JavaScript

How to replace '$txt$' in javascript.I want to replace all occurrences in the string



It's what i tried



if (html.indexOf('$txt$') > -1) {
html = html.replace(/$txt$/ig, '<input type=text></input>');
}


but it won't replace the string.What's my mistake.Please help me





Insert value in MySql with enter key i.e. without submit button

I have a problem, problem is that I have a textbox in html form in PHP, I want when we write some text in this textbox then press enter key then value of textbox will be insert in the sql table ?





What exactly is dynamic memory?

I was reading the C++ tutorial and I don't understand why I need to declare dynamic memory, this is what the tutorial says:




Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program.




And then it says that we have to use new and delete operators to use dynamic memory.
However, I seem to be using dynamic memory when declare a pointer, e.g. char* p, for which I have not specified the length of the array of characters. In fact, I thought that when you use a pointer you are always using dynamic memory. Isn't it true?
I just don't see the difference between declaring a variable using new operator and not. I don't really understand what dynamic memory is. Can anyone explain me this?





Running bat files in Jenkins

I have a simple question. I want to run a bat file that should run post build. The bat file takes in to parameters previousVersion and currentVersion (These parameters are entered as Validating String Parameters before the build starts).



This is what I have tried
Execute Windows Batch Command



set v = %currentVersion%
set pv = %previousVersion%
cmd \k "C:\jenkins\workspace\mybatfile.bat %pv% %p%"


The error I get is that cmd is not recognized as an internal or external command operable program or batch file exit 9009