Monday, 30 September 2013

how do I find all Elements of a Group?

how do I find all Elements of a Group?

I am given a Group $\mathbb{Z_{11}^*}$. a multiplicative group.
How do i find all elements of this Group?

For $n$ at least 5, the index of a subgroup of $Alt(n)$ is at least $n$.

For $n$ at least 5, the index of a subgroup of $Alt(n)$ is at least $n$.

Can someone can help me get started with this problems?
Prove that $A_n$ does not have a proper subgroup of index less than $n$
for all $n \geq 5$.

ListFragment shows empty text when the list is not empty

ListFragment shows empty text when the list is not empty

I am trying to make a LoaderManager list backwards compatible to Android
2.1. The list is loading fine but the @id/android:empty message shows even
when there are items clearly visible in the list.
I have looked at a number of solutions on StackOverflow that use
setEmptyView() and setEmptyText() but couldn't get them to work.
Here is the code for the ListFragment. I have been combining code from
various http://www.vogella.com/ tutorials.
package com.example.contentprov;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.contentprov.data.MyTodoContentProvider;
import com.example.contentprov.data.TodoTable;
/*
* TodosOverviewActivity displays the existing todo items
* in a list
*
* You can create new ones via the ActionBar entry "Insert"
* You can delete existing ones via a long press on the item
*/
public class TodoOverviewFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
private SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.todo_list);
fillData();
}
// Opens the second activity if an entry is clicked
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(getActivity(), TodoDetailActivity.class);
Uri todoUri = Uri.parse(MyTodoContentProvider.CONTENT_URI + "/" +
id);
i.putExtra(MyTodoContentProvider.CONTENT_ITEM_TYPE, todoUri);
startActivity(i);
}
private void fillData() {
// Fields from the database (projection)
// Must include the _id column for the adapter to work
String[] from = new String[] { TodoTable.COLUMN_SUMMARY };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
getActivity().getSupportLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.todo_row, null, from,
to, 0);
setListAdapter(adapter);
}
// Creates a new loader after the initLoader () call
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { TodoTable.COLUMN_ID,
TodoTable.COLUMN_SUMMARY };
CursorLoader cursorLoader = new CursorLoader(getActivity(),
MyTodoContentProvider.CONTENT_URI, projection, null, null,
null);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// data is not available anymore, delete reference
adapter.swapCursor(null);
}
@Override
public void onItemClick(AdapterView<?> l, View v, int position, long
id) {
Intent i = new Intent(getActivity(), TodoDetailActivity.class);
Uri todoUri = Uri.parse(MyTodoContentProvider.CONTENT_URI + "/" +
id);
i.putExtra(MyTodoContentProvider.CONTENT_ITEM_TYPE, todoUri);
startActivity(i);
}
}
Here is the XML file for the list:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_todos" />
</LinearLayout>

How to display rows that when added together equal zero

How to display rows that when added together equal zero

Been searching for a few weeks for a solution to this but have come up blank.
I have table of data similar to this:
client_ref supplier_key client_amount
1111 GBP 10
1111 GBP -10
1111 EUR 50
2222 CHF -22.5
2222 CHF -20
3333 EUR -27
3333 EUR -52
3333 EUR 79
I need to extract all items where the client_ref and supplier_key match
and the total of the client_amount equals zero. The output would look like
this:
client_ref supplier_key client_amount
1111 GBP 10
1111 GBP -10
3333 EUR -27
3333 EUR -52
3333 EUR 79
I have written the following that returns the totals but I need any help
you could provide to change this to show the rows that make up the totals
rather than just the overall results.
SELECT tbis.client_ref ,tbis.supplier_key ,sum(tbis.client_amount)
FROM [XXXX].[dbo].[transaction] tbis
WHERE tbis.tbis.client_amount !=0
GROUP BY tbis.client_ref, tbis.supplier_key
HAVING sum(tbis.client_amount) =0
ORDER BY sum(tbis.client_amount)
Hope this makes sense and my first post is OK. Please feel free to
critique my post.

Sunday, 29 September 2013

Row numbering selection auto-fill till the end

Row numbering selection auto-fill till the end

I have a table with thousands of lines. I want to number rows by adding 1
2 3 next to first rows, then to select these and drag till end to make a
fill with increasing numbers.
How to autofill till last row without dragging with a mouse for several
minutes?

python fibonacci function that take a list of integers & returns True return false otherwise

python fibonacci function that take a list of integers & returns True
return false otherwise

how to write a python function that takes a list of integers and returns
True if they are consecutive numbers within the Fibonacci sequence. False
is returned otherwise

php print pdf using php_printer.dll on windows serverside

php print pdf using php_printer.dll on windows serverside

my job is to print pdf-files serverside on a windows-machine with xampp
installed. Now I´ve installed php_printer.dll and copied/written a
test-script from here:
$printer = "\\\\SERVER\\PRINTER";
$file = "test.pdf";
if ($ph = printer_open($printer)) {
// Get file contents
$fh = fopen($file, "rb");
$content = fread($fh, filesize($file));
fclose($fh);
printer_start_doc($ph, "TESTPAGE");
printer_start_page($ph);
// Set print mode to RAW and send PDF to printer
printer_set_option($ph, PRINTER_MODE, "RAW");
printer_write($ph, $content);
printer_close($ph);
echo "-> Job was sent to ".$printer;
} else {
echo "-> Couldn't connect... ".$printer;
}
But it does not work with pdf-files; text-only is okay. If I print
pdf-files, there are only incorrect chars on the paper :( What can I do to
print serverside pdf´s in php? Any tips?
Regards, rumble

Saturday, 28 September 2013

error in mapping form to case class in play 2 for scala

error in mapping form to case class in play 2 for scala

val registrationForm: Form[Registration]=Form(
mapping(
"fname"->text(minLength=2),
"lname"->text(minLength=1),
"userEmail"->text(minLength=5),
"userPassword" -> tuple(
"main" -> text(minLength = 6),
"confirm" -> text
).verifying(
// Add an additional constraint: both passwords must match
"Passwords don't match", userPassword => userPassword._1 ==
userPassword._2
),
"gender"->number,
"year"->number,
"month"->number,
"day"->number
)
{
// Binding: Create a User from the mapping result (ignore the second
password and the
accept field)
(fname, lname, userEmail, userPassword, gender, year, month, day, _) =>
Registration(fname,lname,userEmail,userPassword._1, gender,
year,month,day)//error here
}
{
// Unbinding: Create the mapping values from an existing User value
user => Some(user.fname, user.lname, user.userEmail,(user.userPassword, ""),
user.gender, user.year, user.month, user.day, false)
}
)//end registrationForm
My case class is -
case class Registration(fname:String, lname:String, userEmail:String,
userPassword:String, gender:Int, year:Int,month:Int, day:Int )
The above code is giving a error- wrong number of parameters; expected =
8. I have giving comment to the line in which error occurs

ObjectAnimator not fading background colors in a thread

ObjectAnimator not fading background colors in a thread

I'm changing the background color of the view every 2 seconds to a newly
generated color and trying to get color1 and color2 to fade into each
other. The ObjectAnimator isn't working quite right.
My code as follows:
public class DynamicColors extends Activity {
public int color1, color2, red1, red2, blue1, blue2, green1, green2;
ObjectAnimator anim;
View v;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dynamiccolors);
v = findViewById(R.id.view);
// Generate color1 before starting the thread
red1 = (int)(Math.random() * 128 + 127);
green1 = (int)(Math.random() * 128 + 127);
blue1 = (int)(Math.random() * 128 + 127);
color1 = 0xff << 24 | (red1 << 16) |
(green1 << 8) | blue1;
v.setBackgroundColor(color1);
// We haven't initialized color2 yet. Will set this later
anim = ObjectAnimator.ofInt(v, "backgroundColor", color1);
anim.setEvaluator(new ArgbEvaluator());
anim.setDuration(2000);
new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
DynamicColors.this.runOnUiThread(new Runnable() {
public void run() {
//generate color 2
red2 = (int)(Math.random() * 128 + 127);
green2 = (int)(Math.random() * 128 + 127);
blue2 = (int)(Math.random() * 128 + 127);
color2 = 0xff << 24 | (red2 << 16) |
(green2 << 8) | blue2;
// Update the color values
anim.setIntValues(color1, color2);
anim.start();
// Order the colors
color1 = color2;
}
});
}
}
}.start();
}
}
Any thoughts on what could be going wrong with the ObjectAnimator? I think
the thread is really confusing me on this one.

Can @fontface be used within a tag? (for email signature reliability)

Can @fontface be used within a tag? (for email signature reliability)

I am working on getting an email signature to take a custom look. It irks
me that that I am compelled to go this route by the inconsistent rendering
of email clients, but is there a way to make @fontface apply fonts to text
by declaring the font style within a tag itself? Doing it the standards
way (either with the styling in a header or within the HTML body) does not
get the font to render on mobile email clients, though it does on some
desktop apps.
I tried styling within the tag. (sample below) In theory this could work,
but does not come out nicely on a browser. Should I let this one go, or
are there better ways I am missing?
And just for clarity, this @fontface syntax does work for me when put in a
correctly done style tag. Below is my attempt at defining it within the
tag which yields weird results. Non-font styling comes through nicely, but
the font gets put in as Times, not Tiemann. (Look at the "C" and the "Í"
to tell them apart.)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-16be-with-bom" />
<title>Untitled</title>
<meta name="generator" content="BBEdit 10.5" />
</head>
<body>
<span style="@font-face
font-family:'Tiemann';
src:
url('https://dl.dropboxusercontent.com/u/35370696/font_embed/tiemannlightwebfont.eot');
src:
url('https://dl.dropboxusercontent.com/u/35370696/font_embed/tiemannlightwebfont.eot?#iefix')
format('embedded-opentype'),
url('https://dl.dropboxusercontent.com/u/35370696/font_embed/tiemannlightwebfont.woff')
format('woff'),
url('https://dl.dropboxusercontent.com/u/35370696/font_embed/Tiemann_Light.ttf')
format('truetype'),
url('https://dl.dropboxusercontent.com/u/35370696/font_embed/tiemannlightwebfont.svg#Tiemann')
format('svg');
font-size:22pt;
color:#6D6D6D;
float:left;
">
DIACRÍTICA
</span>
</body>
</html>

