Monday, 30 September 2013

Ranking a vector containing ties – mathematica.stackexchange.com

Ranking a vector containing ties – mathematica.stackexchange.com

How can I rank a vector such that the ties are replaced by their middle
ranks. For example, {1, 2, 2, 3}. I want to rank this vector but the ties
must be replaced by their mid-rank; i.e., given {1, 2, …

Showing that the preimage of a continuous function on R is a รณ-algebra

Showing that the preimage of a continuous function on R is a ó-algebra

Let $f$ be a continuous function on $\mathbb{R}$. Define
$\mathcal{A}=\left \{ E\subseteq \mathbb{R} : f^{-1}(E)\in
\mathcal{B}(\mathbb{R})\right \}$.
I want to show that $\mathcal{A}$ is a $\sigma$-algebra.
I think I'm just being silly, but this exercise almost seems trivial to
me. I mean since $f$ is continuous, then for every open $E\subseteq
\mathbb{R}$ we know that $f^{-1}(E)$ is open in $\mathbb{R}$. Then
wouldn't $\emptyset, E^c \in \mathcal{A}$ if $E\in \mathcal{A}$, and that
$\mathcal{A}$ is closed under countable unions automatically follow? What
am I missing here?

Ambiguous error in inherite class c++

Ambiguous error in inherite class c++

so i will give a small example of what is my problem,can someone help me
resolve this:
class A
{
virtual void show()=0;
};
class B:public virtual A
{
void show(){/*content inside*/}
};
class C:public virtual A
{
void show(){/*content inside*/}
};
class D:public B,public C
{
void show(){/*content inside*/}
};
can someone help me in this ambiguous problem,because i want to use the
function show() in all classes,and i didn't quite understand how to solve
this

Destroying controller in angular

Destroying controller in angular

I have a function like this, in an AngularJS controller
$timeout($scope.loadPosts, 5000); // pull every 5 seconds
When I navigate away from the controller (to another view), how can I stop
the timeout and eventually destroy the controller so it is not running
anymore?

Sunday, 29 September 2013

How to design constructors?

How to design constructors?

Lets assume a class Foo with 2 instance variables, int x and int y. The
use case demands I can construct the class with either none, single or all
params.
input X input Y
0 0 no constuctor
0 1 public Foo(int x);
1 0 public Foo(int y);
1 1 public Foo(int x, int y);
Now whats the convention/best practices in this case. Do I need to add all
the permutations of constructors ? If yes, the it would result in
exponential growth. If No, then whats solution ?

App crashing when using fragments

App crashing when using fragments

Im working with fragments and..
Ive got a problem in my code that I just cant find.
The logcat points at this piece of code, in one of my fragments:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
My main class (the FragmentActivity):
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
public class Fragments extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
MainActivity fragment = new MainActivity();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_place, fragment);
transaction.commit();
}
public void onSelectFragment(View view) {
Fragment newFragment;
if (view == findViewById(R.id.add)) {
newFragment = new Add();
} else if (view == findViewById(R.id.map)) {
newFragment = new MainActivity();
} else {
newFragment = new MainActivity();
}
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_place, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
and the logcat:
09-30 00:02:52.363: E/AndroidRuntime(32284): FATAL EXCEPTION: main
09-30 00:02:52.363: E/AndroidRuntime(32284): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.free/com.example.free.Fragments}:
android.view.InflateException: Binary XML file line #8: Error inflating
class fragment
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2185)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2210)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.ActivityThread.access$600(ActivityThread.java:142)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.os.Looper.loop(Looper.java:137)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.ActivityThread.main(ActivityThread.java:4931)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
java.lang.reflect.Method.invokeNative(Native Method)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
java.lang.reflect.Method.invoke(Method.java:511)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
dalvik.system.NativeStart.main(Native Method)
09-30 00:02:52.363: E/AndroidRuntime(32284): Caused by:
android.view.InflateException: Binary XML file line #8: Error inflating
class fragment
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.view.LayoutInflater.inflate(LayoutInflater.java:489)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.view.LayoutInflater.inflate(LayoutInflater.java:396)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
com.example.free.MainActivity.onCreateView(MainActivity.java:124)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.Activity.performStart(Activity.java:5018)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
09-30 00:02:52.363: E/AndroidRuntime(32284): ... 11 more
09-30 00:02:52.363: E/AndroidRuntime(32284): Caused by:
java.lang.ClassCastException: com.google.android.gms.maps.MapFragment
cannot be cast to android.support.v4.app.Fragment
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.Fragment.instantiate(Fragment.java:402)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.Fragment.instantiate(Fragment.java:377)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:277)
09-30 00:02:52.363: E/AndroidRuntime(32284): at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
09-30 00:02:52.363: E/AndroidRuntime(32284): ... 24 more
The class "MainActivity" is very long so I pasted it using pasebin:
http://pastebin.com/Lt3wbNzD
Thanks for your assistance!
Edit:
private GoogleMap map;
FragmentTransaction transaction =
getChildFragmentManager().beginTransaction();
transaction.add(R.id.map, map).commit();
it shows an error:
The method add(int, Fragment) in the type FragmentTransaction is not
applicable for the arguments (int, GoogleMap)

C# XNA Combining texture shaders

C# XNA Combining texture shaders

I'm having a lot of difficulty with this problem and was hoping someone
could help.
I'm making a glow shader, I have everything in place I just don't know how
to save the output of the glow shader to a texture so I can pass it into
my combine shader and place it ontop of the rendered scene.
Currently this is what I have:
(Draws the scene and sets up he render target)
//Passes the scene texture into the glow shader to blur it
// I don't know how to take the output of the code below and turn it into
a texture
GraphicsDevice.SetRenderTarget(finalGlowRenderTarget);
GraphicsDevice.Clear(new Color(0, 0, 0, 0));
sceneTexture = (Texture2D)sceneRenderTarget;
for (int l = 0; l <
resourceLoader.GlowShader.CurrentTechnique.Passes.Count; l++)
{
resourceLoader.GlowShader.Parameters["sceneTexture"].SetValue(sceneTexture);
resourceLoader.GlowShader.CurrentTechnique.Passes[l].Apply();
}
//I currently have this, but it's not working, I just get a blank black
texture
GraphicsDevice.SetRenderTarget(null);
finalGlowTexture = finalGlowRenderTarget;
GraphicsDevice.Clear(new Color(0, 0, 0, 0));
//Draws everything
for (int l = 0; l <
resourceLoader.GlowCombineShader.CurrentTechnique.Passes.Count;
l++)
{
resourceLoader.GlowCombineShader.Parameters["sceneTexture"].SetValue(renderTargetTexture);
resourceLoader.GlowCombineShader.Parameters["glowTexture"].SetValue(finalGlowTexture);
resourceLoader.GlowCombineShader.CurrentTechnique.Passes[l].Apply();
}
//Applies everything to the fullscreen quad
renderQuad.Render();

Pick random number within a range

Pick random number within a range

I have a table (TableA) with an integer column(ColumnA) and there is data
already in the table. Need to write a select statement to insert into this
table with the integer column having random values within 5000. This value
should not already be in columnA of TableA
Insert into TableA (columnA,<collist....>)
SELECT <newColId> ,<collist....> from TableB <where clause>

Saturday, 28 September 2013

Most popular, extensible wiki?

Most popular, extensible wiki?

I am trying to find a wiki, preferably open source, that I can easily
extend programmatically. xwiki (though Java/groovy based) seems a bit
clumsy to me. Just discovered twiki and love it (though Perl is not my
language of choice).
Problem is, I looked up a bunch of wikis on google trends and it seems
that twiki is way past its popularity peak. Something must have "stolen"
its market share, but what? Confluence has risen, but it's commercial and
a paid product. Anything else?

How use a function from algo.generic

How use a function from algo.generic