How to reference the DOM element knockout creates when foreach binding to an observableArray

How to reference the DOM element knockout creates when foreach binding to
an observableArray

When you click on one of the four buttons in this fiddle
http://jsfiddle.net/Fe8mT/
[Spades] [Hearts] [Diamonds] [Clubs]
knockout will add a new LI item to the UL corresponding to the "suit" of
the button. I would like to know how to reference the newly created LI
element in the self.addCard handler.
self.addCard = function (data,event) {
var card = event.currentTarget.id; // the button's id (S,
H, D, C)
self.hand.push(card);
};
I want to add a css class to the LI knockout creates when an item is
pushed onto the observableArray. If the [Spades] button was clicked,
adding a "spade" to the observableArray, I'll addClass("spades") to the
LI; if the [Hearts] button was clicked, I'll addClass("hearts").

Friday, 27 September 2013

Bootstrap css file is added automatically in production but no locally as it should be in Rails App

Bootstrap css file is added automatically in production but no locally as
it should be in Rails App

Okay so this is a pretty weird problem, I have a Rails app that uses the
bootstrap grid and no other bootstrap css file. Locally everything renders
just fine, but in production mode, (I'm using Heroku) it seems as though
the bootstrap css stylesheet is being added, and I have no idea where it's
coming from or why it's doing this. It wasn't doing this before and I'm
pretty sure I haven't added anything that would automatically include the
bootstrap css styles. I hope I'm missing something obvious here, but I
just can't pin-point the problem and it has never happend before,
hopefully you guys can tell me what I'm doing wrong. I'll post my gem file
as I think it must have something to do with that:
source 'https://rubygems.org'
gem 'rails', '3.2.12'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.0.1'
gem 'jquery-rails', '2.0.2'
gem 'activeadmin'
gem 'rename'
gem 'obscenity'
gem 'omniauth'
gem 'omniauth-facebook'
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.11.0'
gem 'guard-rspec', '1.2.1'
gem 'guard-spork', '1.2.0'
gem 'spork', '0.9.2'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '3.2.5'
gem 'coffee-rails', '3.2.2'
gem 'uglifier', '1.2.3'
end
group :test do
gem 'capybara', '1.1.2'
gem 'factory_girl_rails', '4.1.0'
gem 'cucumber-rails', '1.2.1', :require => false
gem 'database_cleaner', '0.7.0'
# gem 'launchy', '2.1.0'
# gem 'rb-fsevent', '0.9.1', :require => false
# gem 'growl', '1.0.3'
end
group :production do
gem 'pg', '0.12.2'
end

How to print elements and values from two related associative arrays in PHP

How to print elements and values from two related associative arrays in PHP

I have two associative arrays. $dpt_total is a list of departments, and
the total for those departments. $cl_subtotal is a multidimensional array
of department, class and subtotal.
I want to display the department and total, then the classes associated
with that department and the subtotal for the class. For example:
vdump($dpt_total);
array(2) {
'None' ¨ float 132.88
'instore bakery' ¨ float 786.24
}
Sizes: 2
vdump($cl_subtotal);
array(2) {
'None' ¨ array(1) {
'None' ¨ float 132.88
}
'instore bakery' ¨ array(10) {
'pies' ¨ float 70.94
'cakes' ¨ float 146.71
'miscellaneous' ¨ float 25.57
'cookies' ¨ float 52.38
'brownies' ¨ float 33.96
'rolls' ¨ float 143.02
'danish' ¨ float 90.42
'bagels & pretzels' ¨ float 85.68
'breads' ¨ float 55.73
'dessert case' ¨ float 81.83
}
}
Should display:
Department Class Total
-------------------------------
None 132.88
None 132.88
Instore Bakery 786.24
pies 70.94
cakes 146.71
misc 25.57
cookies 52.38
(and so on)

Returning a pointer to an array C++

Returning a pointer to an array C++

I have a function that needs to return a pointer to an array:
int * count()
{
static int myInt[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
return &myInt[10];
}
inside my main function I want to display one of the ints from that array,
like here at index 3
int main(int argc, const char * argv[])
{
int myInt2[10] = *count();
std::cout << myInt2[3] << "\n\n";
return 0;
}
this however gives me the error: "Array initializer must be an initializer
list"
how do I create an array within my main function that uses the pointer to
get the same elements as the array at the pointer?

Excel VB Button

Excel VB Button

In the "ActiveSheet.Buttons" I get the size of the buttons but not the
text that I want, it only shows "Button 1" (whatever number shows up). Can
anyone tell me how to get a custom text in the button?
Sub AT()
Sheets("134B").Select
Sheets("New Tab").Visible = True
Sheets("New Tab").Select
ActiveSheet.Buttons.Add(0.75, 0.75, 36, 28.5).Select
ActiveSheet.Buttons.Add(37.5, 0.75, 17.25, 28.5).Select
ActiveSheet.Buttons.Add(55.5, 0.75, 17.25, 28.5).Select
ActiveSheet.Buttons.Add(73.5, 0.75, 36, 28.5).Select
Sheets("New Tab").Copy Before:=Sheets(3)
Sheets("New Tab").Select
ActiveWindow.SelectedSheets.Visible = False
Sheets("New Tab (2)").Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets("DB").Select
Range("J23").Select
End Sub

How to use an array of objects properly

How to use an array of objects properly

I'm trying to assign the values of a split string in to a global array of
objects. The string is called result and looks something like:
"John.Doe.100.New-Mike.Jordan.200.Veteran-".
Splitting the string works fine, but I'm having trouble assigning the
corresponding values into the object array. which doesn't work at all. Any
idea where the problems are?
var UserData[]=new Object();
function SplitDatabase(result){
var RawUsers = result.split('-');
for (var i = 0; i < (RawUsers.length-1); i++) {
var tempUserData=RawUsers[i].split('.');
for (var x=0; x < (tempUserData.length);x++){
switch (x)
{
case 0:
UserData[i].firstname=tempUserData[x];
break;
case 1:
UserData[i].lastname=tempUserData[x];
break;
case 2:
UserData[i].points=tempUserData[x];
break;
case 3:
UserData[i].rank=tempUserData[x];
break;
}
}
}
}

Install Help for Vigra on Windows 7

Install Help for Vigra on Windows 7

Can some one please explain how to install Vigra (1.9.0) on windows 7?
I have read the directions on the vigra website but was unable to
understand clearly.
Thanks, Avishek

Thursday, 26 September 2013

How to limit texture size for whale project

How to limit texture size for whale project

I am using Unity3d for developing games.
In project exeist many textures.
How to limit texture size for whole prject?

Wednesday, 25 September 2013

I have WPF window that i want to Print on paper size **4inch by 6inch**

I have WPF window that i want to Print on paper size **4inch by 6inch**

I have WPF window that i want to Print on paper size 4inch by 6inch.
i dont understand where to set this size?? i am using window size to print
but window size its not working. my printer is not fixed paper size.
this is my print code:
private void _print()
{
PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
//printDlg.ShowDialog();
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities =
printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth
/ this.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
this.ActualHeight);
//Transform the Visual to scale
this.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
Size sz = new Size(this.ActualWidth, this.ActualHeight);
//update the layout of the visual to the printer page size.
this.Measure(sz);
this.Arrange(new Rect(new
Point(capabilities.PageImageableArea.OriginWidth,
capabilities.PageImageableArea.OriginHeight), sz));
//now print the visual to printer to fit on the one page.
printDlg.PrintVisual(this, "Print Page");
}

Thursday, 19 September 2013

looping through scan and replacing matches individually

looping through scan and replacing matches individually

I would like to loop through regex matches and replace each match
individually in the loop.
For example:
content.scan(/myregex/).each do |m|
m = 'new str'
end
How could I do that?
The reason why I want to do that is because each match will be replaced
with a different output from a function.
Thanks for help

What is the SQL to get the first val in a column in a table?

What is the SQL to get the first val in a column in a table?

I want to refactor this code, because it seems wasteful and wacky and weird:
public string getVersion()
{
try
{
string dynSQL = "SELECT * FROM invHeader";
DataSet workSites = dbconn.getDataSet(dynSQL);
//Go thru dataset and display the working files
//Only need one, although we'll be duplicating the version
//per each site as a check value during upgrades
//return workSites.Tables[0].Rows
foreach (DataRow row in workSites.Tables[0].Rows)
{
sVersion = row["ID"].ToString();
break;
}
}
catch (Exception ex)
{
Duckbill.ExceptionHandler(ex, "InvHeader.getVersion");
}
return sVersion;
} // getVersion
I was thinking I could change it to something like this:
public string getVersion()
{
try
{
string dynSQL = "SELECT FIRST ID FROM invHeader"; // I also tried
"SELECT 1 ID FROM invHeader"
DataSet workSites = dbconn.getDataSet(dynSQL);
return workSites.Tables[0].Rows[0];
}
catch (Exception ex)
{
Platypus.ExceptionHandler(ex, "InvHeader.getVersion");
}
} // getVersion
...but neither query returned what I want (the value of ID in the first
row). So what is the SQL to do that.
BTW, I know this should be some sort of scalar call, but so many funky
Rube Goldbergesque things happen in these homegrown, self-rolled methods
that rely on each other, I'm afraid to touch that; this little cleanup
should be doable without quaking in my booties, though.
UPDATE
I guess I jumped the gun awarding the answer - "SELECT TOP 1 ID FROM
invHeader" in SQL Server CE Query Analyzer results in:
FAILED: SELECT TOP 1 ID FROM invHeader
Error: x800...._E_ERRORSINCOMMAND
Native Error: (25501)
Description: There was an error parsing the query. [Token line number,
Token line offset, Token in error,,]
Interface defining error: IID_ICommand
Paaram. 0:1
Param. 1: 8
Param. 2:0
Param. 3: TOP
Param. 4:
Param. 5:
This seems cryptic as all get-out, but one thing I do grok is that SQL
Server CE Query Analyzer is "not amused."

New IsWiX Setup Project fails to build - undefined preprocessor variable

New IsWiX Setup Project fails to build - undefined preprocessor variable

I am attempting to use WiX Toolset to create a deployment project. I am
using Visual Studio.NET 2010 SP1, WiX 3.7, and IsWix 2.0.13013.4. I am
using .NET framework 4.0.
I created the directory structure provided below.
C:\Projects\ExcelXLL\Installer C:\Projects\ExcelXLL\Installer\Deploy
I added an IsWix Setup Project under the Installer directory in the path
C:\Projects\ExcelXLL\Installer\ExcelXLL64Deploy.
If I attempt to compile the setup project, I get the exception: Error 1
Undefined preprocessor variable '$(var.ExcelXLL64DeployMM.TargetPath)'.
C:\Projects\ExcelXLL\Installer\ExcelXLL64Deploy\Code\Features.wxs 16 1
ExcelXLL64Deploy
What am I doing wrong or is there an issue with either IsWix or Wix?

IE8 appendChild "Unexpected call to method or property access"

IE8 appendChild "Unexpected call to method or property access"

I really need some help with this issue I'm having. Only seem to have on
IE8. IE7 works fine which is weird. I'm using IE9 (F2) development tool
IE8 emulator which seem to work good. I also checked on VMware native IE8
and getting the same results. Anyway is that a issue with appendChild in
IE8? How can I solve this issue and is there a jquery or better way of
coding this section.
IE report this as the issue **
s.appendChild(document.createTextNode(jcode)); ** "Unexpeced call to
method or property access"
for (var i=0; i<showContain.length+1; i++)
{
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
var jcode = "$('#showdiv" + i +
"').mouseover(function(){$('.showcaseoff').hide(); $('#showcase" + i +
"').show()});";
s.appendChild(document.createTextNode(jcode));
document.body.appendChild(s);
}
Thanks...

Ruby regex for html parser

Ruby regex for html parser

I have such html part:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwULLTIwMjYxMTgwOTAPFgIeBGd1aWQFIDI1NmYyOTdkZWZhNjQyODhhYTVmOWI4MGE5MzRjNjlhFgJmD2QWAgIDDxYCHgxhdXRvY29tcGxldGUFA29mZhYCAgEPZBYGZg9kFgJmD2QWAgIFDw8WAh4EVGV4dAUO0JLRi9C50LTQuNGC0LVkZAICD2QWAgICD2QWAgIBDxAPFgYeDURhdGFUZXh0RmllbGQFBU5hendhHg5EYXRhVmFsdWVGaWVsZAUQSURXZXJzamVKZXp5a293ZR4LXyFEYXRhQm91bmRnZBAVAwZQb2xza2EHRW5nbGlzaA7QoNGD0YHRgdC60LDRjxUDATEBMgIxNxQrAwNnZ2cWAQICZAIED2QWAmYPZBYCAgEPZBYCZg9kFgICAQ9kFgICAw9kFgQCAg8PFgQeJk5vQm90X1Jlc3BvbnNlVGltZUtleV9jdGwwMCRjcCROb0JvdElEBnWRyyBNg9BIHiROb0JvdF9TZXNzaW9uS2V5S2V5X2N0bDAwJGNwJE5vQm90SUQFNE5vQm90X1Nlc3Npb25LZXlfY3RsMDAkY3AkTm9Cb3RJRF82MzUxNTE5MTQ3MjUxNzIzNDFkFgICAQ8WAh4PQ2hhbGxlbmdlU2NyaXB0BVl2YXIgZSA9IGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdjdGwwMF9jcF9Ob0JvdElEX3BjbmInKTsgZS5vZmZzZXRXaWR0aCArIGUub2Zmc2V0SGVpZ2h0O2QCAw9kFgICAQ9kFgJmD2QWBAIDD2QWBGYPZBYCAgEPZBYIAgEPDxYGHgpQbGFpblZhbHVlBQQ0RDVoHg5FbmNyeXB0ZWRWYWx1ZQUgMjQxZjdmZGQ3ODIxNGJhYzgyOGNhNzU3ZDY4NWI3Y2IeB1Zpc2libGVoZGQCAw8PFgIfC2hkZAIFDw8WAh8LaGRkAgcPFgIfC2dkAgMPZBY
CZg9kFgICAQ8PFgIfAgUK0JTQsNC70LXQtWRkAgUPZBYKZg9kFgRmD2QWAgIBDw8WAh8CBRPQktC40LQg0YPRgdC70YPQs9C4ZGQCAQ9kFgICAQ8QZGQWAGQCAQ9kFgRmD2QWAgIBDw8WAh8CBR7QnNC10YHRgtC+0L3QsNGF0L7QttC00LXQvdC40LVkZAIBD2QWAgIBDxBkZBYAZAICD2QWBGYPZBYCAgEPDxYCHwIFCNCh0YDQvtC6ZGQCAQ9kFgICAQ8QDxYCHgxBdXRvUG9zdEJhY2toFgIeCG9uQ2hhbmdlBR5jYkR6aWVuR29kemluYV9vbkNoYW5nZSh0aGlzKTtkFgBkAgMPZBYEZg9kFgICAQ8PFgIfAgUG0YfQsNGBZGQCAQ9kFgICAQ8QZGQWAGQCBQ9kFgJmD2QWBAIBDw8WAh8CBSTQl9Cw0YDQtdCz0LjRgdGC0YDQuNGA0L7QstCw0YLRjNGB0Y9kZAIDDw8WAh8CBTbQntGC0YHRg9GC0YHRgtCy0LjQtSDRgdCy0L7QsdC+0LTQvdGL0LUg0LTQsNGC0Ysg0LTQviBkZBgBBR1jdGwwMCRjcCRldmVudE9yZGVyVmFsaWRhdGlvbg8PZDKpAwABAAAA/////wEAAAAAAAAADAIAAABGTVNaX1dXV19LTElFTlQsIFZlcnNpb249Mi4xMi4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUBAAAATU1TWl9XV1dfS0xJRU5ULktvbnRyb2xraS5FdmVudE9yZGVyVmFsaWRhdGlvbitFdmVudE9yZGVyVmFsaWRhdGlvbkNvbnRyb2xEYXRhBAAAAAtFdmVudE51bWJlchNFdmVudEV4cGlyYXRpb25UaW1lDVNlY3VyaXR5VG9rZW4MTGljem5pa1Rva2VuAwMBAAxTeXN0ZW0uSW50MzJxU3lzdGVtLk51bGxh
YmxlYDFbW1N5c3RlbS5EYXRlVGltZSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0IAgAAAAgIAAAAAAoGAwAAACBmNjZlZTgwODEwZWM0ZjcwYThhZjY2ZDcyNDlmNWFjZgEAAAALZGrI7rw4FqPtCexAP1+dCQ7Qps1t">
and i try to use such regex:
VIEWSTATE = (/<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="(.*?)" \/>/.match body_text)[1]
but it seems, that it is working strange, and fetching not all value, but
just part of it. In that case, which regex i must use? (note, that part
VIEWSTATE" id="_VIEWSTATE" value= is required in regex).
Will be good, if you tell me how)
PLEASE! don't write me with nokogiri!

API protocol for internal servers

API protocol for internal servers

I have two Rails servers, one for web server, and the other for backend
processes.
Two servers access to the same PostgreSQL database. I need to notify
backend server to do analytics when a new user sign up with web server,
then notify web server the resulted analytics once it's done. I think the
best way to handle this is via an API to backend server.
Since my backend will only be accessed my my web server, what would be the
simplest solution to secure access? Is DoorKeeper an overkill?

JavaScript for applying effect to the images effect

JavaScript for applying effect to the images effect

script in java for applying effect to the images effect like sketch,
Effects.Quill., many more just like the effect applied in photofunia
site.**
effect like vintage,old photo,pop art,grey scale,downlight,blue
wash,sharpen,inverted, blur and many more i want the code in javascript by
which i can make a website of photo editing..
thanks in advance

Wednesday, 18 September 2013

Organizing rails controllers within namespaces

Organizing rails controllers within namespaces

I have a fairly simple question about the code organization of rails
controllers:
If we have an app store platform (i.e. Google Play) which consists of
Developers (They create/upload the apps), Admins (Review and approve the
apps) and Users (Who consume the apps via the store).
The developers do everything through the developers platform, so it would
make sense to have a developers namespace to group related items. The same
logic would seem to make sense for the admin, give them an admin panel
under an admin namespace.
Now here's the question - I have two namespaces, Admin and Developer - if,
a developer can change an app's state from :draft to :pending (for review)
and the admin can change the state from pending to :approved/:rejected,
where is the recommended place to store apps_controller.rb?
There seems to be three ways to handle this and I'm not quite sure which
is the most 'correct', either for practical reasons or conventional
reasons. The three options I can think of are:
1) In both the Admin & Developer namespace (and populate the store from
developer::apps)? 2) Only in the Developers namespace 3) The
apps_controller should not live in either namespace.
Thanks in advance!

preinstalled /bin/zsh executable missing

preinstalled /bin/zsh executable missing

I got my zsh messed up so I deinstalled it. Now in /bin/ on my HD the
preinstalled zsh executable is missing. How can i resolve this problem,
since it's a preinstalled file I somehow got deleted?

Instantiate a modelForms MultiSelectCheckBox widget

Instantiate a modelForms MultiSelectCheckBox widget

I am using ModelForms with a ModelMultipleChoiceField widget. I have 2
questions:
My checkbox widget for Treatment Options from SelectOptionForStateForm
renders existing selections from the stateoption table in my database. How
does it know to look in that table for existing records? In my views.py I
am only passing the disease and state objects which do not look at the
stateoption table.
How do I instantiate my SelectOutcomeForOptionForm so that my Treatment
Outcomes checkbox is also pre-selected from the stateoptionoutcome table
in my database?
forms.py
class SelectOptionForStateForm(forms.ModelForm):
class Meta:
model = State
exclude = ['state', 'relevantdisease']
def __init__(self, *args, **kwargs):
disease=kwargs.pop('disease', None)
super(SelectOptionForStateForm, self).__init__(*args, **kwargs)
self.fields['relevantoption']=forms.ModelMultipleChoiceField(queryset=Option.objects.filter(relevantdisease_id=disease),required=True,
widget=forms.CheckboxSelectMultiple)
self.fields['relevantoption'].label="Treatment Options"
class SelectOutcomeForOptionForm(forms.ModelForm):
class Meta:
model = StateOption
exclude = ['partstate', 'partoption']
def __init__(self, *args, **kwargs):
disease=kwargs.pop('disease', None)
super(SelectOutcomeForOptionForm, self).__init__(*args, **kwargs)
self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.filter(relevantdisease_id=disease),required=True,
widget=forms.CheckboxSelectMultiple)
self.fields['relevantoutcome'].label="Treatment Outcomes"
views.py
def stateoptionoutcome(request, disease_id, state_id):
state = get_object_or_404(State, pk=state_id)
disease = get_object_or_404(Disease, pk=disease_id)
if request.method == "POST":
optionForm = SelectOptionForStateForm(request.POST,
disease=disease, instance=state)
outcomeForm = SelectOutcomeForOptionForm(request.POST,
disease=disease, instance=state)
if optionForm.is_valid() and outcomeForm.is_valid():
#Deletes state objects so there are no duplicate options in the
database
try:
state_option =
StateOption.objects.filter(partstate=state).delete()
except StateOption.DoesNotExist:
state_option = None
#Saves user options to database
for option_id in request.POST.getlist('relevantoption'):
state_option = StateOption.objects.create(partstate=state,
partoption_id=int(option_id))
#Deletes stateoption objects found in StateOptionOutcome
try:
state_option_outcome =
StateOptionOutcome.objects.filter(stateoption=state_option).delete()
except StateOptionOutcome.DoesNotExist:
state_option_outcome = None
#Saves user outcomes to database
for outcome_id in request.POST.getlist('relevantoutcome'):
state_option_outcome =
StateOptionOutcome.objects.create(stateoption=state_option,
relevantoutcome_id=int(outcome_id))
return HttpResponseRedirect(reverse('diseasestateoptionlist',
kwargs={'disease_id':disease_id, 'state_id':state_id}))
models.py
class State(models.Model):
state = models.CharField(max_length=255)
relevantdisease = models.ForeignKey(Disease)
relevantoption = models.ManyToManyField(Option, through='StateOption')
class StateOption(models.Model):
partstate = models.ForeignKey(State)
partoption = models.ForeignKey(Option)
relevantoutcome = models.ManyToManyField(Outcome,
through='StateOptionOutcome')
class StateOptionOutcome(models.Model):
stateoption = models.ForeignKey(StateOption)
relevantoutcome = models.ForeignKey(Outcome)
outcomevalue = models.CharField(max_length=20)