I'm trying to use from the Repl the algo.generic pow multifunction, in
order to learn clojure.
How can I use algo.generic from the Repl?
-I'm using lein repl.
-added [org.clojure/algo.generic "0.1.1"] at project.clj
-lein deps
=> (use 'clojure.algo.generic)
=> (pow 5 6)
CompilerException java.lang.RuntimeException: Unable to resolve symbol:
pow in this context,
compiling:(/tmp/form-init6907113967558511638.clj:1:1)`

Thanks..

Path aliasing for static resources in Spring dispatcher servlet

Path aliasing for static resources in Spring dispatcher servlet

I have a Spring Web app where the dispatcher servlet is only used for
static files. There also is a Jersey servlet for API calls from
JavaScript, mapped on another URL pattern, not too relevant to my problem.
At the moment my entire dispatcher configuration looks like this:
@Configuration
@EnableWebMvc
public class DispatcherConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/www/");
}
}
There is a main.html file right under www in my classpath. If a request
comes in for /main.html, the file is served correctly. Great.
Now, I would like this same file to be returned for requests on /, /part
and a bunch other paths. Basically, I want some kind of path aliasing
here, or direct mapping from path to file. How can I achieve it?

Friday, 27 September 2013

OpenFileDialog - Check if has not been selected

OpenFileDialog - Check if has not been selected

I am working on a procedure to Open a file from Excel. I want to insert a
check, if the user presses Open without selecting a file, then have a
message box pop warning.
Here is a portion of my code where I want to insert the check. I tried
using Is Nothing, but it did not work for me.
If GetOpenFileName.ShowDialog() =
System.Windows.Forms.DialogResult.OK Then
fileStream = GetOpenFileName.OpenFile()
If (fileStream Is Nothing) Then 'I tried checking here,
but it does not fire.
vmbContinue = MsgBox(strAlert, MsgBoxStyle.RetryCancel
+ MsgBoxStyle.Critical, "No Workbook Seletected")
If vmbContinue = MsgBoxResult.Cancel Then
xlWB.Close(SaveChanges:=False)
Exit Sub

Approach to Incrementally Index Database Data from Multi-Table Join in Lucene with No Unique Key

Approach to Incrementally Index Database Data from Multi-Table Join in
Lucene with No Unique Key

I have a particular SQL join such that:
select DISTINCT ... 100 columns
from ... 10 tabes, some left joins
Currently I export the result of this query to XML using Toad (I'll query
it straight from Java later). I use Java to parse the XML file, and I use
Lucene (Java) to index it and to search the Lucene index. This works
great: I get results 6-10 times faster than querying it from the database.
I need to think of a way to incrementally update this index when the data
in the database changes.
Because I am joining tables (especially left joins) I'm not sure I can get
a unique business key combination to do an incremental update. On the
other hand, because I am using DISTINCT, I know that every single field is
a unique combination. Given this information, I thought I could put the
hashCode of a document as a field of the document, and call updateDocument
on the IndexWriter like this:
public static void addDoc(IndexWriter w, Row row) throws IOException {
//Row is simply a java representation of a single row from the above
query
Document document = new Document();
document.add(new StringField("fieldA", row.fieldA, Field.Store.YES));
...
String hashCode = String.valueOf(document.hashCode());
document.add(new StringField("HASH", hashCode, Field.Store.YES));
w.updateDocument(new Term("HASH", hashCode), document);
}
Then I realized that updateDocument was actually deleting the document
with the matching hash code and adding the identical document again, so
this wasn't of any use.
What is the way to approach this?

Getting meta tags from a page source using Selenium Python

Getting meta tags from a page source using Selenium Python

I'm trying to fetch the data from the URL
https://play.google.com/store/apps/details?id=com.teslacoilsw.launcher&hl=en
and fetch the below data
<meta content="3.99" itemprop="price">
I used the following code implemented in Python to fetch but it failed.
browser = webdriver.Firefox() # Get local session of firefox
browser.get(sampleURL) # Load page
assert "Google Play" in browser.title
priceValue = browser.find_element_by_xpath("//div[@itemprop='price']")#
print priceValue.text
But it says it can't find the xpath of value price. Any idea why?

Cannot allocate objects of type _____ because the following virtual functions are pure within ____

Cannot allocate objects of type _____ because the following virtual
functions are pure within ____

I'm new to C++ and can't seem to figure this one out. I'm working on
implementing classes for chain manipulations. The error is stemming from
these two classes:
Chain.h
//Chain.h file
#ifndef CHAIN_H
#define CHAIN_H
#include <iostream>
#include <sstream>
#include <string>
#include "Linearlist.h"
#include "chainNode.h"
using namespace std;
class chain : public linearList
{
public:
//Constructor, copy constructor, and destructor
chain(int initialCapacity);
//chain(const chain<T>&);
//~chain();
//Other Methods
virtual bool empty() const {return listSize==0;}
virtual int size() const {return listSize;}
virtual int* get(int theIndex) const;
virtual int indexOf(const int& theElement) const;
virtual void erase(int theIndex);
virtual void insert(int theIndex, const int& theElement);
virtual void traverse();
virtual void maxMin();
protected:
void checkIndex(int theIndex) const;
int* firstNode;
int listSize;
};
Linearlist.h
#ifndef linear_
#define linear_
#include <iostream>
using namespace std;
class linearList
{
public:
virtual ~linearList() {};
virtual bool empty() const = 0;
virtual int size() const = 0;
virtual int* get(int theIndex) const = 0;
virtual int indexOf(const int& theElement)const = 0;
virtual void erase(int theIndex) = 0;
virtual void insert(int theIndex,
const int& theElement) = 0;
virtual void traverse()=0;
virtual void MaxMin()=0;
// virtual void output(ostream& out) const = 0;
};

Htaccess to change URL displayed in browser

Htaccess to change URL displayed in browser

I am trying to prevent xyz.com from appearing in the browser address bar
but still direct abc.com traffic to the xyz.com site. I was expecting that
to happen once I removed "R" from the [QSA, L]. However there doesn't
appear to be any change. Is there a different HTTP header or connection
variable that I should be using?
rewritecond %{HTTP_HOST} ^(www\.)?abc\.com$ [NC]
rewriterule ^ http://xyz.com/?snack [QSA,L]

How can I speed up this SQL view?

How can I speed up this SQL view?

I'm a beginner at this so hope you can help. I'm working in SQL server
2008R2 and have a view that is comprised from four tables all joined
together:
SELECT DISTINCT ad.award_id,
bl.funding_id,
bl.budget_line,
dd4.monthnumberofyear AS month,
dd4.yearcalendar AS year,
CASE
WHEN frb.full_value IS NULL THEN '0'
ELSE frb.full_value
END AS Expenditure_value,
bl.budget_id,
frb.accode,
'Actual' AS Type
FROM dw.dbo.dimdate5 AS dd4
LEFT OUTER JOIN dbo.award_data AS ad
ON dd4.fulldate BETWEEN ad.usethisstartdate AND
ad.usethisenddate
LEFT OUTER JOIN dbo.budget_line AS bl
ON bl.award_id = ad.award_id
LEFT OUTER JOIN dw.dbo.fctresearchbalances AS frb
ON frb.el3 = bl.award_id
AND frb.element4groupidnew = bl.budget_line
AND dd4.yearfiscal = frb.yr
AND dd4.monthnumberfiscal = frb.period
The view has 9 columns and 1.5 million rows and growing. A select * from
this view was taking 20 minutes for all the rows. I added indexes on the
fields in the tables that are joined on and that improved it to 10
minutes. My question is what else could I do to get the select to run
faster?
Many thanks, Violet.

Thursday, 26 September 2013

checkedListBoxControl1_ItemCheck Distinguish between user check AND programmatically checked

checkedListBoxControl1_ItemCheck Distinguish between user check AND
programmatically checked

I have a checked list and when the program loads, I need to load a list of
string and boolean to the checklist box. But whilst setting the booleans
this.mediaCenter.ItemManager.SetDirectoryCheck(index, isChecked);
checkedListBoxControl1_ItemCheck Fires. I dont want that because when it
fires, it refreshes my database and takes a long time to complete. I only
want it to fire if user changes the checked list Check state.
Note: I have
Presently I am using A flag to do that and its ugly and giving me a lot of
problems else here
private void checkedListBoxControl1_ItemCheck(object sender,
DevExpress.XtraEditors.Controls.ItemCheckEventArgs e) //fires second
on check
{
int index = e.Index;
bool isChecked = e.State == CheckState.Checked;
this.mediaCenter.ItemManager.SetDirectoryCheck(index, isChecked);
if (this.IsUserClick)
BuildDatabaseAsync();
this.IsUserClick = false;
}
private bool IsUserClick;
private void checkedListBoxControl1_Click(object sender, EventArgs e)
//Fires first on check
{
if (checkedListBoxControl1.SelectedItem == null) return;
IsUserClick = true;
}
May be my approach of filling the Listbox Control is strange in the first
place. But due to a lot of unwanted changes along the path. I do it as
follows
private void BuildCheckListControl(string[] dirs)
{
IsUserClick = false; "directories reources" and prevent UI from
updating
this.checkedListBoxControl1.DataSource = dirs;
for (int i = 0; i < dirs.Length; i++)
checkedListBoxControl1.SetItemChecked(i, checkedList[i]);
}
checkedList[] contains an array of booleans corresponding to the dirs arrays

Thursday, 19 September 2013

How to set number picker value when the min and max are the same?

How to set number picker value when the min and max are the same?

I can't seem to figure out how for a value into the numberpicker. It
always shows 0 when the min and max are the same. Is there any way to
ovveride it? Here is my code.
int min =
cursor.getInt(cursor.getColumnIndex(RestaurantElementsTable.KEY_MIN_QUANITY));
int max =
cursor.getInt(cursor.getColumnIndex(RestaurantElementsTable.KEY_MAX_QUANITY));
int defaultQuanity =
cursor.getInt(cursor.getColumnIndex(RestaurantElementsTable.KEY_DEFAULT_QUANITY));
String[] nums = new String[21];
for(int i=0; i<nums.length; i++)
nums[i] = Integer.toString(i*1);
if ( max - min == 0){
((NumberPicker) view).setValue(defaultQuanity);
}else {
((NumberPicker) view).setMaxValue(max);
((NumberPicker) view).setMinValue(min);
((NumberPicker) view).setWrapSelectorWheel(false);
((NumberPicker) view).setValue(defaultQuanity);
}

Get UTC date of last commit

Get UTC date of last commit

I'm trying to put together a bash/sh script that gets the UTC time of the
last commit from a svn repo (the other VCSs are easy) I understand that i
can just do svn propget --revprop -rHEAD svn:date and get it rather
easily, but there is no guarantee that the svn checkout will be online, so
I'd prefer an offline version, if possible.
Maybe something to do with getting the UTC time from svn info? (by
screwing with the timezones)
Summary: How can i get the UTC time of a svn commit, while not having
access to the server?
Thanks

generate dynamic URL to download local files

generate dynamic URL to download local files

I'm looking for a way (in java) to explore the file tree of my disk, and
generate a dynamic link
(https://mydomain.com/QAJDFDJJxxxxxxxxxxxxxxxxjjhjh) accessible from
outside (I have a public IP address) of a given file.
Thanks in advance

MeasureString length is different from CSS Width

MeasureString length is different from CSS Width

I have a program that let's users create a canvas and drag/drop/resize
text onto that canvas using jquery ui. I submit the CSS & DOM details via
JSON to the server to draw these out and return a pdf. I also scale up the
size of the canvas and all related elements to draw them at higher
resolution using the GDI in .NET.
This all works great, except around line-height. This is defined in the
CSS as the same as the font-size in px. So, when I draw text, I split the
text string and draw word by assembling a line and then moving to the next
one by the font size. I do this word by word and measure the string
against the text's parent div's width. 99% this works, but occasionally
there is a difference when the word is wrapped in my calculation and what
is in the browser (screenshot below).
I've added a 1% buffer to the width in .NET to catch these, but there is
always a slight discrepancy that seems to change depending on the font.
Is there a way I can preserve the same wrap in browser in .NET? Is there a
better way to draw out text than what I am doing? Can I change CSS to act
more like .NET in the word wrap detection? This seems like a minor
problem, but clients expect parity between what they create and what gets
generated, so I'm going nuts here trying to find a good solution. I'm open
to anything, thanks!
Example Pic: The word 'pick' wraps onto the next line when I draw it in
.NET. The right side is the editor in the browser, while the rendered
result is on the left.

.NET code:
else if (c.Item is textObj)
{
textObj t = (textObj)c.Item;
if (string.IsNullOrWhiteSpace(t.text) ||
t.text.Length == 0)
continue;
//get color
//SolidBrush textColor = new
SolidBrush(ColorTranslator.FromHtml(t.color));
SolidBrush textColor = new
SolidBrush(Color.FromArgb(alphaBrush,
ColorTranslator.FromHtml(t.color)));
//get font
//get optional font style
//FontFamily ff = new FontFamily(t.font);
//ff.IsStyleAvailable(FontStyle.Regular);
FontStyle fs = FontStyle.Regular;
if (t.italic)
{
fs = fs | FontStyle.Italic;
}
if (t.bold)
{
fs = fs | FontStyle.Bold;
}
if (t.underline)
{
fs = fs | FontStyle.Underline;
}
InstalledFontCollection fontsCollection = new
InstalledFontCollection();
FontFamily[] fontFamilies = fontsCollection.Families;
List<string> fonts = new List<string>();
FontFamily ff = new FontFamily(t.font);
ff = fontsCollection.Families.Where(n => n.Name ==
t.font).FirstOrDefault();
Font f = new Font(t.font, t.font_size, fs,
GraphicsUnit.Pixel, 0);
//get alignment
StringFormat frmt;
switch (t.align)
{
case "center":
frmt = new StringFormat { LineAlignment =
StringAlignment.Center, Alignment =
StringAlignment.Center, FormatFlags =
StringFormatFlags.NoClip };
break;
case "left":
frmt = new StringFormat { LineAlignment =
StringAlignment.Near, Alignment =
StringAlignment.Near, FormatFlags =
StringFormatFlags.NoClip };
break;
case "right":
frmt = new StringFormat { LineAlignment =
StringAlignment.Far, Alignment =
StringAlignment.Far, FormatFlags =
StringFormatFlags.NoClip };
break;
default:
frmt = new StringFormat { LineAlignment =
StringAlignment.Near, Alignment =
StringAlignment.Near, FormatFlags =
StringFormatFlags.NoClip };
break;
}
t.text = this.CleanString(t.text);
//split string
List<string> words = t.text.Split(new char[]{'
',}).ToList();
words = HandleHyphens(words);
string currentLine = string.Empty;
int currentWord = 0;
int currentY = t.coord.y;
SizeF stringSize = new SizeF();
bool IsHyphenated = false;
foreach (string w in words)
{
string testLine;
if (w.Length > 1 && LeftRightMid.Right(w, 1)
== "-")
{
if (IsHyphenated)
{
//handles multiple hyphendated words
testLine = currentLine + w;
}
else
{
testLine = currentLine + " " + w;
}
IsHyphenated = true;
}
else if (IsHyphenated)
{
testLine = currentLine + w;
IsHyphenated = false;
}
else
{
if (currentWord > 0 &&
words[currentWord-1] == "-")
{
testLine = currentLine + w;
}
else
{
testLine = currentWord == 0 ? w :
currentLine + " " + w;
}
//testLine = currentLine + " " + w;
IsHyphenated = false;
}
stringSize = g.MeasureString(testLine, f);
if (stringSize.Width < (t.size.width * 1.01))
//if (stringSize.Width < (t.size.width))
{
currentLine = testLine;
}
else
{
Rectangle lineRect = new
Rectangle(t.coord.x, currentY,
(int)(t.size.width*1.01),
(int)stringSize.Height);
g.DrawString(currentLine.TrimStart(' '),
f, textColor, lineRect, frmt);
currentY += t.font_size;
currentLine = w;
}
currentWord++;
}
//write last line
g.DrawString(currentLine.TrimStart(' '), f,
textColor, new Rectangle(t.coord.x, currentY,
(int)(t.size.width * 1.063),
(int)stringSize.Height), frmt);
HTML of text object:
<div id="text1379600411940" class="canvas_object text ui-draggable
ui-resizable selected" style="width: 491px; height: 322px; position:
absolute; left: 240.9px; top: 413px; z-index: 1007; opacity: 1;">
<div class="ui-resizable-handle ui-resizable-ne" style="z-index: 90;
display: block;"></div>
<div class="ui-resizable-handle ui-resizable-se ui-icon
ui-icon-gripsmall-diagonal-se" style="z-index: 90; display: block;"></div>
<div class="ui-resizable-handle ui-resizable-sw" style="z-index: 90;
display: block;"></div>
<div class="ui-resizable-handle ui-resizable-nw" style="z-index: 90;
display: block;"></div>
<div class="canvas_obj_text align_left" style="font-size: 29px;
line-height: 29px; font-family: Cabin;">One whiff and you know this is
serious stuff. The aromas of baking brioche, coconut, candied citrus and
leather pick up roasted coffee and grilled nuts on the palate, permeating
the senses. Profound depth and complexity, offering a unique Champagne
experience. Drink now through 2006. 40,000 cases made. –BS</div>
</div>

How to get Openid for google account

How to get Openid for google account

I am developing a Spring MVC webapp that has Spring security enabled. I am
trying to use OpenID to use gmail login for access to the webapp given
instructions here.
I want only a specific set of users to have access to webapp. For this, I
would be required to add all the users and their ID's to tag. (Later will
implement a DB access for this)
My question is: How can I find the OpenID for my gmail account that will
be used to access the webapp?
I understand that the OpenID is unique for each account and can be used
for local authorization. Please correct me if I am wrong.

mssql - select from another table if no results from the first table

mssql - select from another table if no results from the first table

I have to run a query to find a price. I have multiple price lists, each
in their own table. customer_price, default_price and minimum_price.
not all price lists have all the products and at times a product might not
appear on any price list and then the price needs to return 0 for the
price.
so I want to:
select price from customer_price where customer='walmart' and
product='whitebread'
if this returns a result then all is well. if the result is 0,NULL or the
query returns no rows I want this to run:
select price from default_price where customer='walmart' and
product='whitebread'
if this returns a result then all is well. if the result is 0,NULL or the
query returns no rows I want to simply return 0.
I am not sure how to proceed. I tried a case statement but the case
statement fails if no row is found in the results. how can I do this or
say if 0 results then
thanks in advance, as always.

Feed a stream into Uri

Feed a stream into Uri

I am using the MJpegDecoder from Coding4Fun to decompress a motion-jpeg
stream in a windows runtime based app.
For a project I need to compare TCP- with UDP-transmission. The decoder
expects a URI to the mjpeg source (for TCP streams it is http:// IpAdress
: PORT). now with message based UDP I was thinking about providing a
stream in which I write the single messages.
Question is:
Is it possible to get the Uri to an in-memory stream, without writing it
to a temporary file before?

Wednesday, 18 September 2013

Raphaeljs path id inside a set attributes

Raphaeljs path id inside a set attributes

I'm working on a map with Raphaeljs and I have the paths inside a set
because I want all of them to have the same attributes and all is good but
now I would like to set an id to each path and I did it to one but the
attributes got lost, so my question is...Is there a way to have an path.id
inside a set with the set attributes? Thanks
Here is the file http://jsfiddle.net/tLSpv/2/
var paper = Raphael(0,0,540, 615);
var newmexico = paper.set();
newmexico.push(
paper.path("M343.249,11.503l-1.658,3.554l-0.474,16.822c0,0-3.554-0.711-5.449-0.711
s-5.686,3.554-5.449,4.265c0.237,0.711-1.895,13.268-1.895,14.215s3.554,4.502,3.317,5.449c-0.237,0.948-0.711,3.554-0.474,4.502
c0.237,0.948,0.711,7.345,0.474,9.477c-0.237,2.132,0.948,11.846-1.658,13.268h42.883v5.449h38.855h37.197V73.103l1.303-1.303V1.239
L340.643,1.18v4.4L343.249,11.503z").node.id = 'colfax'; colfax.attr
paper.path("M448.917,73.103 448.917,87.793 448.917,93.005 469.529,93.005
469.529,101.771 506.963,101.771 506.963,111.248 506.252,111.248
506.252,139.205 533.498,139.205 533.498,56.637 539.421,56.637
539.421,1.286 450.22,1.239 450.22,71.8z"),
paper.path("M506.015,139.205 506.015,177.113 482.56,177.113 482.56,193.46
461.475,193.46 439.598,203.965 439.598,225.13 438.888,225.841
438.888,262.405 454.84,262.405 454.84,262.09 454.84,262.405 476.36,262.405
476.36,253.718 496.103,253.718 496.103,243.648 505.146,243.648
505.146,234.961 514.386,234.961 514.386,224.971 533.498,224.971
533.498,139.205 506.252,139.205z"),
paper.path("M143.759,9.845c0,0-2.132,3.554-3.317,3.554s-12.32,9.714-12.32,9.714V86.05
l5.923,1.269l40.751,0.474h18.717v22.982h56.151v4.311l0.059,0.013l-0.059-0.013v3.271h17.769v-7.108h30.326v3.125l4.738,0.902
l3.08-1.185l6.634-0.237l3.08-4.502l-13.031-5.686c0,0-8.055-4.738-9.003-7.818c-0.948-3.08-11.372-11.846-11.372-11.846
l-4.265-1.658c0,0-8.529-1.895-9.24-3.08c-0.711-1.185,0.474-3.791,0.474-3.791l4.502-1.658l3.317-1.895v-9.003l0.474-11.372
l-2.606-11.846l0.711-5.686l-1.185-6.871v-6.634l0.237-9.714l-4.265-9.477l-0.032-0.173l-124.69-0.066l-2.031,4.74L143.759,9.845z"),
paper.path("M454.844,262.343 454.844,318.731 454.844,262.343
438.893,262.343 438.893,243.548 438.891,243.548 419.78,243.548
419.78,253.183 411.408,253.183 411.408,262.286 411.408,262.344
371.131,262.344 371.131,289.611 371.131,289.827 370.509,289.827
370.509,317.31 380.134,317.31 380.134,326.471 400.352,326.471
400.352,328.051 436.681,328.051 436.681,318.889 454.873,318.889
454.873,262.343z")) .attr({ fill: '#F7F0EA', stroke: '#006599',
'stroke-width': 1, cursor: 'pointer' })
.hover(function () {
this.animate({fill: '#006599'}, 300);
},
function () {
this.animate({fill: '#F7F0EA'}, 300)
}
);

Why does simplex noise seem to have *more* artifacts than classic Perlin noise?

Why does simplex noise seem to have *more* artifacts than classic Perlin
noise?

I read Stefan Gustavson's excellent paper on simplex noise, in which I was
promised that:
Simplex noise has no noticeable directional artifacts
in contrast with "classic" Perlin noise. I excitedly implemented it to
find out that the opposite appeared to be true. I do see artifacts in
classic noise, but I see at least as many artifacts in simplex noise,
aligned at 45 degrees to the main axes. They're especially noticeable when
you map the noise to a step function.
To ensure it wasn't a problem with my implementation, I used someone
else's JavaScript implementation. Compare some images:
Classic noise vs simplex noise
Classic noise step vs simplex noise step
And here's a gallery with all of them. In that last image, look for
borders that are aligned at 45 degrees from horizontal/vertical. They're
all over the place. I can highlight some of them if need be, but they seem
really obvious to me. (And again, I see them in the classic noise image as
well.)
Is this a problem with the simplex noise algorithm? Is it something that
can be fixed? Or am I the only one who sees this as a problem?

Why does TextReader.Read return an int, not a char?

Why does TextReader.Read return an int, not a char?

Consider the following code ( .Dump() in LinqPad simply writes to the
console):
var s = "&#55378;&#57186;"; //3 byte code point. 4 byte UTF32 encoded
s.Dump();
s.Length.Dump(); // 2
TextReader sr = new StringReader("&#55378;&#57186;");
int i;
while((i = sr.Read()) >= 0)
{
// notice here we are yielded two
// 2 byte values, but as ints
i.ToString("X").Dump(); // D852, DF62
}
Given the outcome above, why does TextReader.Read() return an int and not
a char. Under what circumstances might it read a value greater than 2
bytes?

how to configure mysql to accept local queries

how to configure mysql to accept local queries

Hi have a c++ application that makes queries to mysql database, I need to
run LOAD DATA LOCAL INFILE but if I do this from c++ it does not work...
right now I have it set using the username in my.cnf which is on default
(mysql)
#define USER "mysql"
#define PASSWD "jdhfa"
#define URL "tcp://10.3.21.49:3306"
if I use 127.0.0.1 in the url it will throw an error
Can't connect to MySQL server on '127.0.0.1' (111) (MySQL error code:
2003, SQLState: HY000 )
Server waiting for connections
In my.cnf I changed bind address to my IP becasue I need to access the
database from other places, but I still need to use it from my c++
program, I tried to add two bind-address statement
bind-address 10.3.21.49
bind-address 127.0.0.1
and this did not work.
I am not sure what else to do here??

How do I return a list of joined hibernate entities?

How do I return a list of joined hibernate entities?

Suppose I have a MySQL table, and entity tag in hibernate, where a tag is
a row in the following
id (primary key), tag, entity id
1, food, 77
2, shop, 98
3, food, 32
...
I'd like to return the total counts of the same tag sorted in decreasing
number of entries. Aka,
tag, count
food, 2
shop, 1
...
I was told to do something like
SELECT tag, COUNT(*) `count`
FROM table1
GROUP BY tag
ORDER BY `count` DESC
Output:
| TAG | COUNT |
|------|-------|
| food | 2 |
| shop | 1 |
However, how do I read this newly created list of entities out from
Hibernate? Do I need to somehow define a new object to read this list out?
The same question goes for say reading an entity (row) that is defined,
but just joined with another entity as part of a query. How do I read out
the result?
Thanks!

How to get Windows Login Time in C# Asp.net?

How to get Windows Login Time in C# Asp.net?

Anyone has got ideas/solution for getting the windows Login time in C#
Asp.net.. I just want the code to get it... Thanks in advance..

tsql: How to retrieve the last date of each month between two dates

tsql: How to retrieve the last date of each month between two dates

I have two date for example 08/08/2013 and 11/11/2013 and I need last date
of each month starting from August to November in a table so that i can
iterate over the table to pick those dates individually.
I know how to pick last date for any month but i am stucked with a date
range.
kindly help, it will be highly appreciated.
Note : I am using Sql 2008.

hover on parent and highlith all childs

hover on parent and highlith all childs

I have the following html:
<span id="spanus">
<a href="#">child1</a>
<a href="#">child2</a>
<a href="#">child3</a>
</span>
and css:
span{
background: gray;
border: 2px solid #eaeaea;
display: inline-block;
margin: 40px;
}
span:hover{
background: yellow;
border: 2px solid #fbfbfb;
}
a{
padding: 10px;
display: inline-block;
}
span a:hover{
color: #fff;
background: red;
}
fiddle:
My question is how can I have hover over all 3 a childs once of span when
I hover the span
thank you.

Tuesday, 17 September 2013

Facebook feed dialog - feed dialog not working as expected

Facebook feed dialog - feed dialog not working as expected

I have been trying this for the past couple of days but I couldn't get it
worked. I am trying to post on a users wall using feed dialog when he
enters an app for the first time using javascript SDK. Below is the code:
<div id="fb-root"></div>
<script type="text/javascript">
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
window.fbAsyncInit = function() {
FB._https = (window.location.protocol == "https:");
FB.init({
appId: '<?php echo $config["apikey"]; ?>',
frictionlessRequests : true,
status: true,
cookie: true,
oauth: true,
xfbml: true
});
FB.Event.subscribe('edge.create', function(href, widget) {
// Do something, e.g. track the click on the "Like" button here
addChipsLike();
});
};
var ffuname = '';
var lluname = '';
function post_to_wall()
{
FB.api('/me', function(response)
{
ffuname = response.first_name;
lluname = response.last_name;
});
//alert('inside');
FB.ui({
method: 'feed',
link: 'somelink',
picture: 'somepicture.png',
name: 'Name of the link',
caption: 'CaptDescription'
}, doitnow);
}
</script>
I check whether the user is new or not and if he is a new user I call the
post_to_wall() function inside php code.
The Problem is sometimes the feed dialog is loading but i couldn't get the
username, and sometimes the feed dialog is loading but "An error occurred.
Please try again later" in it and, sometimes the feed dialog is not at all
loading with an error in console, say "FB is not defined" in the line
FB.api.
Could anybody please help me to fix this issue? Thanks in advance...

is it possible to declare two application in AndroidManifest

is it possible to declare two application in AndroidManifest

the manifest is like this:
<manifest
<application
android:name=".MyApplication1" >
<MainActivity
...
</application>
<application
android:name=".MyApplication2" >
<MyService
android:process=":remote" />
</application>
actually, i want to fix a issue like this: if I declare service MyService,
which runs in a private process, whthin MyApplication1, then two instances
of MyApplication1 will be created, which means the initialization in
MyApplication1 will be done twice. So, i wanna to init a separate
application when MyService is to be launched by declaring MyService in a
separate application MyApplication2 as shown above in the manifest. But
unfortunately, it doesn't work as i think: MyService can not start at all.
have i omitted something, or made a fundamental mistake to try doing so?

JQuery Mobile and Firefox don't play well together?

JQuery Mobile and Firefox don't play well together?

Having some teething issues with jQuery Mobile. Was wondering if anybody
else is experiencing a smattering of errors when they're using Firefox
(desktop) and have the jQuery Mobile script includes in their <head> like
so:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script
src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
In both Chrome and Firefox I get a host of CSS errors, which I presume are
negligible. But in Firefox I get a couple of JS errors on top of that,
which also seems to break my page (responsive elements not rendering like
they would when I remove the jQuery Mobile script).
The JS errors:
Empty string passed to getElementById(). @
http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.js:11100
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. @
http://code.jquery.com/jquery-1.9.1.js:3346
I know the errors seem pretty verbose, but I'm not familiar with bloaty
javascript plugins and their policy on graceful degradation. Anyone else
having this issue?

Programmatically get all tables of a database owned by a user

Programmatically get all tables of a database owned by a user

I created the following query:
select is_tables.table_name from information_schema.tables is_tables join
pg_tables on is_tables.table_name=pg_tables.tablename where
is_tables.table_catalog='<mydatabase>' and
is_tables.table_schema<>'information_schema' and
is_tables.table_schema<>'pg_catalog' and pg_tables.tableowner='<myuser>';
I assume there is no database vendor independent way of querying this. Is
this the easiest/shortest SQL query to achieve what I want in PostgreSQL?

How to make a seperator bar invisible in VB

How to make a seperator bar invisible in VB

I have been trying to hide few menu options, I make the options invisble
and the code is as follows: mnuDataOutNegOffset.Visible = False
mnuDataOutNegLink.Enabled = False mnuDataOutNegLink.Visible = False
However these options are invisible but a separator bar is seen in the
popupmenu, how to make the separator bar invisible in the popupmenu.

Is it possible to call a function every time a view is updated in Durandal?

Is it possible to call a function every time a view is updated in Durandal?

I have a web application using Durandal and I want to call
$('document).ready(function() {
$('.selectpicker').selectPicker();
}
every time a view is updated. Does anyone have any suggestions of how to
go about this?

Sunday, 15 September 2013

JDBC CURD operatoin through Command Line Argument

JDBC CURD operatoin through Command Line Argument

i m trying to Curd operation through Command Line Argument here i assign
args[0] for operation(insert,delete ,update) args[1] for name args[2]
designation args[3] dob args[4] dob
package empcmd; import java.sql.*;
public class EmpCmd {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/sandeep";
static final String USER="root";
static final String PASS="root";
public static void main(String args[])throws ClassNotFoundException {
String name;
String desg;
int dob;
int age;
Connection con=null;
PreparedStatement ps=null;
try{
class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(DB_URL,USER,PASS);
char op;
int x=0;
op=args[0];
name=args[1];
desg=args[2];
dob=args[3];
age=args[4];
if(args[0]=insert||INSERT||Insert)
{
ps=con.prepareStatement("insert into sandeep
values(?,?,?,?)");
ps.setString(1,name);
ps.setString(2, desg);
ps.setString(3,dob);
ps.setString(4,age);
x=ps.executeUpdate();
}
else if (args[0]=update||Update||UPDATE)
{
ps=con.PrepareStatement("update sandeep set
name=?,desg=?,dob=?,age=?");
ps.setString(1,name);
ps.setString(2, desg);
ps.setString(3,dob);
ps.setString(4,age);
x=ps.executeUpdate();
}
else if (args[0]=delete||DELETE||Delete)
{
ps=con.PrepareStatement("delete from sandeep where name=?);"
ps.SetString(1,name);
x=ps.executeUpdate();
}
}
}catch(SQLException se){
se.printStackTrace(); }
}

Icon little issue

Icon little issue

Finally the hour has come, the release folder is not empty now, the last
touches are done. I've noticed this behavior and was wondering if someone
else had this problem and how to solve it:
Ok here.
Ok here.
Not okey here.
The icon comes with a variety of sizes, and it is set as resource in VS
solution.
It's not very important but it gives a very poor image of the app. Is
there any easy solution?

parse byte count in ftp log

parse byte count in ftp log

I'm running on an arm architecture. Should be a bash script. I would like
to graph total bytes coming and out of my ftp server.
I parse the ftp.log file with this command to get this output:
`cat ftp.log | grep loaded`
the interesting lines are in this format:
Sep 14 18:46:00 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/backupffp.sh downloaded (423 bytes, 0.78KB/sec) Sep 15
22:06:47 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/ffp-2013-09-14.tar.bz2 downloaded (904753213 bytes,
1928.17KB/sec) Sep 15 22:32:26 sharecenter pure-ftpd: (doc@omega) [NOTICE]
/mnt/HD/HD_a2//SAVE/test.avi uploaded (576711530 bytes, 1465.80KB/sec)
Now I need to get the values after the "(" and before the word "bytes" and
add them.
Example:
--> downloaded 423+904753213=904753636 => returned value: 904753636
--> uploaded 576711530 => returned value: 576711530
Now the script will run every 5 minutes, so the result has to take into
account only the numbers between the last 5 minutes. Example: At 22:05
script runs and adds all bytes. When script runs again at 22:10 only the
transfered bytes between 22:05 to 22:10 should be added.
For rrd you need a simple output, 2 variables "dowloaded" and "uploaded".
So I will need those 2 values in those 2 variables.
I hope I am clear enough, if not don't hesitate to ask for more information.
Many thanks for your help.

How do you assign n buttons to jQuery dialog in a loop?

How do you assign n buttons to jQuery dialog in a loop?

The code below does something odd. Whenever you click a button in the
dialog, you see "test5" as the alert text, not "test0", "test2", ...
"test4" respectively for each button. Something about assigning the
function in a loop is not working.
var arrbuttons = [];
for (var i=0; i<5; i++) {
arrbuttons.push({click: function() { alert('test'+i);}, text:'test'+i});
}
jQuery("#requestdialog").dialog(
{
title: "test",
height: 250,
width: 500,
modal: true,
buttons: arrbuttons
}

association owned by classifier and association owned by relationship in UML

association owned by classifier and association owned by relationship in UML

7.3.3 Association(from kernel) ,page 36,UML superstructure ,v2.4.1:
an association either owned by classifier or by relationship.
Is there a real-life example in UML about association owned by classifier
and association owned by relationship?

How to design website like www.apple.com/iphone-5c

How to design website like www.apple.com/iphone-5c

I want to design website like www.apple.com/iphone-5c in right-hand side.
It will change tabs when i scrolling mouse wheel or click on "dot".
which css or script is that? please introduce me.
thank you

VCF hebrew contacts appears as questions marks

VCF hebrew contacts appears as questions marks

I have a VCF file of all my contact in hebrew, I'm using an application -
"Contact Sync for Gmail" on my mobile which is working prefectly, so i
sync all the contacts to the gmail and then i can transfer from the gmail
to my mobile with this application, but all the contacts appears with
questions marks, any idea?

Saturday, 14 September 2013

how to add 2 columms in mysql?

how to add 2 columms in mysql?

i have a table called "attendance" in which there are several columns
I want to add 2 columns and put the result in the third column in the same
table.
how to do it in (mysql).

Multiple Web Sites/Roles on Azure, Impact of staging server

Multiple Web Sites/Roles on Azure, Impact of staging server

I'm looking to set up two web roles or websites on my Azure Cloud Service.
The websites need to share the same database schema. I use NHibernate ORM,
so I have to make sure that both projects are always using the same data
model, or else it will cause major problems.
I've researched setting up multiple websites on a single web role (which
seems odd to me, can't I just run multiple web roles, each with a single
site)?
http://msdn.microsoft.com/en-us/library/windowsazure/gg433110.aspx
Like any good developer, I use a staging server. If I have to manually set
the domain name is configuration files, how will azure know not to be
sending people who visit that domain to the staging server?! I.E. If they
visit blah.foo.com and I have two deployments (staging and production), is
IIS going to be able to know only to send people to the production
environment?
Please advise on the best way to go about doing this.

Gill Sans font family rendering with @font-face

Gill Sans font family rendering with @font-face

I am new in rendering fonts with @font-face. I am using Gill Sans font
family in my design. I did research to understand make it work for me but
I am not able to understand how to use it. The font type I am using dont
have .eot and woff font type. I can just see gill sans font true type font
in my font folder.
I want if anyone can help to to understand how it work and make it easy
for me to use this. I am not understand what is happening in the below
code.
@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff') format('woff'), /* Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
Thanks,

Javascript Grammer Checking

Javascript Grammer Checking

Could someone kindly correct my javascript work?
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function myFunction()
if (screen.width 800 =>) {
alert(".");
var redirect=confirm("You are on the mobile site. Would you like to
visit our full site instead?");
if (redirect == true) {
window.location.href = 'http://TEXTHIDDEN.com/';
}
else {
return true;
}
</script>
</html>
<center><h2> Hi there. Sorry, but the TEXT HIDDEN mobile site isnt ready
yet. </h2>
<h2> If you are not on a mobile device or portable </h2>
<h2> gaming console, press on the button below. Thank You. </h2>
My aim: If a user visits the mobile version of my site, it will prompt
them to go to the desktop page, if they are using a pc or high-res tabet
(width 800+).
Thanks

C++: Reading data from a memory mapped file

C++: Reading data from a memory mapped file

I have used MapVirtualFile to map a file under Window using C++ VS2010.
I would now like to fill a structure with the data.
I have been using
void clsMapping::FeedPitchmarksFromMap(udtPitchmarks &uAudioInfo,unsigned
long int uByteStart)
{
unsigned long int iCountPM;
memcpy(&iCountPM, &((char*)(m_pVoiceData))[uBytePos],sizeof(int));
uAudioInfo.Pitchmarks.resize(iCountPM);
for (unsigned long int i=0;i<iCountPM;i++)
{
iBytePos+=sizeof(int);
unsigned long int iByteStart;
memcpy(&iByteStart, &((char*)(m_pVoiceData))[iBytePos],4);
iBytePos+=sizeof(int);
unsigned long int iByteCount;
memcpy(&iByteCount, &((char*)(m_pVoiceData))[iBytePos],4);
iBytePos+=sizeof(int);
unsigned int iF0;
memcpy(&iF0, &((char*)(m_pVoiceData))[iBytePos],4);
uAudioInfo.Pitchmarks[i].ByteStart =iByteStart;
uAudioInfo.Pitchmarks[i].ByteCount =iByteCount;
uAudioInfo.Pitchmarks[i].F0 =iF0;
}
}
As one can see, I am currently using memcpy to get the data. Is there a
faster way to do "get my data over"?

How to create separate model for each user type in Laravel

How to create separate model for each user type in Laravel

I have the basic User model that deals with the users table, I have two
types of users, each type has different attributes and reads those
attributes form a different database.
User: name, email, type (x,y)
type_x: gender, age
type_y: color, location
So I have the user table, the type_x table, and the type_y table.
How can I create three different models, User, Typex, and Typey so that I
can retrieve the data of each model in a different way and dealing with a
different table?

Get only random 20% of consecutive inputs

Get only random 20% of consecutive inputs

I have a system that constantly gathers items from a rss feed.
I want to take only a certain percentage, say 20%, of those items, randomly.
My approach is that for each item I "throw a dice" using rand(0,100) and
accept the item only if the result of this statement is < 20.
Is it a good approach?

Friday, 13 September 2013

Helper class is not returning image name which is stored in SQLite databse

Helper class is not returning image name which is stored in SQLite databse

I am trying to retrieve image paths from SQLite database and display
corresponding images on the ImageView. The problem is, helper class is not
returning the image name, so that, I am unable to display the image in the
ImageView. Please see the following code for helper.class
public static final String GETSD = "select DISTINCT FileName from Photos
where
last_disp_TimeStamp in (select MIN(last_disp_TimeStamp) from Photos where
DisplayCount in (select MIN(DisplayCount) from Photos));";
public static final String UPDATE_DISP = "update Photos set DisplayCount =
Displaycount+1 where last_disp_TimeStamp in (select MIN(last_disp_TimeStamp)
from Photos where DisplayCount in (select MIN(DisplayCount) from Photos));";
public static final String UPDATE_TIMESTAMP = "update Photos set
last_disp_TimeStamp = CURRENT_TIMESTAMP where FileName in (select
FileName from
Photos where last_disp_TimeStamp in (select MIN(last_disp_TimeStamp) from
Photos
where DisplayCount in (select MIN(DisplayCount) from Photos)));";
public String getSDPath() {
// TODO Auto-generated method stub
Cursor c;
SQLiteDatabase myDB ;
String commonpath = "/storage/sdcard/DCIM/Camera/SAMPLE IMAGES/";
String result="";
String h = "";
try {
myDB=this.openDataBase();
c=myDB.rawQuery(GETSD,null);
myDB.execSQL(UPDATE_DISP);
myDB.execSQL(UPDATE_TIMESTAMP);
if (c != null ) {
if (c.moveToFirst()) {
do {
// put your code to get data from cursor
int img = c.getColumnIndex("FileName");
result = c.getString(img);
h=commonpath+result;
}while (c.moveToNext());
}
}
if(c != null)
{
myDB.close();
c.close();
}
}catch(SQLException sqle){
throw sqle;
}
return h;
}
The queries are working fine, when I test them on SQLite browser I don't
have any problem with queries. I have checked the database file in
/data/data/com.example.myappname/databases/ folder. I have the required
photos in /storage/sdcard/DCIM/Camera/SAMPLE IMAGES/.
The path this function is returning is, /storage/sdcard/DCIM/Camera/SAMPLE
IMAGES/. But the expected string from this function is, something like
/storage/sdcard/DCIM/Camera/SAMPLE IMAGES/xxx.png
The string "xxx.png" is stored in database and with the query GET_SD, I am
retrieving the name of the image.
I have checked many questions and tutorials on this, but didn't get
solution for this.Please suggest me some solution. Thanks in advance.

What is a 'library' file? ie: shared library

What is a 'library' file? ie: shared library

For example, the description of /lib/ is that it contents shared library
files for the system.
What exactly is a library? Are we talking about library files similarly to
importing a library in C? What is contained in a library file and what are
they used for?
What relation does it have to a .dll

xls export problemusing params

xls export problemusing params

Is there any way or example to export xls on rails 2.3.5 without using
gems and something complicated?
I'm trying to export to xls with conditions by ejectuve_id that i selected
i have this code
*********It s in my controller********
@search_ejecutive = params[:search_ejecutive].to_i
@search_status = params[:status_id].to_i
@list_ejecutives_comision = Ejecutive.find(:all)
ejecutive_ids = []
obj_user.ejecutives.each do |ejecutive|
@list_ejecutives_comision << Ejecutive.find(ejecutive.id)
end
@list_policies_search = Policy.deleted_is(0)
if params[:search_ejecutive].to_i!=0
@list_policies_search =
@list_policies_search.ejecutive_id_is(@search_ejecutive)
end
ejecutive_ids = []
obj_user.ejecutives.each do |ejecutive|
ejecutive_ids << ejecutive.id
end
if !ejecutive_ids.blank?
@list_policies_search =
@list_policies_search.ejecutive_id_in(ejecutive_ids)
end
@list_policies_search = @list_policies_search.deleted_is(0)
@list_policies = @list_policies_search.paginate(:page =>
params[:page], :per_page => 10)
And here i'm showing links that i tried
<% form_remote_tag
:url=>{:action=>"generate_print_ejecutive_comercial"},:before=>"load_close('loading_search')",:success=>"load_off('loading_search')"
do -%>
<label>Ejecutivo:</label>
<%= select_tag 'search_ejecutive',"<option
value=\"\">Seleccione</option>"+options_for_select(@list_ejecutives_comision.collect
{|t| [t.name.to_s+" "+t.lastname1.to_s,t.id]})%>
<input name="Buscar" value="Buscar" type="submit" /><span
id="loading_search"></span>
<% end %>
<%=
link_to("xls","http://localhost:3000/policy_management/policy/generate_print_ejecutive/generate_print_ejecutive.xls")%>
<%= link_to "xls",
:controller=>"policy_management/policy",:action=>"generate_print_ejecutive",:format=>"xls"
,:search => params[:search_ejecutive],:page => params[:page] %>
<%= link_to 'Imprimir',
:controller=>"policy_management/policy",:action=>"generate_print_ejecutive",
:format=>"pdf" %>
<div id="table">
<%= render :partial=>"table2" %>
My :partial table2 is the result of @list_policies My teacher doesn't want
doesn't want to reveal me the secret ,told me that the trick is
@list_policies
I tried to export manually and i tried this
@list_policies.find(:all,:conditions=>"ejecutive id = 1")
Somebody can help me with this, my teache told me that i need to export
:search_ejecutive params
I will appreciate all help

'Model is not immutable' TypeError

'Model is not immutable' TypeError

I am getting this traceback;
--- Trimmed parts ---
File "C:\Users\muhammed\Desktop\gifdatabase\gifdatabase.py", line 76, in
maketransaction
gif.tags = list(set(gif.tags + tags))
File "C:\Program Files
(x86)\Google\google_appengine\google\appengine\ext\ndb\model.py", line
2893, in __hash__
raise TypeError('Model is not immutable')
TypeError: Model is not immutable
Here is related parts of my code;
class Gif(ndb.Model):
author = ndb.UserProperty()
#tags = ndb.StringProperty(repeated=True)
tags = ndb.KeyProperty(repeated=True)
@classmethod
def get_by_tag(cls,tag_name):
return cls.query(cls.tags == ndb.Key(Tag, tag_name)).fetch()
class Tag(ndb.Model):
gif_count = ndb.IntegerProperty()
class PostGif(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
if user is None:
self.redirect(users.create_login_url("/static/submit.html"))
return
link = self.request.get('gif_link')
tag_names = shlex.split(self.request.get('tags').lower())
@ndb.transactional(xg=True)
def maketransaction():
tags = [Tag.get_or_insert(tag_name) for tag_name in tag_names]
gif = Gif.get_or_insert(tag_name)
if not gif.author: # first time submission
gif.author = user
gif.tags = list(set(gif.tags + tags))
gif.put()
for tag in tags:
tag.gif_count += 1
tag.put()
if validate_link(link) and tag_names:
maketransaction()
self.redirect('/static/submit_successful.html')
else:
self.redirect('/static/submit_fail.html')
What is the problem with gif.tags = list(set(gif.tags + tags)) line?

Can't checkout master branch

Can't checkout master branch

I've been working in a branch with some code to improve an application.
Now that I this is finished, I want to merge this branch with master
branch, but I can't. I first try to checkout master branch like this:
$ git checkout master
but I get this error:
error: The following untracked working tree files would be overwritten by
checkout:
vendor/bin/doctrine
vendor/bin/doctrine.php
...
but the vendor directory is included in .gitignore file. If I do:
$ git status
I get this:
# On branch mejoras_contralador
nothing to commit (working directory clean)
After this, I would do:
$ git merge branch
How to avoid this error?

Kernel Level Event Detection

Kernel Level Event Detection

Is it possible to detect an event occurring in an application on Kernel
level?
For example, I have a very simple program that takes two input numbers,
adds them and displays the result. I wish to build another program which
detects when the addition in the first program is complete - This is an
event detection in some sense. (it does not wish the result, just needs to
know when the additon is done).
Now I do not wish to modify my first application to "send" some kind of
response when it is done adding. Is there some way I can contact the
kernel to notify me, when this particular application performs an
"addition", and I use this as proof that the addition has occured ?
(This may not be the best example, but I hope you get the idea. Another
example could be that I wish to detect when a browser (Chrome for e.g.)
has finished downloading a file, so I can sync it to my dropbox. Assume
that chrome fires no event on download complete and that I want to do it
without modifying the Chrome source code.)
Also, I wish to do it on Kernel Level because I wish the event detection
to be language independent. However, if there is any such feature in any
particular language, I would be interested in knowing it as well.
Any response would be appreciated. Thanks.

WP7 Map Application with Multiple TileSources

WP7 Map Application with Multiple TileSources

I'm developing a C# map application for Windows Phone 7 using custom
MapTileSources. I'm wondering if I can have multiple map layers, so that
each of them binds to a different MapTileSource. The idea is that the
first layer contains the ground map and the layers above that would
represents routes and other information on top of the ground map. The
layers above should be partially transparent. Is this possible and any
ideas how this could be done?

Thursday, 12 September 2013

How do I tell sbt to publish a zip instead of a jar?

How do I tell sbt to publish a zip instead of a jar?

SBT docs describe how to publish to a maven repo:
http://www.scala-sbt.org/release/docs/Detailed-Topics/Publishing
I want to publish just the contents of the src/main/resources folder and I
want to publish a zip instead of a jar.
Can I do this without adding an sbt plugin?

Post http python

Post http python

The below python script, when run, produces an HTML file. When the user
clicks on "submit your request", the big textarea below it is filled with
parameters that I want to send to another python script. Currently the
only way I can get it to work is to paste the textarea to the textbox at
the bottom, and press Enter.
I would like to kill the bottom texbox, and get the "submit your request"
to send the content of the area box.
Please help, I have spent countless hours today and its driving me crazy.
#!/Python27/python
import cgi, os
import cgitb; cgitb.enable() # for troubleshooting
print "Content-type: text/html"
print
print """
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
<font size="11"><b>Order Form</b></font><img border="0" src="cross.bmp"
width="70" height="70" align="right">
<br>
</br>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map_canvas{
height:400px;
width:800px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/JavaScript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/JavaScript">
</script>
<script>
var marker, myCircle, map;
var geocoder;
function initialize() {
var myLatlng = new google.maps.LatLng(43.651975,-79.378967);
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event){
var x=document.getElementById("mySelect").selectedIndex;
var y=document.getElementById("mySelect").options;
addMarker(event.latLng,Number(y[x].text));
document.getElementById("lat").value =event.latLng.lat();
document.getElementById("lon").value =event.latLng.lng();
});
}
//////////////////////////////////
function codeAddress() {
var address = document.getElementById('autocomplete').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//var myLatlng1 = new google.maps.LatLng(43.651975,-79.378967);
addMarker(results[0].geometry.location,250)
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
});
}
///////////////
function addMarker(latLng,givenRadval){
document.getElementById("lat").value =latLng.lat();
document.getElementById("lon").value =latLng.lng();
//clear the previous marker and circle.
if(marker != null){
marker.setMap(null);
myCircle.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable:true,
icon:"logo.bmp"
});
//circle options.
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0,
map: map,
center: latLng,
radius: givenRadval
};
//create circle
myCircle = new google.maps.Circle(circleOptions);
//when marker has completed the drag event
//recenter the circle on the marker.
google.maps.event.addListener(marker, 'dragend', function(){
myCircle.setCenter(this.position);
document.getElementById("lat").value =this.position.lat();
document.getElementById("lon").value =this.position.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize)
function Submit_For_Proccessing(){
document.getElementById("Request_Details").value=
"'"+document.getElementById("lat").value
+"' '"+
document.getElementById("lon").value
+"' '"+
document.getElementById("mySelect").value+"'
'"+
document.getElementById("street_number").value+"'
'"+
document.getElementById("street_name").value+"'
'"+
document.getElementById("city").value+"'
'"+
document.getElementById("Postal_Code").value+"'
'"+
document.getElementById("province").value+"'
'"+
document.getElementById("country").value+"'
'"+
document.getElementById("Site_Name").value+"'
'"+
document.getElementById("reference_number").value+"'
'"+
document.getElementById("Your_name").value+"'
'"+
document.getElementById("email_address").value+"'";
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:auto;height:400px;"></div>
<form method="post" action="index.cgi">
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>1. Define your Area of Interest:</b></legend>
<table>
<tr><input id="autocomplete" name="auto" size="24"
type="textbox" value="" color="green" ><input type="button"
value="Zoom" onclick="codeAddress()">
<tr><td align="left">Study Radius:</td><td><select width="120"
style="width: 120px" id="mySelect"><option>200</option><option
selected="true">250</option><option>300</option></select>
Meters</td></tr>
<tr><td align="left"><a
href="http://en.wikipedia.org/wiki/Latitude">Latitude</a>:</td><td><input
size="18" type="text" id="lat" value="" disabled></td></tr>
<tr><td align="left"><a
href="http://en.wikipedia.org/wiki/Longitude">Longitude</a>:</td><td><input
size="18" type="text" id="lon" value="" disabled></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>2. Define Address Details:</b></legend>
<table>
<tr><td align="left">Street Number</a>:</td><td><input
size="18" type="text" id="street_number" value="3504"
></td></tr>
<tr><td align="left">Street Name</a>:</td><td><input size="18"
type="text" id="street_name" value="Hurontario" ></td></tr>
<tr><td align="left">City</a>:</td><td><input size="18"
type="text" id="city" value="Mississuaga" ></td></tr>
<tr><td align="left">Postal Code</a>:</td><td><input size="18"
type="text" id="Postal_Code" value="L5B0B9" ></td></tr>
<tr><td align="left">Province</a>:</td><td><input size="18"
type="text" id="province" value="Ontario" disabled ></td></tr>
<tr><td align="left">Country</a>:</td><td><input size="18"
type="text" id="country" value="Canada" disabled ></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :300px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>3. Define Report details</b></legend>
<table>
<tr><td align="left">Site Name</a>:</td><td><input size="22"
type="text" id="Site_Name" value="Contaminated site 01"
></td></tr>
<tr><td align="left">Reference Number</a>:</td><td><input
size="22" type="text" id="reference_number" value="Order001"
></td></tr>
<tr><td align="left">Your Name</a>:</td><td><input size="22"
type="text" id="Your_name" value="Adel Hallak" ></td></tr>
<tr><td align="left">Email Address</a>:</td><td><input
size="22" type="text" id="email_address"
value="adel.elhallak@gmail.com" ></td></tr>
</table>
</fieldset>
<fieldset style="float:left;width :150px;padding : 10px;margin: 1em
0.7em 0.3em;display : inline-block;height: 210px;">
<legend><b>4. Submit Request</b></legend>
<input align="center" type="button" value=" Submit your
request " id="Send_coordinates" width="148" height="148"
onclick="Submit_For_Proccessing()">
<textarea rows="4" cols="50" style="width:145px;
height:150px;font-size:8pt;" id="Request_Details"
name="Request_Details" value="Initial"></textarea>
</fieldset>
</form>
"""
form = cgi.FieldStorage()
Request_Details = form.getvalue("Request_Details", "(no Request_Details)")
print """
<p>%s</p>
<form method="post" action="Thankyou.py">
<p><input type="text" name="Request_Details"/></p>
</form>
</body>
</html>
""" % cgi.escape(Request_Details)

Windows Service starting/stopping another service

Windows Service starting/stopping another service

I have a slight problem with a service I have written in C++. The service
itself functions correctly and is running under the SYSTEM account. During
one point of execution, I have to start or stop another service. This,
however, is not working. The call to OpenService() returns error code 5,
which is "Access denied".
To give a little bit more detail: I have to start an own time provider
service that tries to open port 123 on a network adapter, and this port is
often already opened by the win32time Service from Windows. What I try to
do is to give the user the option to automatically stop this service when
my service is starting, and starting it again when it stops.
This service can only be accessed with elevated user privileges on systems
that are UAC-capable, I know that, but I always thought that the SYSTEM
account would be able to perform this action by default, but apparently I
am wrong.
Is it possible somehow to elevate my service (maybe by adapting the
privilege level in the manifest to 'requireAdministrator' or something
similar)? I haven't tried this yet to be honest, since I fear that the UAC
prompt will be stuck in session 0 or things the like. Or is there another
way to grant my service running under SYSTEM the privileges to control
another service's status?
Any suggestions are very much appreciates, thanks!
EDIT
Okay, here's the code, and I feel a little bit stupid now... I have
totally forgotten to check the API thoroughly, because I thought that the
last parameter of OpenService() can be zero to request all privileges by
default, but I have to pass SC_MANAGER_ALL_ACCESS. Sorry for bothering
everybody. I will try this tomorrow and close this question when I have
the results.
SC_HANDLE scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE) ;
if(nullptr == scm) {
/* Handle and return */
}
// I am missing SC_MANAGER_ALL_ACCESS here probably
SC_HANDLE svc = OpenService(scm, _T("w32time"), 0);
int lastError = GetLastError();
if(ERROR_SERVICE_DOES_NOT_EXIST == lastError) {
/* Handle and return */
}
if(start) {
if(0 != StartService(svc, 0, nullptr)) {
int lastError = GetLastError();
if(ERROR_SERVICE_ALREADY_RUNNING != lastError) {
/* Handle */
}
}
} else {
SERVICE_STATUS status;
QueryServiceStatus(svc, &status);
if(SERVICE_STOPPED != status.dwCurrentState) {
if(ControlService(svc, SERVICE_CONTROL_STOP, &status)) {
do {
QueryServiceStatus(svc, &status);
} while(SERVICE_STOPPED != status.dwCurrentState);
} else {
/* Handle */
}
}
}
CloseHandle(svc);
CloseHandle(scm);

Quick way to insert for loop in Eclipse

Quick way to insert for loop in Eclipse

Is there a (quick) way to automatically insert the java for loop e.g. for
(int i=0;i< someInt;i++){ ? It would be very convenient (as rest of code
generation functionality).

No output being displayed when passing values through Get

No output being displayed when passing values through Get

I have this piece of code, which should retrieve the value from the
database and then print in on the page, I have created links that will
pass value to the page and then I retrieve the value from GET and the
result should be printed, but is it happening? NO!, I am not getting any
errors on the page, rather I am getting nothing on the result page cos its
a blank page.
function retrieve($resul)
{
//$resul=mysql_query($qry);
if($resul)
{
echo '<table class="pos" cellspacing="10">' ;
echo '<tr>';
$x = 0;
while($result=@mysql_fetch_array($resul,MYSQL_ASSOC))
{
if($x<2)
{
echo '<td>' ;
echo '<div class="img-wrap"> <div style="300 px; font-size:15px;
text-align:center; background-color= "ff0066;">' ;
echo "<img src='{$result['image']}' alt='alternate text' width='220px'
height='200px' style='padding-bottom:1.0em;' >" ;
echo "<b>";
echo $result['company'] . " " . $result['model'] ;
echo "</b>" ;
echo "<br>";
echo $result['cpu'] ."/" . $result['ram'] ."/" . $result['HDD'];
echo "<br>";
echo "<b>" . $result['price'] ."<b>" ;
echo '</div>' ;
echo '</td>' ;
$x++;
}
else
{
echo '<td>' ;
echo '<div class="img-wrap"> <div style="300 px; font-size:15px;
text-align:center; background-color= "ff0066;">' ;
echo "<img src='{$result['image']}' alt='alternate text' width='220px'
height='200px' style='padding-bottom:1.0em;' >" ;
echo "<b>";
echo $result['company'] . " " . $result['model'] ;
echo "</b>" ;
echo "<br>";
echo $result['cpu'] ."/" . $result['ram'] ."/" . $result['HDD'];
echo "<br>";
echo "<b>" . $result['price'] ."<b>" ;
echo '</div>' ;
echo '</td>' ;
echo '</tr>' ;
echo '<tr>' ;
$x=0 ;
}
}
echo '</table>' ;
}
}
if ( isset($_GET['company'] ))
{
$company= $_GET['company'] ;
}
if(isset($_GET['range']))
{
$range= $_GET['range'] ;
}
if(isset($_GET['cpu']))
{
$cpu= $_GET['cpu'] ;
}
if(isset($_GET['lifestyle']))
{
$lifestyle= $_GET['lifestyle'] ;
}
if(isset($_GET['display']))
{
$display= $_GET['display'] ;
}
if(isset($_GET['ram']))
{
$ram= $_GET['ram'] ;
}
if(isset($_GET['HDD']))
{
$HDD= $_GET['HDD'] ;
}
if(!empty($company))
{
$qry = "SELECT * FROM LAPTOP WHERE company='$company' " ;
$resul=mysql_query($qry);
retrieve($resul) ;
}
if(!empty($cpu))
{
$qry= "SELECT * FROM LAPTOP WHERE cpu='$cpu' " ;
$resul=mysql_query($qry);
retrieve($resul) ;
}
if(!empty($lifestyle))
{
$qry= "SELECY * FROM LAPTOP WHERE lifestyle='$lifestyle' " ;
$resul=mysql_query($qry);
retrieve($resul) ;
}
if(!empty($display))
{
$qry= "SELECT * FROM LAPTOP WHERE display='$display'" ;
$resul=mysql_query($qry);
retrieve($resul) ;
}
if(!empty($ram))
{
$qry= "SELECT * FROM LAPTOP WHERE ram='$ram' " ;
$resul=mysql_query($qry);
retrieve($resul) ;
}
if(!empty($HDD))
{
$qry= "SELECT * FROM LAPTOP WHERE HDD='$HDD' " ;
$resul=mysql_query($qry);
retrieve($resul) ;
}
?>
The links on the previous page are like this
I have checked my table that if I am committing any errors in the
uppercase and lowercase thing but its perfectly fine cos I have stored all
the information in the table after converting it into lowercase. Has it
got something to do with the function retrieve()? PS: I will change the
functions to mysqli() once this script works Thanks in advance

Table parameters or xml data type

Table parameters or xml data type

I have a store procedure with 50 parameters and may be increased in future.
I know I can pass less parameter if I use a string xml or table parameter.
And I'm confusing .Should I use xml or table parameters ?
Anybody , Please help me choose the best solution. Thank you.

Wednesday, 11 September 2013

selectOneMenu not populating another selectOneMenu using ajax listener

selectOneMenu not populating another selectOneMenu using ajax listener

I am using two selectOneMenu. Selection of first one should populates the
second one by providing the selected value as a parameter. I have gone
through a lot of online stuff but still not find a way to resolve it. The
listener method is getting called on dropdown value change. Someone please
help me out.
<p:selectOneMenu value="#{myBean.mGroup}" id="mGroup" style="width:130px;" >
<f:selectItem itemLabel="Environment" itemValue="E"></f:selectItem>
<f:selectItem itemLabel="Health" itemValue="H"></f:selectItem>
<f:selectItem itemLabel="Physical" itemValue="P"></f:selectItem>
<p:ajax update="mClass" listener="#{myBean.mGroupChangedListener}" />
</p:selectOneMenu>
<p:selectOneMenu id="mClass" style="width: 130px;" value="#{myBean.mClass}">
<!-- <f:selectItem itemLabel="Temp1" itemValue="Temp1" /> if i
remove comment from this line, it works -->
<f:selectItems value="#{smyBean.mClassList}" var="clas"
itemLabel="#{clas.mClassDesc}" itemValue="#{clas.mClassId}" />
</p:selectOneMenu>
// listener method
public void mGroupChangedListener(AjaxBehaviorEvent event) {
List<MClass> mClassList =
service.getMClass(event.getComponent().getAttributes().get("value").toString());
myBean.setMClassList(mClassList);
}