JS - Strip variable of html tags and replace with line breaks

JS - Strip variable of html tags and replace with line breaks

I've been going round in circles for ages with this. I'm trying to create
a function in javascript (or jQuery) that will take a variable filled with
html and output a plain text version. The function needs to strip the html
tags and insert line breaks at the end of heading and paragraph tags.
The html variable would be something like:
var html = '<h1>This is a heading</h1><p>This is a paragraph</p><p>This is
another paragraph</p>'
This is really close: http://jsfiddle.net/wv49v/, but it doesn't take a
variable, only a DOM object (I think!). I.e. this works:
document.getElementById("text").value =
getInnerText(document.getElementById("content"));
and this doesn't:
document.getElementById("text").value = getInnerText(html);
If there is a better solution to this I'm open to suggestions!

python argparse -h like behaviour and mutually exclusive arguments

python argparse -h like behaviour and mutually exclusive arguments

My script will normally accept a required argument like so script.py PATH
but I also what to be able to call it like so script.py -e EXPRESSION and
omit PATH alltogether.
Is there a way to do that with argparse?
For backwards compatibility I want to add this feature but not change the
existing behaviour for example by having paths be passed with script.py
--path PATH instead of just script.py PATH
I expect that this shouldn't be too hard as it is similar to the behaviour
of -h.

how to upload files from a winform app to server?

how to upload files from a winform app to server?

I want to upload some files to my server from a winform application.
Clients will select files from their pc and once they click upload the
files should be uploaded to their folders in server.
I do not want to use ftp for this, because I can not risk the security. Is
there any solution ?
Files can be of any size and formats including pictures, word documents,
presentations and videos

gogo: CommandNotFoundException: Command not found: services

gogo: CommandNotFoundException: Command not found: services

I know some of the commands havechanged names when Apache Felix started
using GoGo
For example: ps --> lb (list bundles)
What is the equivalent for services <BUNDLENO>
I am trying to get the following output from my console:
services 5
Distributed OSGi Zookeeper-Based Discovery Single-Bundle Distribution (6)
provides:
-----------------------------------------------------------------------------------
... other services ...
----
objectClass = org.osgi.service.cm.ManagedService
felix.fileinstall.filename = org.apache.cxf.dosgi.discovery.zookeeper.cfg
service.id = 38
service.pid = org.apache.cxf.dosgi.discovery.zookeeper
zookeeper.host = localhost
zookeeper.port = 2181
zookeeper.timeout = 3000

Tuesday, 17 September 2013

value is not called in other method though it is defined globally in ios6

value is not called in other method though it is defined globally in ios6

I am posting the code which I tried.I am getting string value and then I
am adding it to an array and getting the array value too.But problem comes
when I try to use the array value in other method ,it's value is blank.
//ViewController.h
@interface ViewController : UIViewController{
NSString *stringValueVideoiD;
NSMutableArray *TableVideoIDArray;
}
//ViewController.m
@implementation ViewController
- (void)viewDidLoad
{
TableVideoIDArray=[[NSMutableArray alloc]init];
[self getAllRows];
}
-(void) getAllRows{
if(sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK)
{
NSString *sqlStatement = [NSString stringWithFormat:@"SELECT * FROM
table"];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(db,[sqlStatement UTF8String] , -1,
&compiledStatement, NULL)== SQLITE_OK)
{
while(sqlite3_step(compiledStatement)==SQLITE_ROW)
{
char *videoId = (char *)
sqlite3_column_text(compiledStatement, 1);
stringValueVideoiD = [[NSString alloc]
initWithUTF8String:videoId];
TableVideoIDArray=[[NSMutableArray alloc]init];
[TableVideoIDArray addObject:stringValueVideoiD];
NSLog(@"vids array:%@",TableVideoIDArray);
//vids aray:value is printed
}
}
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView
dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell==nil) {
cell=[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleTableIdentifier];
}
NSLog(@"here:%@",TableVideoIDArray);
//here comes the problem.My console result is
2013-09-18
11:18:24.431 TubeAlert[468:11303] here:( ) //so guys I need your help why
this is happenning or I am making mistakes in my code.

Why doesn't this code give any exceptions?

Why doesn't this code give any exceptions?

I am using Apache commons net library to upload a file to a server. This
is the code:
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class Test {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
client.connect("");
client.login("", "");
client.setFileType(FTP.BINARY_FILE_TYPE);
client.storeFile("log", new FileInputStream("log"));
client.logout();
}
}
I haven't specified any url or login credentials. Why doesn't it give an
exception?

Postgres - using DISTINCT ON to get first row, but also getting the COUNT(*) work

Postgres - using DISTINCT ON to get first row, but also getting the
COUNT(*) work

I'm using
SELECT DISTINCT ON()
to return a particular row from a group of rows. Works well. But what I
also want to return is the "COUNT(*)". So it might look like
SELECT DISTINCT ON(name)
name, num_items, COUNT(name)
FROM customers
ORDER BY name, num_items DESC
But of course, I get an error saying "name should be in a GROUP BY
aggregate function".
How can I achieve the same result with the "count()" included?

c program aborts with core dump unless printf is inserted in code?

c program aborts with core dump unless printf is inserted in code?

I have a function that aborts with a core dump unless I insert a printf:
// Read all available text from the connection
char *sslRead (connection *c)
{
const int readSize = 1024;
char *rc = NULL;
int received, count = 0;
char buffer[1024];
// printf("??"); // If I comment this out: Aborted (core dumped)
if (c)
{
while (1)
{
if (!rc)
rc = malloc (readSize * sizeof (char) + 1);
else
rc = realloc (rc, (count + 1) *
readSize * sizeof (char) + 1);
received = SSL_read (c->sslHandle, buffer, readSize);
buffer[received] = '\0';
if (received > 0)
strcat (rc, buffer);
if (received < readSize)
break;
count++;
}
}
return rc;
}
The malloc seems to be the offending line.
The full source code is here:
http://savetheions.com/2010/01/16/quickly-using-openssl-in-c/
What could be causing this?
Below is the output from my build:
23:06:41 **** Incremental Build of configuration Debug for project
HelloWorldOpenSSL ****
Info: Internal Builder is used for build
gcc "-IC:\\dev\\cygwin64\\opt\\cs\\include" -O0 -g3 -Wall -c
-fmessage-length=0 -o MyC.o "..\\MyC.c"
gcc "-LC:\\dev\\cygwin64\\opt\\cs\\lib" -o HelloWorldOpenSSL.exe MyC.o
-lssl -lcrypto
23:06:42 Build Finished (took 804ms)

Setar TsDyn ADF specification no lags error

Setar TsDyn ADF specification no lags error

In tsDyn, I am attempting to model a ADF-like threshold model, but I want
to include zero lags. When I do this, I get an error no matter how I
specify it. When I allow one lag I get both a first differenced lag and a
regular lag. I just want the regular lag as in an ADF test. Thanks!

OAuth2 in development and production

OAuth2 in development and production

What is the best strategy of using OAuth2 authentication in development
and production environment?
For example, I want to create an open source web based GitHub client. I
have registered my client as GitHub application. According to OAuth2 spec
I have to specify a redirect url while registering an application. What
redirect_url should I use, localhost-based or real production url? If I
use localhost-based (for development), my production site obviously stop
working (and vice versa).
Is it safe to store client_id and client_secret in public code? If no,
what is the best strategy to store it (i.e. in some config file that is
not added to source version control system)?

Sunday, 15 September 2013

How to make one area of a html page redirect to another url while the rest part of the page stay same?

How to make one area of a html page redirect to another url while the rest
part of the page stay same?

I'm working on a CMS back-end with Codeigniter. Maybe it's not clear to
state my question with word. So I use some simple html code to express my
question: There is a html page called A.html. The code in A.html is
following:
<html>
<head>
/*something*/
</head>
<!-- menu area -->
<div class="menu">
<ul class="nav">
<li class="nav-header">menu item1</li>
<li class="nav-header">menu item2</li>
<li class="nav-header">nav-header3</li>
</ul>
</div>
<!-- content area -->
<div id="content">
</div>
</html>
I know we can use jQuery's load to change the #content's content when I
click the nav-header.But my question is that how can I make content change
just in the content area(#content) while the rest of page content stay
same when I click the link in the content area. I have tried the
iframe,but it make the page more complex and I don't like it. Thanks.

Android Timer/Clock

Android Timer/Clock

i want a clock/timer that's not insanely fast and force closes like a
while loop. This force closes:
while(loopEnabled == true)
{
//Do stuff
Toast toast Toast.makeText(this, "Hi!", 10000);
toast.show();
}
And so does this:
public void loop()
{
//Do stuff
Toast toast Toast.makeText(this, "Hi!", 10000);
toast.show();
resetLoop();
}
public void resetLoop()
{
Thread.sleep(100);
loop();
}
Any alternatives to stop this? I'm meaning for code to happen rapidly over
and over.

How to add values to existing dictionary key Python

How to add values to existing dictionary key Python

I am trying to create a function that takes in four parameters: A keyname,
start time, end time, and then a dictionary. I have to create a tuple out
of the start time and end time and then append that to a list of tuples,
as we will be running this function multiple times. Then I am trying to
put certain parts of the list of tuples to certain keynames.
I think it's better if I would show you would the output looks like:
courses = insertIntoDataStruct("CS 2316", "1505", "1555", courses)
courses = insertIntoDataStruct("CS 2316", "1405", "1455", courses)
courses = insertIntoDataStruct("CS 2316", "1305", "1355", courses)
courses = insertIntoDataStruct("CS 4400", "1405", "1455", courses)
courses = insertIntoDataStruct("CS 4400", "1605", "1655", courses)
print(courses)
{'CS 2316': [(1505, 1555), (1405, 1455), (1305, 1355)], 'CS 4400': [(1405,
1455), (1605, 1655)]}
This is my code so far:
aDict = {}
tupleList = []
def insertIntoDataStruct(name,startTime,endTime,aDict):
timeTuple = tuple([startTime, endTime])
tupleList.append(timeTuple)
aDict[name] = tupleList
return aDict
I know that this will give me a dictionary with each key having ALL
values, but I have no idea on how to make it so that each value that I add
will be added on to the dictionary as seen in the output. I have tried a
lot of random things, but I am still stuck on this. :(

My website is showing apache2 test page

My website is showing apache2 test page

My website that I use xenforo for stopped working and shows the apache2
test page and the domain/admin.php doesn't load and shows this
http://pastebin.com/84mLHuKr. What is wrong with it and how do I fix this?

Set CurrentUICulture in Windows 8.1

Set CurrentUICulture in Windows 8.1

I'm using Windows 8.1 with Russian locale. I've set it in Control Panel >
Languages. Recently, I've downloaded a program which uses Russian language
for UI and it has had a problem with encoding. After a little research
I've found that although my CurrentCulture is setted to ru-RU, my
CurrentUICulture is setted to en-US. The strange thing that all other
programs which use cyrillic work perfectly fine.
So now the question. How to set CurrentUICulture in Windows 8.1?

C++ memcpy: double incompatible with const void

C++ memcpy: double incompatible with const void

I have a private member
vector<double>m_data_content_joinfeatures;
and a struct:
struct udtJoinFeatures
{
double Values[16];
};
I would now like to copy some values from m_data_content_joinfeatures to a
struct of udtJoinFeatures like this:
void clsMapping::FeedJoinFeaturesFromMap(udtJoinFeatures &uJoinFeatures)
{
unsigned int iByteStartPos=1024; //where the data starts that I want
to copy
unsigned int iByteCount=128; //the number of bytes that I want to copy
memcpy(&uJoinFeatures[0],
m_data_content_joinfeatures[iByteStartPos],iByteCount);
}
But the compiler tells me that "double is not compatible with the
parameter of the kind void*".
Can somebody help? I don't want to use a for-next-statement to copy my
values over. I would like to use MemCpy if possible because I think it is
the fastest way.
Thank you!

JCarouselLite not showing all images/links properly

JCarouselLite not showing all images/links properly

I use JCarouselLite to slide accross all the images/link in my page. 6 of
them are displayed on the page by default, but after clicking the Next
button some time, no images that should be additionaly displayed are
showing. Then, after some time clicking Next button, they are displayed
right (see image). Could somebody help me with this? Thanks in advance.

Code:
<div id="cat_slider">
<div id="cat_slider_inside">
<ul class="cat_slider_inside">
<?php foreach ($categories as $cat) : ?>
<li>
<a href=...>
<img src="<?php echo z_taxonomy_image_url($cat->term_id);
?>" />
<span><?php echo $cat->name; ?></span>
</a>
</li>
<?php endforeach; ?>
</ul><!-- end .cat_slider_inside -->
</div><!-- end #cat_slider_inside -->
</div><!-- end #cat_slider -->
<!-- Categories Slider Buttons -->
<a href="#" class="md-prev-button"></a>
<a href="#" class="md-next-button"></a>
JQ:
$(function() {
// Load the categories sliders
$('#cat_slider_inside').jCarouselLite({
btnNext: '.md-next-button',
btnPrev: '.md-prev-button',
visible: 2
});
});

Saturday, 14 September 2013

Insert in parent child table + Oracle + Entity framework 5 + VS 2012

Insert in parent child table + Oracle + Entity framework 5 + VS 2012

I have been started working on EF 5 on oracle database and as first
assignment I have to insert into parent child tables in oracle database.
But I am facing an issue with inserting record in child table because
oracle doesn't return identity column from parent table like sql server.
I want to use EF with oracle database in same manner as I was using with sql.
I don't want to use trigger to insert into parent child tables
Also I don't want to use generating sequences before inserting into parent
and child tables
We have very high operations on these tables so we can't go with above
options.
Please suggest if there is any other out of box option available with EF 5
in VS 2012 ultimate edition.
Thanks you,

Autocompile Stylus in Ruby on Rails server?

Autocompile Stylus in Ruby on Rails server?

How I can compile automatically in my server the .styl files and dont have
to run Stylus in the console...?
I dont want to run all the times I want to work the command "stylus -w" in
the folder of my stylesheets, I want to my server auto compile my .styl.

eregi() deprecated - I am not sure how to rewrite this code

eregi() deprecated - I am not sure how to rewrite this code

Deprecated code:
function validate_email($email) { return
eregi("^[_.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+.)+[a-zA-Z]{2,6}$",
$email); }
I am a JavaScript beginner. The above code gives an error. I am not too
sure how to rewrite using preg_match.

Codeigniter pagination ignores last db entries

Codeigniter pagination ignores last db entries

So I have code like this Controller:
function latest()
{
// Pagination $config
$config['base_url'] = base_url() . 'posts/latest';
$config['total_rows'] = $this->m_posts->getLatestPostsCount(50);
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['use_page_numbers'] = TRUE;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['posts'] = $this->m_posts->getLatestPosts($config['per_page'],
$page);
$data['pagination'] = $this->pagination->create_links();
$this->template->build('posts/posts', $data);
}
and model:
function getLatestPosts($limit = 0, $start = 0)
{
$this->db->order_by('id', 'desc');
// Get LATEST posts -> pagination
$q = $this->db->get('posts', $limit, $start);
foreach ($q->result() as $key => $row)
{
$data[$key]['id'] = $row->id;
// and so on
}
return $data;
}
function getLatestPostsCount($limit = 0)
{
$this->db->order_by('id', 'desc');
$q = ($limit == 0) ? $this->db->get('posts') : $this->db->get('posts',
$limit);
return $q->num_rows();
}
so yeah.. the problem is that if I have, lets say, 50 db entries (posts)
and set per page = 8. it is 50/8 = 6, right? I have problem with
pagination that those 2 just dissapears... codeigniter just don't create
the 7th page with last two entries.... How can I get this 7th page, and
display 2 missing posts???

Docker updating image along when dockerfile changes

Docker updating image along when dockerfile changes

I'm playing with docker by creating a Dockerfile with some nodejs
instructions. Right now, every time I make changes to the dockerfile I
recreate the image by running sudo docker build -t nodejstest . in my
project folder however, this creates a new image each time and swallows my
ssd pretty soon.
Is there a way I can update an existing image when I change the dockerfile
or I'm forced to create a new one each time I make changes to the file?
Sorry if it's a dumb question

Incomplete data when I execute my report?

Incomplete data when I execute my report?

Ive created a report using report viewer and but when I execute the report
the column Student ID, First Name, Last Name, Middle Initial, Contact
Number are empty. The other columns is okay and has data.

unable to specify multiple permissions on facebook using passportjs

unable to specify multiple permissions on facebook using passportjs

app.get('/auth/facebook', passport.authenticate('facebook', { scope: [
'email','publish_actions','user_birthday' ] }));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
failureRedirect: conf.failureRedirect || '/'
}), exports.redirectOnSuccess);
};

Friday, 13 September 2013

Ios NSDictionary array - grouping values and keys

Ios NSDictionary array - grouping values and keys

I have the following result of NSDictionary Array
Bath = {
Keynsham = (
"nsham companies"
);
};
Bath = {
"Midsomer Norton" = (
"Keynsham companies"
);
};
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
};
Birmingham = {
"Acock's Green" = (
"Acock's Green taxi companies"
);
};
Birmingham = {
"Alcester Lane's End" = (
"Alcester Lane's End taxi companies"
);
};
How can i combine the values and keys so that I end up with only one
category as shown below;
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
"Midsomer Norton" = (
"Keynsham companies"
);
Keynsham = (
"nsham companies"
);
};
I am not sure if this is the best way to explain it

Still requiring login after SSH authentication

Still requiring login after SSH authentication

I followed everything in the GitHub tutorial:
https://help.github.com/articles/generating-ssh-keys
I did all the commands in the directory of my repository. I reached the
end of tutorial successfully and got the message: "Hi username! You've
successfully authenticated, but GitHub does not # provide shell access."
However when I tried to do things such as push it still requested for my
username and password.

Is O(n) + O(n log n) equals to O(n log n)?

Is O(n) + O(n log n) equals to O(n log n)?

One code I've done follows this schema:
for (i = 0; i < N; i++){ // O(N)
//do some processing...
}
sort(array, array + N); // O(N log N)
Whats the complexity in Big-O notation?
Thanks in advance

How do I get logs/details of ansible-playbook module executions?

How do I get logs/details of ansible-playbook module executions?

Say I execute the following.
$ cat test.sh
#!/bin/bash
echo Hello World
exit 0
$ cat Hello.yml
---
- hosts: MyTestHost
tasks:
- name: Hello yourself
script: test.sh
$ ansible-playbook Hello.yml
PLAY [MyTestHost]
****************************************************************
GATHERING FACTS
***************************************************************
ok: [MyTestHost]
TASK: [Hello yourself]
********************************************************
ok: [MyTestHost]
PLAY RECAP
********************************************************************
MyTestHost : ok=2 changed=0 unreachable=0
failed=0
$
I know for sure that it was successful.
Where/how do I see the "Hello World" echo'ed/printed by my script on the
remote host (MyTestHost)? Or the return/exit code of script?
My research shows me it would be possible to write a plugin to intercept
module execution callbacks or something on those lines and write a log
file. I would prefer to not waste my time with that.
E.g. something like the stdout in below (note that I'm running ansible and
not ansible-playbook):
$ ansible plabb54 -i
/project/plab/svn/plab-maintenance/ansible/plab_hosts.txt -m script -a
./test.sh
plabb54 | success >> {
"rc": 0,
"stderr": "",
"stdout": "Hello World\n"
}
$

Highslide JS - Is there a way to have expanded images share a common center?

Highslide JS - Is there a way to have expanded images share a common center?

I'm using Highslide JS with gallery, using a single thumbnail to launch
the gallery. After expanding the image, when advancing through the
expanded gallery, all of the images appear to be anchored at the bottom,
meaning, when you switch from a landscape (long-side horizontal) image to
a portrait (long-side vertical) image, the bottom edge of the image will
stay in one place, and the remainder of the image will expand upwards.
This doesn't work too badly, except if when you go from a portrait image
to a landscape image, the new image is sitting at the bottom of the
viewport. Is there any way to have all of the images share a common
center, and expand from there, instead of sharing a common bottom edge?
That way they won't be constantly moving up and down in the viewport. If I
want to use a thumbstrip, I can't place it on the top or bottom since it
can/will get covered up by an image at times. All of the expanded images
I'm using are 800x536 or 536x800, depending on orientation.

Getting garbage data when marshalling C structure with union to C# code

Getting garbage data when marshalling C structure with union to C# code

I am trying to use following C struct in managed application
typedef struct libvlc_media_track_t
{
uint32_t i_codec;
uint32_t i_original_fourcc;
int i_id;
libvlc_track_type_t i_type;
int i_profile;
int i_level;
union {
libvlc_audio_track_t *audio;
libvlc_video_track_t *video;
libvlc_subtitle_track_t *subtitle;
};
unsigned int i_bitrate;
char *psz_language;
char *psz_description;
} libvlc_media_track_t;
typedef struct libvlc_audio_track_t
{
unsigned i_channels;
unsigned i_rate;
} libvlc_audio_track_t;
typedef struct libvlc_video_track_t
{
unsigned i_height;
unsigned i_width;
unsigned i_sar_num;
unsigned i_sar_den;
unsigned i_frame_rate_num;
unsigned i_frame_rate_den;
} libvlc_video_track_t;
typedef struct libvlc_subtitle_track_t
{
char *psz_encoding;
} libvlc_subtitle_track_t;
unsigned libvlc_media_tracks_get( libvlc_media_t *p_md,
libvlc_media_track_t ***tracks );
And .NET version looks like this:
[StructLayout(LayoutKind.Explicit)]
public struct libvlc_media_track_t
{
[FieldOffset(0)]
public uint i_codec;
[FieldOffset(4)]
public uint i_original_fourcc;
[FieldOffset(8)]
public int i_id;
[FieldOffset(12)]
public libvlc_track_type_t i_type;
[FieldOffset(16)]
public int i_profile;
[FieldOffset(20)]
public int i_level;
[FieldOffset(24)]
public libvlc_audio_track_t audio;
[FieldOffset(24)]
public libvlc_video_track_t video;
[FieldOffset(24)]
public libvlc_subtitle_track_t subtitle;
[FieldOffset(48)]
public uint i_bitrate;
[FieldOffset(52)]
public IntPtr psz_language;
[FieldOffset(56)]
public IntPtr psz_description;
}
[StructLayout(LayoutKind.Sequential)]
public struct libvlc_audio_track_t
{
public uint i_channels;
public uint i_rate;
}
[StructLayout(LayoutKind.Sequential)]
public struct libvlc_video_track_t
{
public uint i_height;
public uint i_width;
public uint i_sar_num;
public uint i_sar_den;
public uint i_frame_rate_num;
public uint i_frame_rate_den;
}
[StructLayout(LayoutKind.Sequential)]
public struct libvlc_subtitle_track_t
{
public IntPtr psz_encoding;
}
[DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
public static unsafe extern int libvlc_media_tracks_get(IntPtr media,
libvlc_media_track_t*** ppTracks);
unsafe
{
libvlc_media_track_t** ppTracks;
int num = LibVlcMethods.libvlc_media_tracks_get(m_hMedia, &ppTracks);
if (num == 0 || ppTracks == null)
{
throw new Exception();
}
for (int i = 0; i < num; i++)
{
libvlc_media_track_t* pTrackInfo = ppTracks[i];
}
LibVlcMethods.libvlc_media_tracks_release(ppTracks, num);
}
The code works without any exception but I get garbage data in most of the
structure/union fields.
Please advise, Thanks in advance

Thursday, 12 September 2013

Count the number of max consecutive "a"'s from a string. Python 3

Count the number of max consecutive "a"'s from a string. Python 3

Say that the user inputs:
"daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"
How would you go about finding the highest number of consecutive "a" and
how would you remove the "a"'s and leave only 2 of them instead of the
large number of them before.
I was thinking of appending each letter into a new empty list but i'm not
sure if that's correct or what to do after.
I really don't know where to begin with this one but this is what i'm
thinking:
Ask the user for input.
Create an empty list
Append each letter from the input into the list
What's next I have no idea.
second edit (something along these lines):
sentence = input("Enter your text: ")
new_sentance = " ".join(sentence.split())
length = len(new_sentance)
alist = []
while (length>0):
alist
print ()

Keep dropdown open on hover jQuery

Keep dropdown open on hover jQuery

I'm making a quick animated drop down. I have it working great when you
mouseover and mouseout on the initial button. I just cant get the HTML div
that drops down to "hold" when you're hovered on the dropdown itself. here
is a fiddle of what I'm doing: http://jsfiddle.net/kAhNd/
here's what I'm doing in the JS:
$('.navBarClickOrHover').mouseover(function () {
var targetDropDown = $(this).attr('targetDropDown');
var targetDropDownHeight = $('#' + targetDropDown).height();
$('#' + targetDropDown).animate({
'height': '200px'
});
}).mouseout(function () {
if ($('.dropdownCont').is(':hover') ||
$('.navBarClickOrHover').is(':hover')) {
} else {
var targetDropDown = $(this).attr('targetDropDown');
var targetDropDownHeight = $('#' + targetDropDown).height();
$('#' + targetDropDown).animate({
'height': '0px'
});
}
});
It works, but the element doesn't stay dropped down when you have your
mouse over it. I added in
if ($('.dropdownCont').is(':hover') ||
$('.navBarClickOrHover').is(':hover')) {
}
to try to make it do nothing when you're hovered over '.dropdownCont'.
Having a hard time explaining it. I'm sorry, I hope I make sense. Any help
would be awesome! here's my Fiddle: http://jsfiddle.net/kAhNd/

INSERT multiple entries from Android -> PHP -> MYSQL

INSERT multiple entries from Android -> PHP -> MYSQL

I am trying to insert multiple (1-50) entries from an Android application
to an external Mysql database. I perfectly got a PHP script to work for
single INSERT queries. But I am failing so far to make this work for a
whole array of entries, most likely due to my limited understanding of
PHP.
Android code:
List<NameValuePair> upload_array = new ArrayList<NameValuePair>();
upload_array.add(new BasicNameValuePair("mFirstname[0]", "FirstName 1"));
upload_array.add(new BasicNameValuePair("mFirstname[1]", "FirstName 2"));
upload_array.add(new BasicNameValuePair("mLastname[0]", "LastName 1"));
upload_array.add(new BasicNameValuePair("mLastname[1]", "LastName 2"));
upload_array.add(new BasicNameValuePair("mNickname[0]", "NickName 1"));
upload_array.add(new BasicNameValuePair("mNickname[1]", "NickName 2"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url/script.php");
HttpResponse response = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(upload_array));
response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
}
And in PHP:
<?php
$connect = mysqli_connect("***","***","***", "***");
if(mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "success";
}
$query = mysqli_prepare("INSERT INTO `namelist`
(`firstname`,`lastname`,`nickname`)
VALUES(?,?,?)");
$mFirstname = $_POST['mFirstname'];
$mLastname = $_POST['mLastname'];
$mNickname = $_POST['mNickname'];
foreach($mFirstname as $key as $key => $value) {
$query->bind_param('sss',$value["mFirstname"],$value["mLastname"],$value["mNickname"];
$query->execute();
}
mysqli_close($connect);
?>
Is the mistake happening in the Android part of the code already or does
this PHP script just not read the data I sent properly? Any insight would
be very welcome.

Filter a combobox in a datagrid based on another combobox column in the same row

Filter a combobox in a datagrid based on another combobox column in the
same row

i am new to wpf and i want to know how can i implement 2 comboboxes
columns in a datagrid where the first combobox contains Countries ,and the
other contains cities so while editing on datagrid cities colunmn combobox
is filtered by the country selected in countries combo box using MVVM
pattern
Thanks

Hiding li tag in jquery

Hiding li tag in jquery

i bulid a drop down menu using li and ul html tag but now i want to hide
some menu depends on user level
CODE:
<li id="20"><a href="#">File Generation<br /></a>
<ul class="subload">
<li id="21" ><a href="#">Generate
Files<br/></a></li>
<li id="22" ><a href="#">Reprocess<br/></a></li>
<li id="23" ><a href="#">File
Regenerate<br/></a></li>
<li id="24" ><a href="#">File
Status<br/></a></li>
</ul></li>
I tried
$(document).ready(function() {
$("li #20").hide();
$("body").on({
ajaxStart: function() {
$(this).addClass("loading");
},
ajaxStop: function() {
$(this).removeClass("loading");
}
});
var theForm = $("form[name=MenuBean]");
var params = theForm.serialize();
var actionURL = theForm.attr("action");
$.ajax({
type: "POST",
url: actionURL + "?name='Anand'",
data: params,
success: function(data, textStatus, XMLHttpRequest) {
alert("Success : " + data);
var tmp = data.split("|");
for (i = 0; i < tmp.length; i++) {
$("li #"+tmp[i]).show();
}
if (data == "success") {
} else {
$("#ajaxresult").show().html(data).fadeIn(1000);
}
},
error: function(XMLHttpRequest, textStatus, data) {
alert("Error : " + data);
}
});
//event.preventDefault();
});
but its not working properly..

Is there an ANTLR4 grammar for ANTLR4

Is there an ANTLR4 grammar for ANTLR4

I know that there is an ANTLR3 grammar for ANTLR3, and it seems to me that
the ANTLR4 distribution contains ANTLR4 grammar written in ANTLR3, but is
there a grammar for ANTLR4 written in ANTLR4 itself?

Wednesday, 11 September 2013

new line chars added to csv file after ftp.storbinary()

new line chars added to csv file after ftp.storbinary()

I am attempting to store a csv file on an ftp server using python's ftplib
module. Right now, I have about 30 lines of code which generates
probabilities of weather values in a 2-d array. I then write this 2-d
array to a csv file.
When I write the csv file onto my local drive, the file displays as
expected within excel. However, when I view the file after I uploaded it
to an ftp server, I see that a new line character has been added after
every row.
I've done some minor testing to see what the problem may be, and I have
been able to upload the csv file with coreftp. The csv file displays
correctly after I do that. So I am pretty sure the file is fine, its
something that is happening when python uploads it onto an ftp server.
I was originally creating a text file with a .csv extension file then
reopening it as a binary file and uploading it. I thought that may be the
issue so I tried using the csv module, but same issue.
Here is my code at the moment...
TEMPSHEADER = [i-50 for i in range(181)]#upper bounds exclusive
WINDSHEADER = [i for i in range(101)]#upper bounds exclusive
HEADER = TEMPSHEADER + WINDSHEADER
for site in ensmosdic:
ensmos = ensmosdic.get(site)
with open(utcnow.strftime("%Y-%m-%d") + "-"
+site+"-prob.csv","w",newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerow(["CODE ","F","ForecastDate","HOUR"]+HEADER)
siteTable =[[0 for x in range(286)] for y in range(24,169)]#upper
bounds exclusive
###########
#other code here, but not important with regards to post
###########
for i in siteTable:
writer.writerow(i)
csvfile.close()#not sure if you have to close csv file, not in csv
module docs
f = open(utcnow.strftime("%Y-%m-%d") + "-" +site+"-prob.csv","rb")
ftpInno.storbinary("STOR " + utcnow.strftime("%Y-%m-%d-") + site
+"-prob.csv",f)
f.close()
ftpInno.close()
Thanks in advance

Visual Studio Form Designer changes layout of controls on open

Visual Studio Form Designer changes layout of controls on open

I have a form that looks like this in the designer:

However, when I close the designer and open it again, it looks like this:

The eight controls that have moved are text boxes and labels that are all
set to Anchor Top, Right while all the other controls have different
anchoring.
Does anyone have any idea what is causing this change of layout, and more
importantly, how it can be prevented?

Instance Variable string collection lost after render => 'new'

Instance Variable string collection lost after render => 'new'

When I get an error creating a quote, it renders the same page it was just
on and displays the errors. Unfortunately two inputs are drop down menus
of strings, and they disappear when the refresh happens.
I've looked at Rail 3: instance variable not available after redirection
which talks about sessions, which looks like it could be the right way to
go but I'm not sure. Any help would be appreciated.
quotes controller
def new
@quote = Quote.new
@quote.items.build
@types = ["T-Shirt", "Hoodie", "Sweatpants"]
@colors = ["White", "Black", "Red", "Blue", "Green"]
end
def create
@quote = Quote.new(params[:quote])
respond_to do |format|
if @quote.save
format.html { redirect_to root_url }
flash[:success] = "Your quote is being approved. You will recieve an
email shortly!"
format.json { render json: @quote, status: :created, location: @quote }
else
format.html { render :action => 'new' }
format.json { render :json => @quote.errors, :status =>
:unprocessable_entry }
flash[:error] = "Quote failed to create! Try again!"
end
end
end
form partial
<!-- item form -->
<%= f.input :make, collection: @types, label: 'Thread Type' %>
<%= f.input :amount, label: 'How Many' %>
<%= f.input :color, collection: @colors %>
<!-- nested form for creating a design of an item -->
<%= f.simple_fields_for :designs, :html => { :multipart => true } do
|designform| %>
<%= render "customdesign", g: designform %>
<% end %>
<!-- add/remove another design -->
<%= f.link_to_add "Add Design", :designs %>
<%= f.input :note, :input_html => { :cols => 50, :rows => 3 }, label:
'Special Notes or Requests' %>
<%= f.link_to_remove "Remove" %>

Bootstrap Collapse - each div by some class?

Bootstrap Collapse - each div by some class?

Have more than one div for collapsing with some class without ID:
<div class="spoiler">
<div class="spoiler-btn">spoiler1</div>
<div class="spoiler-body>spoiler 1</div>
</div>
<div class="spoiler">
<div class="spoiler-btn">spoiler2</div>
<div class="spoiler-body>spoiler 2</div>
</div>
<div class="spoiler">
<div class="spoiler-btn">spoiler3</div>
<div class="spoiler-body>spoiler 3</div>
</div>
With data-attribute data-toggle="collapse" data-target=".spoiler-body" in
.spoiler-btn plugin collapsing all div. But need collapsing only within
parent .spoiler
write this:
$.fn.ready(function() {
$('.spoiler').each(function(){
var $this = $(this)
$this.on('click', '.spoiler-head', function (e) {
$this.children('.spoiler-body').collapse('toggle')
e.preventDefault()
})
})
})
Not sure of the code. And it does not work in mobile Safari. Any right way?
Thanks

Getting `Can't assign requested address` java.net.SocketException using Ehcache multicast

Getting `Can't assign requested address` java.net.SocketException using
Ehcache multicast

Getting java.net.SocketException when trying to start a multicast provider:
2013-09-11 11:45:44,204 [main] ERROR
net.sf.ehcache.distribution.MulticastRMICacheManagerPeerProvider: Error
starting heartbeat. Error was: Can't assign requested address
java.net.SocketException: Can't assign requested address
at java.net.PlainDatagramSocketImpl.join(Native Method)
at
java.net.AbstractPlainDatagramSocketImpl.join(AbstractPlainDatagramSocketImpl.java:178)
at java.net.MulticastSocket.joinGroup(MulticastSocket.java:319)
at
net.sf.ehcache.distribution.MulticastKeepaliveHeartbeatReceiver.init(MulticastKeepaliveHeartbeatReceiver.java:88)
at
net.sf.ehcache.distribution.MulticastRMICacheManagerPeerProvider.init(MulticastRMICacheManagerPeerProvider.java:95)

insert object at index updates whole nsmutablearray

insert object at index updates whole nsmutablearray

I have an NSMutableArray with multiple products. Each product has an
amount. I want to update the amount of the associated product, when a
stepper is clicked. But all my products (whole NSMutableArray) are updated
with the amount of the stepper.
NSInteger index = stepper.tag;
Product *p = [[Product alloc] init];
p = [products objectAtIndex:index];
p.amount = [NSNumber numberWithDouble:stepper.value];
[products removeObjectAtIndex:index];
[products insertObject:p atIndex:index];
Someone a solution?
regards

Publishing photo to facebook fan page album not creating timeline story

Publishing photo to facebook fan page album not creating timeline story

I'm successfully publishing a photo to a facebook fan page album.
According to the api
(https://developers.facebook.com/docs/reference/api/page/#photos) this
should create a story in the timeline by accident, but this isn't
happening. The parameters i use are:
$params = arra(
'message' => 'testing',
'source' => '@/var/www/publish_facebook/images/corn.jpg',
'aid' => '269018009877732',
'access_token' => [The Access Token],
'no_story' => 0
)
$photo = $facebook->api("/".$aid . '/photos', 'post', $params);
By default "no_story" should be set to 0 anyway, according to the
documentation. The photo gets published to the album, but a story is never
created on the timeline...

Spring Web Service Tomcat FULL EXAMPLE

Spring Web Service Tomcat FULL EXAMPLE

I'm working with eclipse, maven, and Tomcat. And, I 'v been searching the
net for 3 days, but i can't find any clear example on web services. if you
can help me, i need a simple example including every single detail( type
of project, server, web.xml file, Servlet file, their directories , their
content, client class). Can you send me any working project ?

Query regarding regular expression

Query regarding regular expression

hi I have a string like this:
String s = "@Path(\"/BankDBRestService/customerExist(String")\";
I want to make that string as
@Path("/BankDBRestService/customerExist")
I tried this:
String foo = s.replaceAll("[(](.*)", "");
i am getting output as
@Path
can anyone please provide me the reqular expression to make this work

Tuesday, 10 September 2013

LinkedIn Company Insider Plugin - no results in New Hire/Position Changes tab

LinkedIn Company Insider Plugin - no results in New Hire/Position Changes tab

We need to be able to view entries in these tabs with the Company Insider
Plugin (generated via
https://developer.linkedin.com/plugins/company-insider-plugin). Is there
any reason that it always returns 0 results, whether done by
implementation on a static HTML page, or through the Company Insider
Plugin code generator?
I have read somewhere that LinkedIn does not ever show you someone who is
more than 3 degrees away from you in terms of connection - does this apply
for entries in New Hire and Position Change in the Company Insider Plugin
as well?
Currently I'm trying to write a custom plugin, using the LinkedIn
Javascript API, but I am still getting zero results on both New Hires and
Position Changes. These are the codes I am using:
var url = '/companies/{companyId}/updates?event-type=new-hire';
IN.API.Raw()
.url(url)
.method('GET')
.body(JSON.stringify(body))
.result(function (result) {
console.log(result);
})
.error(function (error) {
console.log(error);
});
var url = '/companies/{companyId}/updates?event-type=position-change';
IN.API.Raw()
.url(url)
.method('GET')
.body(JSON.stringify(body))
.result(function (result) {
console.log(result);
})
.error(function (error) {
console.log(error);
});
Another question I have is regarding the validity of an access token
generated via the Javascript API. I am able to access the access token
using the following code:
IN.ENV.auth.auth_token
However, when I attempt to use it as part of an AJAX request to a LinkedIn
REST API URL, I end up getting a 401 Unauthorized - Invalid access token
error. An example of the URL I would try is:
var data = $.ajax({
type: 'GET',
data: { oauth2_access_token: IN.ENV.auth.oauth_token,
event-type: new-hire },
url: 'https://api.linkedin.com/v1/companies/1636/updates'
This is a business critical requirement, would most appreciate some light
on this. Thanks.

what order does AudioRecord class of Android store the audio samples in?

what order does AudioRecord class of Android store the audio samples in?

If I call the read() method, as
record.read(lin, 0, R_fft);
where lin is a short array of size 256 and R_fft is 8, in what order does
the read() function store the audio samples from MIC in? For instanc, is
it
lin[0] -> oldest sample
..
..
lin[8] -> newest sample
or is it the other way round, that is
lin[0] -> newest sample
..
..
lin[8] -> oldest sample
or do the samples go towards the higher end of the lin[] array, that is
towards, lin[248] to lin[255]?

History of executed query commands in isql

History of executed query commands in isql

I am using IBM-Informix ISQL version 7.50.UC3.
I wanted to know what is the command that can be used to retrieve the
history of executed SQL's in isql.
Ex: say 5 users executed select queries and 3 delete queries. so, I want
to know the exact queries these users have used in isql enviroment

angularJS ng-repeat list items

angularJS ng-repeat list items

You can do this in angularjs
<ul data-ng-repeat="airport in airports">
<li></li>
<li>{{airport.name}}</li>
</ul>
And you get 3 ul with li in them.
How do you do it with one ul?
if I do this:
<li ng-repeat>{{airport.code}}</li>
<li ng-repaet>{{airport.city}}</li>
then I get all the codes, then all the cities.

Output from while loop not working

Output from while loop not working

Apologies for posting about this topic twice today, this one is a
different question. So I am working on a java problem at the moment where
I am creating a program that simulates the old TV quiz show, You Bet Your
Life. The game show host, Groucho Marx, chooses a secret word, then chats
with the contestants for a while. If either contestant uses the secret
word in a sentence, he or she wins $100.00.
My program is meant to check for this secret word.
Here is my code:
import java.util.Scanner;
public class Groucho{
String secret;
Groucho(String secret){
this.secret = secret;
}
public boolean saysSecret(String line){
if(secret.equals(line)){
return(true);
}
else{
return(false);
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Groucho g = new Groucho(line);
while (in.hasNextLine()) {
String guess = in.nextLine();
/*Not sure about these next two lines:
*String answer = g.saysSecret(guess);
*/System.out.println(answer);
}
}
}
When I run it nothing happens. I thought it should be returning true or
false? What I would actually like it to do is if the line contains the
secret word, it prints a message that says "You have won $100" and tells
what the secret word is. Could anyone point me in the right direction?
Many thanks Miles

portrait-landscape-for multiple games in single package

portrait-landscape-for multiple games in single package

Am developing casino games which consist of 12 games in a single
package..In that few games are in landscape mode and other games in
portrait mode. and am using single config file for all the games... the
problem am facing is while switching from one game to other scaling is not
perfect kindly help me to do

equation of the object

equation of the object

I am using ray tracing and at the beginning I assumed a plane surface so I
used the equation of the plane surface which is :
Ax + BY + CZ +d = 0
while A,B and C are the component of the normal vector of the Plane Normal
= [A B C] and using the Ray equation : Ray = Source + t*Direction And then
solve it for t and I can find the intersection points.
My question now that I have function in matlab to read the surface of the
object but the object may not be plane surface and I am getting the data
of the surface [X Y Z] of the surface but I don't know which equation
should I use to find t and then the intersection point. And I even have a
function to give me the normal vector at each point
If you can edit the tags the get the right ones please do it. Any one has
suggestion please.
Thanks

how can achieve constant aspect ratio in the ILSurface plot?

how can achieve constant aspect ratio in the ILSurface plot?

I have scanned through the documentation on the ilnumerics.net but I could
not find any example where it is applied. This is something that is so
important to the visual elements of our application.

Monday, 9 September 2013

How to apply layout template change to many pages?

How to apply layout template change to many pages?

I'm not sure whether this question really belongs on Stack Overflow or
Server Fault. Anyway...
I have a custom layout template (layout.html file) in the WebDAV file
store on WebSphere Portal 8. This template is used by many pages - I guess
about 100 - and I need to make a change to the template and apply it to
all those pages.
To date, the only way I've found to make any Portal page pick up changes
to a layout template is to change that page to a different template then
change it back to the modified original template. This is a ridiculous
solution when many pages use the same template.
Is there any way to make a large number of portal pages pick up changes in
a layout template that they're already using, without manually updating
each page?

Kendo subgrid deletion (with php)

Kendo subgrid deletion (with php)

I use example like this:Tutorial for Kendo and PHP
And I use code in subgrid as in grid:
subDS = new kendo.data.DataSource({
transport: {
read: "data/channelName.php?acc="+e.data.userId,
destroy: {
url: "data/chMove.php",
type: "DELETE",
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
}
}
},
error: function(e) {
alert(e.responseText);
},
schema: {
data: "results",
model: {
id: "channelId"
}
}
});
detailRow.find(".subgrid").kendoGrid({
dataSource: subDS,
columns: [
{
title: "Channel Name", field: "channelname"
},
{
command: ["destroy"], title: "&nbsp;", width: "100px"
}]
});
However, the code isn't fired in server side of PHP code,
I not sure it is client side code wrong or server side?
The read is return:
{"results":[{"channelname":"test"},{"channelname":"5413trret"},{"channelname":"d453"},{"channelname":"test3"},{"channelname":"ter"},{"channelname":"test5"}]}
and userId is in the read of the grid.
The server side(chMove.php) I try to test if it is fired use alert like:
<?php
// determine the request type
$verb = $_SERVER["REQUEST_METHOD"];
echo "<script>alert('"."123"."');</script>";
?>
But the alert never be fired, needless to say I want to get the
parse_str(file_get_contents('php://input'), $request ); later and parse
the $request.
The final goal is delete what user click in the "Delete" button and the
server side can delete it in database.
Any idea about my code? Or is there any other method to do deletion of
subgrid?
Any advice appreciate.