mardi 30 septembre 2014

scrollTop get each pixel


Vote count:

0




When I use the function scrollTop to get the amount of pixels of the top I receive 1, 4, 20,... depending on the speed that I am scrolling.



$(window).scroll(function(){
var position = $(document).scrollTop();
console.log(position);
)};


I am building a site were I need to get each pixel. This because I am checking when a certain position-value is showing. For example:



if(position === 1200){
// do something
}


Now this is not possible with the values I receive of the scrollTop function. Now I'am using this code below which make it possible to calculate each pixel, but this is only working smooth when the site is not to heigh. If the site is more then 3000px of height, it will begin to jitter because it takes to lang to calculate the pixel.



var viewportFirstPosition = $(document).scrollTop();
$(window).scroll(function(){
var inc;

var viewportHeight = $(window).height();
var viewportNewPosition = $(document).scrollTop();

if(viewportNewPosition > viewportFirstPosition){
inc=1;
}
else{
inc=-1;
}

while(viewportFirstPosition !== viewportNewPosition){
viewportFirstPosition += inc;
console.log(viewportFirstPosition); // 1, 2, 3, 4, 5, ...
}
}


Any ideas how I can do it differently? Without the jitter :) Thanks!



asked 1 min ago







scrollTop get each pixel

Filter Results in AngularJS


Vote count:

0




I have ng-click in my view, which is supposed to filter my presented results.



<a role="menuitem" tabindex="-1" href ng-click="itemFilter=itemABCFilter">ABC Filter</a>


All items from ABC are stored in my controller, such as



$scope.itemABC=["Alpha","Beta","Gamma"];


A list of all items in my view come from a $http request I made. No I seek loop through all data.item (my data I obtained from the get request) and find out whether it contains any element of itemABC or can be considered as a substring of any of the elements of itemABC it.



$scope.itemABCfilter=function(data){
for (var j=0; j<$scope.itemABC.length;j++){
if($scope.itemABC[j].search($scope.data[i].name)>-1) return true;
}


Somehow the code above does not filter my results. Do I handle the $http request results not correctly or is the code simply wrong? How would ou do it?


Thanks



asked 1 min ago







Filter Results in AngularJS

Application working on server glassfish?


Vote count:

0




i want make some application which be working on server (Glassfish), specifically it should be executed in loop for x minutes. I think about ftp client that connect to the host, download file and save it into database. Should I use EJB, or maybe something else?



asked 1 min ago







Application working on server glassfish?

AngularJS with MongoDB and Tomcat 7


Vote count:

0




I want to build an UI which will be an interface scripts and save in mongo db. Tomcat 7 is the webserver. Here, problem is that we can use Node.js, Angularjs and Mongodb or Node.js, Angularjs , Java and Spark. But instead, i wanted to use above technologies as they are in requirements. So how start i am not getting. Thanks in advance



asked 1 min ago







AngularJS with MongoDB and Tomcat 7

How to print British Pound Sign £ on Epson TM-T88 receipt printer?

[unable to retrieve full-text content]

I have tried to print pound sign with static as well as ASCII value, but it shows (?) sign in receipt, so is there any other way to print pound sign in receipt?






How to print British Pound Sign £ on Epson TM-T88 receipt printer?

LINQ query to update property of a list


Vote count:

0




I am trying to convert the following code to linq:



for (int i = 0; i < List.Count;i++ )
{
List[i].IsActive = false;
if(List[i].TestList != null)
{
for(int j = 0;j<List[i].TestList.Count;j++)
{
List[i].TestList[j].IsActive = false;
}
}
}


I tried the following query :



(from s in List select s).ToList().ForEach((s) =>
{
s.IsActive = false;
(from t in s.TestList where t == null select t).ToList().ForEach((t) =>
{
t.IsActive = false;
});
});


But i get an error when TestList is null in the list. I am not sure what I am doing wrong here.



asked 2 mins ago







LINQ query to update property of a list

tfs build is getting failed when releasebuild is true


Vote count:

0




I am working on triggering release from TFS build and I have configured Release Management environment for the same.


TFS build is not successful when I make "ReleaseBuild=true". Error count is zero even though the build is getting failed. From some of the articles, I came to know that build agent account should be created as "Release Manager" in RM client. Now Build Agent is running under NETWORK SERVICES account.


I have few doubts:



  1. Do I need to change Build Agent identity to windows identity and create that user as release manager in RM client?

  2. If yes, what are the necessary permissions to be given for that account in both windows and in RM.

  3. If No, how I could create NETWORK SERVICES as “release manager” in RM


Please help me to resolve this road blocking issue.



asked 1 min ago







tfs build is getting failed when releasebuild is true

Create and fill drop-down in JS file


Vote count:

0




I use mvc2, and I have model with data that I need to have in drop-down.


When i making drop-down in View it is not problem I use:



<%: Html.DropDownList("cbDrop", Model.Drop, "", new { @class = "dropdown" })%>


But now I need to fill drop-down in JS file.


First I try to use:



@Html.DropDownList("cbDrop", Model.Drop, "", new { @class = "dropdown" })


After I getting errors I try first to get value of model like:



var model = @Html.Raw(Json.Encode(Model))


But i get error in firebug for @ is illegal character.


Can I dynamically create drop-down in JS file and fill it with model value? Thanx



asked 1 min ago

Frink

163






Create and fill drop-down in JS file

IncompatibleClassChangeError:org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface *.asm.ClassVisitor as super class


Vote count:

0




I am using Spring 4.1 and writing maven modules from scratch. I have 2 service modules A and B and a webapp which makes calls to service A whose implementation is there in module B. Following is the list of Spring jars in my parent pom.



<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>


I got few more issues before encountering this which i resolved. So one of the posts asked to put the below dependencies as well (I dont understand why i have to provide it if spring needed them why its not packaged with it).



<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspect.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspect.version}</version>
<scope>provided</scope>
</dependency>


I got the mentioned issue and one of the posts suggests to exclude the spring-asm which is old and include latest asm-all dependency.



<dependency>
<groupId>asm</groupId>
<artifactId>asm-all</artifactId>
<version>3.3.1</version>
</dependency>


I removed spring-asm dependency add the above. Now i run into the issue where the classes are not compatible. Kindly suggest how can i resolve it.


Thanks in advance



asked 36 secs ago







IncompatibleClassChangeError:org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface *.asm.ClassVisitor as super class

How to create a join_table with a specific table name? (RAILS)


Vote count:

0




I have been given the unenviable task of moving from Postgres to Oracle. (Very very sad. Not my call). When I run rake db:migrate, rails throws an Oracle error ORA-00972: identifier is too long. How can I specify the table_name in the migration so that it is less than the 30 character limit imposed by Oracle?


The following is an example taken from: http://ift.tt/1vvO7C0


and yields a table name: products_categories


class CreateJoinTableProductsCategories < ActiveRecord::Migration def change create_join_table :products, :categories do |t| # t.index [:product_id, :category_id] # t.index [:category_id, :product_id] end end end


I want to do something like this, specifying the join_table name, to yield the join table name of "myjointablename":


class CreateJoinTableProductsCategories < ActiveRecord::Migration def change create_join_table :products, :categories, table_name: :myjointablename do |t| # t.index [:product_id, :category_id] # t.index [:category_id, :product_id] end end end


But it is not liking it very much.... I would appreciate any help.... cheers!



asked 43 secs ago







How to create a join_table with a specific table name? (RAILS)

Interface between 2 java Applications - How to use path to second application


Vote count:

0




I am writing an interface between 2 java applications. Application 1 is built on top of an Eclipse RCP framework, and is the starting point of my interface. The code I am writing is built within a plugin and loaded via an update site into Application 1. (fairly happy with this part).


My issue then is how to reference the 2nd Application from within this plugin.


Currently, for development I have bundled all of the Application 2 JARs into a separate project, and then referenced this bundled project from my development plugins for Application 1. This works inside Eclipse, but has numerous problems when trying to include this as part of the update site. Not least of which is that the JARs don't belong to us, and therefore re-packaging and distributing them is a no-no.


In my deployed environment, I can assume that Application 2 will be installed on the client machine, along with the required JARs, but I don't necessarily know where they will be installed, or what version they will have.


So I see a number of options, but whether they are correct or not I don't have the experience in deploying Java applications to be able to tell.


Options:



  1. Update command line for Application 1 to specify the classpath for JARs for Application 2.

  2. Use Preferences window inside Application 1 (because this is based on Eclipse RCP), and create a customised ClassLoader for the JARs in Application 2.

  3. Create a cut-down version of the bundled JARs for Application 2 and deploy these through the update site (I have been trying this, but have hit the wall again, and can't help feeling there is a better way).


A secondary question for my plugin development is, How can I tell 'nicely' whether Application 2 is configured and installed ? so that I can gracefully exit my plugin, and perhaps give the user a nice message.



asked 27 secs ago







Interface between 2 java Applications - How to use path to second application

Interrupt service routines in java


Vote count:

0




The question may sound a bit weird. I want to have a complete control over my keyboard.In assembly language it is possible by changing the address of the ISR running in the keyboard port.Is it possible in java.How can I find my keyboard port number and how can I redirect the request coming in the keyboard port to my ISR.



asked 48 secs ago







Interrupt service routines in java

Javascript POST to PHP page


Vote count:

0




My goal is to establish where a page was opened via a javascript pop up, and carry a related URTL varialble through to other page(s). Originally I thought I could do this with a URL variable however as java runs client side and php is server side there is no way to verify whether the window is a java windopw especially given the possibility that someone returned on a favorite or bookmark


I originally made a similar post to this however as the idea has evolved and being stuck with the variable in the URL, this may be a better approach


I think I have figured out the basics but the mechanics involve javascript that I am not so familiar with.


Here is what I have in a page right now



<script>
function PopupCenter(pageURL, title,w,h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
</script>

<a onclick="PopupCenter('/customconfig/index.php, 'CustomBuilder1',1080,700);" href="javascript:void(0);"> <img border=0 src = "/images/Animated.GIF"></a>


Now I found this page http://ift.tt/1rDC1Ed


which tells me how to pot a POST in a javascrip with this code



<script>
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
</script>


Of course the advantage of this method is that there is no URL variable when I go to the first page and I can also carry the POST value through all php pages.


My biggest question is how to merge the code for loading the centered javascript window with the code for passing the POST variable, and making them work "happy together"


This means that if someone goes back on a bookmark or favorite the POST value will be NULL, and I can carry that NULL value through the subsequent page(s) as a POST hidden value


Thanks,


Mark



asked 29 secs ago







Javascript POST to PHP page

How can i get the Friends list from Facebook? How to do this one? pls help me.How can i get the names xpath?


Vote count:

0





  1. How can i get the Friends list from Facebook?

  2. How to do this one?

  3. How can i get the names xpath?


  4. pls help me.


    import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver;



    public class FaceBook {
    public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    //driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.get("http://ift.tt/g8FRpY");
    driver.findElement(By.id("email")).sendKeys("example@yahoo.com");
    driver.findElement(By.id("pass")).sendKeys("xxxxxxx");
    driver.findElement(By.id("loginbutton")).click();
    Thread.sleep(2000);
    driver.findElement(By.linkText("FRIENDS")).click();
    driver.findElement(By.linkText("See All Friends")).click();
    /*//Expand the friend list
    While(true);{
    try{
    WebElement seemore= driver.findElement(By.linkText("seemore"));
    seemore.click();
    Thread.sleep(5000);
    }catch(Throwable t){
    System.out.println("Expanded everything");
    break;
    }
    }*/
    WebElement Box = driver.findElement(By.xpath("//* [@id='collection_wrapper_2356318']"));
    List <WebElement> names = Box.findElements(By.xpath("//a[contains(@id=****)]"));
    System.out.println("No. of friends :"+ names.size());
    for (int i=0;i<names.size();i++){
    String frnds = names.get(i).getText();
    if(!frnds.trim().equals("")) {
    System.out.println(frnds);
    }
    }
    driver.findElement(By.linkText("Account Settings")).click();
    driver.findElement(By.xpath("//*[@id='logout_form']/label")).click();
    }
    }




asked 12 secs ago

DSL

14






How can i get the Friends list from Facebook? How to do this one? pls help me.How can i get the names xpath?

Set active menu to current page by clicking any links outside nav menu


Vote count:

0




Both of the following codes are working.



$("li a").filter(function(){ return this.href == location.href.replace(/#.*/, ""); }).parents('nav ul li').addClass("selected");


and



var loc = window.location.href;
$("a").each(function() {
if(this.href == loc) {
$(this).parents('nav ul li').addClass('selected');
}
});


But my problem is you can only add class to links inside nav. Clicking any links outside the div wont add any class. Please take a look on this url and click link outside nav1 or 2.



  1. Which one do you recommend me to use?

  2. How to set a default class to the first li(videos) using jquery when I click any links outside nav area?


Please help me on this. Thank you!



asked 26 secs ago







Set active menu to current page by clicking any links outside nav menu

ThreadPool quitting upon submit


Vote count:

0




As soon as I submit a runnable to the threadExecutor it quits and I can't figure out why. I've traced the code, but to no avail.



ExecutorService threadPool = Executors.newFixedThreadPool(threads); // create thread pool
threadPool.submit(new Multiplier(this.getColumnsOfRow(i), B.getRowsOfColumn(j), C, i, j)); // just quits here

class Multiplier implements Runnable {

Double[] ARow, BCol;
Matrix C;
int insertRow, insertCol;

public Multiplier(Double[] ARow, Double[] BCol, Matrix C, int insertRow, int insertCol) {
System.out.println("We are here!"); // we never get here..
this.ARow = ARow;
this.BCol = BCol;
this.C = C;
this.insertRow = insertRow;
this.insertCol = insertCol;
}

@Override
public void run() {
double sum = 0;
for (int i = 0; i < ARow.length; i++) {
sum += ARow[i]*BCol[i];
}
C.insertValue(insertRow,insertCol,sum);
}
}


Does anyone have any idea why this would be?



asked 32 secs ago







ThreadPool quitting upon submit

I can't set a new attribute to source tag ! , so what?


Vote count:

0




I can't set a new attribute to source tag ! , so what ?



<audio controls autoplay>
<source id="sourc" />
</audio>

$('source').attr("src" , "value"); // doesn't work , why ?


why it doesn't work ?



asked 45 secs ago







I can't set a new attribute to source tag ! , so what?

Header content not displaying in IE6


Vote count:

0




I have used Joomla 3.3 ("tk_responsi_free" template) to build my website. But when I am trying to view it in IE7 the sub menu section getting suppressed by other modules. So I have added little bit of css code in "custom.css" :



#header
{
z-index: 999;
}


This solved my problem in IE7. But now I am not able to view the contents which were written under Header tag in IE6. I have removed the above css code and also used conditional statement. But the problem remains.


Thanks in advance.



asked 1 min ago







Header content not displaying in IE6

first and last row_number


Vote count:

0




I have a table with many different companies, each with a number of orders ranging from only 1 to a possible n


I have used



ROW_NUMBER() OVER (PARTITION BY CompanyName ORDER BY OrderDate) AS Orders


This gives me a sample like below



Comp1 1
Comp2 1
Comp3 1
Comp3 2
Comp3 3
Comp3 4
Comp4 1
Comp4 2
Comp4 3


How do I go through the table and select the first and last record for each company? to end up with:



Comp1 1
Comp2 1
Comp3 1
Comp3 4
Comp4 1
Comp4 3


asked 1 min ago







first and last row_number

What will happen to my old xcode when I download new xcode?


Vote count:

0




The question is in the title already. I have an old XCode. Then there is a software update message on my Mac. It said that there is a newer version of XCode. If I download the new XCode, will my old XCode be deleted? Or I will end up with 2 XCodes?



asked 28 secs ago







What will happen to my old xcode when I download new xcode?

Object Typecasting


Vote count:

0




In the following code:


A tat = new P();


P bat = (P) tat;


Is typecasting tat like so: P bat = (P) tat;


the same as saying: P tat = new P();


Can you also say in theory that: P bat = ( P tat = new P(); )



asked 1 min ago







Object Typecasting

How do i use CGImageRef to loop over parts of an image that is resized in xcode?


Vote count:

0




I am trying to create an effect that looks as if 2 images are woven into each other. So I scaled the first image to be the background and I am looping over the second image using several UIIMageViews on top of the background to give my desired look. This works when I use images that don't need to be scaled to fit and are the size of my display but when I am using UIGraphics to resize the image I am getting a problem where the image loses quality. Any suggestions would be greatly appreciated.



UIImage *bgImage = [UIImage imageNamed:@"1.jpg"];
UIImageView *bgView = [[UIImageView alloc] initWithImage:bgImage];
bgView.contentMode = UIViewContentModeScaleToFill;
bgView.frame = CGRectMake(0,0,CGRectGetWidth(self.view.frame), (CGRectGetWidth(self.view.frame) / bgImage.size.width) * bgImage.size.height);

bgView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.view addSubview:bgView];

UIImage *frontImage = [UIImage imageNamed:@"2.jpg"];
CGSize newSize = CGSizeMake(CGRectGetWidth(self.view.frame), (CGRectGetWidth(self.view.frame)/frontImage.size.width) * frontImage.size.height);
UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);
[frontImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

int count = 0;
int varX = 10;
int varY = 10;

CGFloat width = self.view.frame.size.width;
CGFloat height = self.view.frame.size.height;
CGFloat tileWidth = width / varX;
CGFloat tileHeight = height / varY;

for (int x = 0; x < varX; x++) {
for (int y = 0; y < varY; y++) {

NSLog(@"%f, %f, %f, %f",x*tileWidth, y*tileHeight, tileWidth, tileHeight);

CGImageRef scaledRef = CGImageCreateWithImageInRect(scaledImage.CGImage, CGRectMake(x*tileWidth, y*tileHeight, tileWidth, tileHeight));
UIImage *image = [UIImage imageWithCGImage:scaledRef scale:scaledImage.scale orientation:scaledImage.imageOrientation];
UIImageView *bgx = [[UIImageView alloc] initWithImage:image];
CGImageRelease(scaledRef);

bgx.frame = CGRectMake((x*tileWidth), (y*tileHeight), tileWidth, tileHeight);
bgx.backgroundColor = [UIColor yellowColor];
bgx.contentMode = UIViewContentModeTopLeft;

if(count%2==0){
[self.view addSubview:bgx];
}
count++;
}
count++;
}


asked 37 secs ago







How do i use CGImageRef to loop over parts of an image that is resized in xcode?

Building a logical tree for a custom control


Vote count:

0




I'm working on a control that has an ObservableCollection as one of its DependencyProperties. This property is set as the DefaultProperty for my control, so I can implicitly add items to the collection in XAML by constructing lines similar to the following:



<MyControl>
<MyItem/>
<MyItem/>
<MyItem/>
</MyControl>


As far as I understand, the WPF engine builds the logical tree when it parses through the XAML. Therefore, each MyItem should be a logical child of the MyControl. Conversely, the MyControl should be the logical parent of each MyItem.


Well, apparently there is more to it. Below is the code that I use to define the relationship above. The custom control contains a DependencyProperty for the ObservableCollection and it is backed by a CLR-property.



[ContentProperty("Items")]
public class MyControl : Control
{
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
"Items",
typeof(ObservableCollection<MyItem>),
typeof(MyControl),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, OnItemsChangedProperty));

[Category("MyControl")]
public ObservableCollection<MyItem> Items
{
get { return (ObservableCollection<MyItem>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}

public MyControl() : base()
{ //Set a new collection per control, but don't destroy binding.
SetCurrentValue(ItemsProperty, new ObservableCollection<MyItem>());
}
}


From with the MyItem (which inherits FrameworkContentElement), I attempt to access its logical parent like so:



if (Parent is FrameworkElement)
{ //Re-Render the parent control.
((FrameworkElement)Parent).InvalidateVisual();
}


To my surprise, the parent control is never re-rendered. This is because the MyItem.Parent property is null. Why is this?


How can I instruct the WPF engine to know that MyControl should be the logical parent to MyItem?



asked 22 secs ago







Building a logical tree for a custom control

Overlapping Perlin Noise


Vote count:

0




I have a perlin noise function, and I want to use it to pick biomes for a map for my game. The problem is that biomes are determined by two factors - average precipitation and average temperature. So, I thought, I'd just make two perlin noise functions and overlap them.


The issue now is that biomes do not encompass all possible precipitation temperature combinations. For example, there is no biome with high precipitation and low temperature, as shown in this picture.



How can I still use perlin noise but never reach the areas that aren't covered by biomes?



asked 34 secs ago







Overlapping Perlin Noise

Copy offset to notepad when hex value is "xx" in .bin file


Vote count:

0




So I have a .bin file (16.5mb) that I would like to search through finding Hex values that I will pre-define in a textbox and copy the offset where the hex value is located into notepad for later use. And repeat this for the entire file.


So far I can load the .bin with button1, textbox1 and OFD. I would rather search only for the Hex value I specify with textbox2 and button2. If it is easier or faster to search for bytes I can enter the hex in as byte equivalent.


I found this which is similar= VB.Net Get Offset Address but no luck configuring it to my needs. Searching for Hex values would be ideal. This looks helpful however.



Dim pos As Integer = 0 ' <== THIS IS THE OFFSET
Dim length As Integer = reader.BaseStream.Length
Do While pos < length
' Read the integer.
Dim value As Byte = reader.ReadByte()
If value = CByte(&H41) Then
Return pos
Exit Do
End If
' Add length of integer in bytes to position.
pos += 1
Loop
End Using


Can someone suggest a good way of accomplishing this? Please and Thank you.



asked 1 min ago







Copy offset to notepad when hex value is "xx" in .bin file

Remove illegal chars from multilanguage string


Vote count:

0




How can I remove illegal chars from multilanguage string, such as <>'"?* etc.?


I can't just use



$allow = "/[^abcdefghijklmnopqrstuvwxyz0123456789-]+/";
$q = preg_replace($allow, "", $q);


I need this to use on a full name field with multilanguage support.



asked 49 secs ago







Remove illegal chars from multilanguage string

Find the time difference between two consecutive rows in the same table in sql


Vote count:

0




Let me tell ya, so much help here, my skill set is rapidly increasing. Thank you all for your help!!


MSSMS 2008 R2 Database is SQL 2008 SP1


However, I'm stuck. I've looked for an answer, but can't seem to find subtracting time in the same table from two different rows of the same table that fits. I'm having a difficult time with the following query. In the table below, I want to differentiate the TimeOut from one row to the TimeIn of the next row. Consider in the following table of finding the difference in minutes between the TimeOut in Row 1 (10:35am) and the TimeIn in Row 2 (10:38am).


Table 1: TIMESHEET



ROW EmpID TimeIn TimeOut
1 138 2014-01-05 10:04:00 2014-01-05 10:35:00
2 138 2014-01-05 10:38:00 2014-01-05 10:59:00
3 138 2014-01-05 11:05:00 2014-01-05 11:30:00


Expected results



ROW EmpID TimeIn TimeOut Minutes
1 138 2014-01-05 10:04:00 2014-01-05 10:35:00
2 138 2014-01-05 10:38:00 2014-01-05 10:59:00 3
3 138 2014-01-05 11:05:00 2014-01-05 11:30:00 6
etc
etc
etc


Basically, I need to differentiate the times in the query to show how long employees where on break. I've tried doing a join, but that doesn't seem to work and I don't know if OVER with PARTITION is the way to go, because I cannot seem to follow the logic (Yeah, I'm still learning). I also considering two temp tables and comparing them, but that doesn't work when I start changing days or employee ID's. Finally, I am thinking maybe LEAD in an OVER statement? Or is it just simple to do a DATEDIFF with a CAST?


Any help would be greatly appreciated!! Thanks in advance.



asked 1 min ago







Find the time difference between two consecutive rows in the same table in sql

HAML form wont submit


Vote count:

0




I'm having trouble with a haml form for stripe. I can't get my submit to function. This is my first time building a from wit haml, any input will help. I'm not even sure if my fields are set up correctly to save into the database.



.container
%section#checkout-form
= form_tag("", method: "POST", id: "payment-form") do
.row
#checkout-form.small-8.columns
.row
#name-form.small-12.columns
.row
.small-6.columns
= label_tag :frist_name, "First Name"
= text_field_tag :name => "First Name", :placeholder => "John", :type => "text"
.small-6.columns
= label_tag :Last_Name, "Last Name"
= text_field_tag :name => "Last Name", :placeholder => "Smith", :type => "text"
.row
.small-12.columns
= label_tag :Email, "Email"
= text_field_tag :name => "Email", :placeholder => "fan@bandfund.com", :type => "text"
#address-info.small-12.columns
.row
.small-12.columns
= label_tag :Address1, "Address 1"
= text_field_tag :name => "Address1", :placeholder => "123 Street", :type => "text"
.row
.small-12.columns
= label_tag :Address2, "Address 2"
= text_field_tag :name => "Address2", :placeholder => "Apartment/Suite", :type => "text"
.row
.small-6.columns
= label_tag :City, "City"
= text_field_tag :name => "City", :placeholder => "Joplin", :type => "text"
.small-6.columns
= label_tag :State, "State"
= text_field_tag :name => "State", :placeholder => "Missouri", :type => "text"
.row
.small-6.columns
= label_tag :ZIP, "ZIP"
= text_field_tag :name => "ZIP", :placeholder => "64804", :type => "text"
.small-6.columns
= label_tag :Country, 'Country'
= text_field_tag :name => "Country", :placeholder => "USA", :type => "text"
#billing-info.small-12.columns
.row
.small-6.columns
= label_tag :Credit_Card_Number, "Credit Card Number"
= text_field_tag :name => "Credit Card Number", :placeholder => "1234 5678 9055 5555", :type => "text"
.small-3.columns
= label_tag :Month, "Month"
= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month", class: 'minilabel', "data-stripe" => 'exp-month'}
.small-3.columns
= label_tag :Year, "Year"
= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year", "data-stripe" => 'exp-year'}
.row
.small-6.columns
= label_tag :Security_Code, 'Security Code'
= text_field_tag :name => "Security Code", :placeholder => "123", :type => "text"
.small-6.columns
= label_tag :Billing_ZIP, 'Billing ZIP'
= text_field_tag :name => "Billing ZIP", :placeholder => "64804", :type => "text"
/ Form Side
#checkout-info.small-4.columns
/ Info Side
%img#cards-image{:alt => "", :src => image_path("cards.svg")}/
.hr-with-margin
.reward
%h4 $25 Per Month
%h5 21 Supporters
%p I'm in a car with Kevin.
%a.button.button-green{:href => "#"} Pledge
/ row
.row.pad-top
.small-12.columns
%submit.button.button-green{type: "submit"} Submit Payment


Thanks in advanced.



asked 2 mins ago







HAML form wont submit

Make JavaScript event handler depend on AJAX response


Vote count:

0




A JavaScript beginner here :) I am trying to write a Web photo viewer where faces would be marked on the photos. To switch between photos, I'd like to use AJAX. My PHP script returns the name of the picture file and the coordinates of faces (x, y, radius) in the form of a JSON string, e.g.



{"filename":"im1.jpg","faces":[{"x":129,"y":260,"radius":40},{"x":232,"y":297,"radius":40}]}


I want to draw circles on a canvas, based on faces, once the mouse is over the photo. Therefore I created a listener for the mouseover event. The problem is that if I add the listener after the AJAX call, the canvas gets multiple listeners and keeps drawing circles from the previous photos. So it looks like the handler needs to be defined in advance. But then I am struggling to pass the AJAX response to it. How could I achieve it?


My HTML code so far looks like this:



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<canvas id="canvas" width="100" height="600"
style="background-size: 100% 100%; border: 1px solid #FF0000;"></canvas>
<script>
var image = new Image();
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

function loadXMLDoc() {

var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var ajaxData = JSON.parse(xmlhttp.responseText);
image.src = ajaxData.filename;
image.onload = function() {
canvas.width = Math.round(canvas.height / image.height * image.width);
canvas.style.backgroundImage = "url('" + image.src + "')";
}
var faces = ajaxData.faces;
canvas.addEventListener('mouseout', function(evt) {
context.clearRect(0, 0, canvas.width, canvas.height);
console.log("Canvas cleared");
}, false);

canvas.addEventListener('mouseover', function(evt) {
console.log("Canvas entered");
console.log("Faces to mark: " + faces.length);

for (i = 0; i < faces.length; i++) {
context.beginPath();
context.arc(faces[i].x, faces[i].y,
faces[i].radius, 0, 2 * Math.PI);
context.strokeStyle = "#00BBBB";
context.lineWidth = 1;
context.stroke();
}
}, false);

}
}
xmlhttp.open("GET", "get_data.php", true);
xmlhttp.send();
}
</script>

<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>


asked 33 secs ago

texnic

662






Make JavaScript event handler depend on AJAX response

Model View Controller (MVC) - how to apply in PHP? can't figure out how to use a controller for PHP


Vote count:

0




I have an assignment to create a login & registering etc system. The solution must follow MVC architechture. My question is:


How can you use a Controller in PHP? I can't see how because there's no way to call specific functions in the controller from a form, the form action must be a php file. Since the form action must be a php file, I can't choose which function to execute, unless I use ifs to find the right function to execute. But that doesn't seem like a good solution.



asked 2 mins ago







Model View Controller (MVC) - how to apply in PHP? can't figure out how to use a controller for PHP

Named Query in Siena


Vote count:

0




We've a requirement for custom search. We have a set of Models and are using a generic DAO. Currently, JDBC is used for this custom search alone to create the statement/query and get the result. A custom ResultSetMapper is used to map the result set to appropriate Model object.


Is there a way in siena to do this ?


Is it possible in siena to have Named Queries ?



asked 1 min ago







Named Query in Siena

To set or not to set the proxy?


Vote count:

-1




I am facing a dilemma:


For unknown reasons, my Ubuntu 14.04 requires a proxy for updating the system software. Otherwise, it just hangs there. Some discussions about this are here.


On the other hand, in order to run my Google App Engine SDK, no proxy is supposed to be set. There are also some discussions here.


Pretty odd situation and I have no idea how to deal with this. Could somebody explains why Ubuntu has to have a proxy for system software update? Is there a solution for such a dilemma?



asked 2 mins ago







To set or not to set the proxy?

Accessing message.properties works in development but not when deployed


Vote count:

0




The following code works fine when deployed locally in a dev environment from a controller (using run-app). It's used to create a JavaScript object with all messages in the current language.



class LocaleController {
private Map<String, String> getMessages() {
// This is the line in question, the rest is just context
def bundle = ResourceBundle.getBundle("grails-app/i18n/messages");
def map = [:]
bundle.keys.each { msg ->
map[msg] = message(code: msg)
}
return map
}

def index() {
header("Cache-Control", "public, max-age=31536000")
render(view: "index", model: [messages: getMessages()], contentType: "text/javascript")
}
}


However, when this is run from a deployed server, I get the following error message



errors.GrailsExceptionResolver - MissingResourceException occurred when processing request: [GET] /compose/locale/index Can't find bundle for base name grails-app/i18n/messages, locale en_US. Stacktrace follows: java.util.MissingResourceException: Can't find bundle for base name grails-app/i18n/messages, locale en_US at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499) at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1322) at java.util.ResourceBundle.getBundle(ResourceBundle.java:1028) at com.accelrys.compose.app.LocaleController.getMessages(LocaleController.groovy:13) at com.accelrys.compose.app.LocaleController.index(LocaleController.groovy...



I would have preferred not to read the file directly, so I tried http://ift.tt/1uZSrqH which uses http://ift.tt/1rq4K1K but that page has been offline for the past 10 days.


I also tried following the steps in How can I create a map with all i18n-messages in Grails but it wouldn't use my customized message source, I copied the answer verbatim (clean/comile/run-app) but it was still using PluginAwareResourceBundleMessageSource instead of ExtendedPluginAwareResourceBundleMessageSource


Any suggestions on what else I can try?



asked 1 min ago







Accessing message.properties works in development but not when deployed

Getting value from XML


Vote count:

0




This is a small part of XML.



wind_gust_mph>3.0/wind_gust_mph>

wind_kph>1.6/wind_kph>

wind_gust_kph>4.8/wind_gust_kph>


I retrieved it from http://ift.tt/1rBQCS1


The below is my code:



public MyWeather parseWeather(Document srcWunderGroundDoc){

MyWeather myWeather = new MyWeather();
Node windGust = srcWunderGroundDoc.getElementsByTagName("wind_gust_mph").item(0);
myWeather.gust = windGust.getAttributes().getNamedItem("wind_gust_mph").getNodeValue().toString();


}


When I tried to run my app and it crashed. Can someone show me how to get three tags above?






asked 1 min ago







Getting value from XML

How to execute this python script via jquery or php


Vote count:

-1




I need to execute this script, either via jquery or php. And I have no idea how to do it.


I tried to add the script and run it in browser and it says 500 Internal server error. I have added 755 file permission.


Thanks in adv.



asked 24 secs ago







How to execute this python script via jquery or php

Partitioning wide rows in Spark / Cassandra


Vote count:

0




Let's assume we have a Cassandra cluster with RF = N and a table containing wide rows.


Our table could have an index something like this: pk / ck1 / ck2 / ....


If I create an RDD from the table as follows:



val wide_row = sc.cassandraTable(KS, TABLE).select("c1", "c2").where("pk = ?", PK)


I notice that one Spark node has 100% of the table and the others have none. I assume this is because the spark-cassandra-connector has no way of breaking down the query token range into smaller sub ranges because it's actually not a range -- it's simply the hash of PK.


At this point we could simply call redistribute(N) to spread the data across the Spark cluster before processing, but this has the effect of moving data across the network to nodes that already have the data locally in Cassandra (remember RF = N)


What we would really like is to have each Spark node load a subset of the wide row locally from Cassandra.


One approach which came to mind is to generate an RDD containing the list of all values of the first cluster key (ck1) when pk = PK. We could then use mapPartitions() to load a slice of the wide row based on each value of ck1.


Assuming we already have our list values for ck1, we could write something like this:



val ck1_list = .... // RDD

ck1_list.repartition(ck1_list.count().toInt) // create a partition for each value of ck1

val wide_row = ck1_list.mapPartitionsWithIndex(f)


Within the partition iterator, f(), we would like to call another function g(pk, ck1) which loads the row slice from Cassandra for row key pk and column ck1. We could then apply flatMap to ck1_list so as to create a fully distributed RDD of the wide row without any shuffing.


So here's the question:


Is it possible to make a CQL call from within a Spark task? What driver should be used? Can it be set up only once an reused for subsequent tasks?


Any help would be greatly appreciated, thanks.



asked 1 min ago







Partitioning wide rows in Spark / Cassandra

Show image in legend highchart for symbol


Vote count:

-1




How can i show image in legend in Highchart. Adding sample screen shot for sameenter image description here



asked 29 secs ago

Rutu

25






Show image in legend highchart for symbol

Single Method Web Service - Bad idea?


Vote count:

0




There has been some debate around a web service for a project. A few of the old school developers think a single method which accepts a generic object (a JSON string containing a method name and data which be serialized into different objects) is a good way of doing it. It'll work...but feels completely wrong.


Personally, I think this completely goes against the grain of a service and further down the line will spell trouble and headaches as the project grows/changes. I would prefer to go down a RESTful route or standard service method verb of "GetCustomerById", giving a Separation of Concern. Plus if we ever expose the service, the method names will mean something to external consumers.


The generic method touted will work perfectly fine, but I feel it just goes completely against the principle of SOA and services. Plus, I feel like I'm losing a battle against some old school ways of thinking - "it works though".


Are there any other pitfalls I can put forward to show that this will be a bad idea in the long run? I'm a advocate of patterns and practices, which can fall on deaf ears. Any pros and cons I can use would be appreciated.



asked 1 min ago







Single Method Web Service - Bad idea?

How to add new object of model in a foreign controller


Vote count:

0




I am rather new to Rails.


I am working on a profile-page for a User. The show view is divided into partials. The thing about my modelling structure is, that a User can have a Skill. But the User model itself does not have a Skill related column, so all Skill entries are saved in the Skill model.


So, my question is, how can I include a partial into the User show view, that contains a simple add Skill form (name needed only), which saves that Skill into its own table and adds it to the others collection of User.skills?



asked 1 min ago







How to add new object of model in a foreign controller

VBA Outlook item.find method not working on subject property


Vote count:

0




Please see the code below



Dim taskItems As Outlook.items, similarTaskItems As Outlook.items
Dim Item As Variant, similarItem As Variant, finalItem As Variant
Dim int_count As Integer
Dim str_tIsortProp As String
str_tIsortProp = "[CreationTime]"
Set taskItems = olToDoFldr.items

taskItems.Sort str_tIsortProp, OlSortOrder.olAscending

For Each Item In taskItems
Set similarTaskItems = taskItems.Find("[Subject]='" & Item.Subject & "'")

If similarTaskItems.Length > 1 Then
similarTaskItems.Sort str_tIsortProp, OlSortOrder.olAscending
For int_count = similarTaskItems.Length - 1 To 0 Step -1
If int_count = 0 Then
Set finalItem = similarTaskItems(int_count)
Else
If Not finalItem Is Nothing Then
finalItem.Body = finalItem.Body & vbCrLf & similarTaskItems(int_count).Body
similarTaskItems(int_count).Delete
End If
End If
Next
End If

Next Item


When I run this code the find method is suppose to return at least 1 item but it returns nothing. What am I missing?



asked 38 secs ago







VBA Outlook item.find method not working on subject property

PDO, output all data from a table


Vote count:

0




I have been trying to output data from a db table but I can't seem to do it, it doens't show up no matter what I do. I tried using foreach but no dice. This code was taken from a phpacademy tutorial and I am trying to modify it by adding a bit of functionality like being able to gather all data from the database using pdo



$bgItems = DB::getInstance()->getAll('background_image');

echo '<pre>', var_dump($bgItems), '</pre>';

foreach($bgItems as $bgItem) {
echo $bgItem;
}


This is what the DB class looks like with the method i'm trying to implement: public function query($sql, $params = array()) {



$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}

if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}

return $this;
}

public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');

$field = $where[0];
$operator = $where[1];
$value = $where[2];

if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}

else {
$sql = "{$action} FROM {$table}";
if(!$this->query($sql)->error()) {
return $this;
}
}

return false;
}

public function getAll($table) {
return $this->action('SELECT *', $table);
}


And this is the output I get when trying to view the data retrieved using var_dump, which obviously looks like a complicated array.



object(DB)#3 (5) {
["_pdo":"DB":private]=>
object(PDO)#4 (0) {
}
["_query":"DB":private]=>
object(PDOStatement)#8 (1) {
["queryString"]=>
string(30) "SELECT * FROM background_image"
}
["_error":"DB":private]=>
bool(false)
["_results":"DB":private]=>
array(3) {
[0]=>
object(stdClass)#7 (2) {
["id"]=>
string(1) "1"
["name"]=>
string(28) "4ee269991861331957002e21.jpg"
}
[1]=>
object(stdClass)#9 (2) {
["id"]=>
string(1) "2"
["name"]=>
string(36) "22769-interesting-cat-meme-rv31.jpeg"
}
[2]=>
object(stdClass)#10 (2) {
["id"]=>
string(1) "3"
["name"]=>
string(50) "10645322_300758350130075_5393354656605964412_n.jpg"
}
}
["_count":"DB":private]=>
int(3)


}



asked 13 secs ago







PDO, output all data from a table

How to import csv which have lines that are ends with separate character?


Vote count:

0





11110|2005001|abc|apple|00|good|fine|2|||||0|||go|stop||20100520|



Above is an example of csv data.


I'm trying to import a csv into database table. But every line of the csv ends with separate character '|'.


I think that is why keep failing to import data.


I chose options like this :



partial import : uncheck;
format of imported file : csv
option - fields terminated by : |
option - fields enclosed by by :
option - field escaped by : \
option - lines terminated by : auto
option - column names :


How can I import these csv files into db?


Can not delete the '|' at the end of the line.


Because there are more than 400,000 lines in csv file.


And I don't know regular expression and some of lines are ends with '|||' like this;;



11110|2005001|abc|apple|00|good|fine|2|||||0|||go|stop|||




asked 35 secs ago







How to import csv which have lines that are ends with separate character?

smack failed to login on gtalk


Vote count:

0




I'm using smack 4.0.4 and trying to establish a connection with gtalk server but without any success. connection.getHost() and connection.getUser() returns null . Here is my code



ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
XMPPTCPConnection connection = new XMPPTCPConnection(connConfig);

try {
connection.connect();
System.out.println("Connected to " + connection.getHost());
} catch (XMPPException ex) {
//ex.printStackTrace();
System.out.println("Failed to connect to " + connection.getHost());
System.exit(1);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login("user@example.com", "password");
System.out.println("Logged in as " + connection.getUser());

Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);

} catch (XMPPException ex) {
//ex.printStackTrace();
System.out.println("Failed to log in as " + connection.getUser());
System.exit(1);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


and the output is



Connected to null
Failed to log in as null


asked 39 secs ago

Doua Beri

1,054






smack failed to login on gtalk

Need to handle the random pop (Feedback popup) using java in selenium webdriver


Vote count:

0




Feedback pop up generates random in my application.


I can't go ahead without closing this pop up. Can somebody tell me how we can handle this situation?



asked 1 min ago







Need to handle the random pop (Feedback popup) using java in selenium webdriver

Angular service calling another service


Vote count:

0




I'm making a simple Angular app to manage incomes. The incomes come from projects that I store in json (for testing purpose).


So, basically, I use a service in Angular to get this json and I would like to have another service that call Projects service and filter the incomes of each projects.


Here's the code :



facturateApp.service('Projects', function($http){


var Projects = {
async: function() {

var promise = $http.get('base.json').then(function (response) {
return response.data;
});
return promise;
}
};
return Projects;


});

facturateApp.service('Incomes', function(Projects){
var incomes = [];
Projects.async().then(function(d) {
var projects = d;

angular.forEach(projects, function(project){

if(typeof(project.account.accountAmount) == 'number' && project.account.accountAmount > 0){
var newIncome = {};
newIncome.projectName = project.projectName;
newIncome.clientName = project.clientName;
newIncome.typeIncome = "Accompte";
newIncome.amount = project.account.amountAccount;
newIncome.date = project.account.accountDate;
newIncome.notes = project.account.accountType;
incomes.push(newIncome);


}



});
angular.forEach(projects, function(project){


if (typeof(project.total.totalAmount) == 'number' && project.total.totalAmount > 0){
var newIncome = {};
newIncome.projectName = project.projectName;
newIncome.clientName = project.clientName;
newIncome.typeIncome = "Accompte";
newIncome.amount = project.total.totalAmount;
newIncome.date = project.total.totalDate;
newIncome.notes = project.total.totalType;
incomes.push(newIncome);


}


});

});
console.log(incomes); // still returns [];
return incomes;

});


My problem is that the last log returns an empty array. I probably know why : incomes is returned before Projects.async().then(function(d) is executed.


But I don't know wait for this function to be executed before returning incomes in a service that call another service...


Any help ?



asked 1 min ago







Angular service calling another service

Why? crashing when using condition (startsWith) with mimeType


Vote count:

-1





public class HelperUtil {

static int iconRes = R.drawable.unknown;

public static Bitmap getNestedIcon(Context context, String path) {

String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
if (type.startsWith("image")) { //crashing here
return BitmapFactory.decodeResource(context.getResources(),
R.drawable.image);
} else if (type.startsWith("audio")) { //crashing here
return BitmapFactory.decodeResource(context.getResources(),
R.drawable.audio);
} else if (type.startsWith("video")) { //crashing here
return BitmapFactory.decodeResource(context.getResources(),
R.drawable.video);
} else { //not crashing
return BitmapFactory.decodeResource(context.getResources(),
iconRes);
}
} else { //not crashing
return BitmapFactory
.decodeResource(context.getResources(), iconRes);
}

}
}


I am trying to list file with proper icon but when I used if(type.startsWith) condition it always crashing activity...I don't understand what's going on where I take wrong move? please help



asked 3 mins ago







Why? crashing when using condition (startsWith) with mimeType

How do I get the phone owner's full name through AccountPicker?


Vote count:

0




I need both the phone owner's name and email.


I successfully obtained the name through using ContactsContract.Profile (how to get firstname and lastname of Android phone owner?), but I wasn't able to obtain an email. It is possible to get the email, but it isn't 100% that you'll get any data whatsoever (so even getting the name isn't 100%).


Hence, I'm using AccountPicker, AccountManager & the Google Play Services API to try to get it. That being said, I understand that this method doesn't guarantee getting the email or name either, but I'd at least like to know how to get the name. The following is how I got the email:



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_register);
int REQUEST_EMAIL_CODE = 1;

try {
Intent intent = AccountPicker.newChooesAccountIntent(null, null,
new String[] { "com.google" }, false, null, null, null, null);
startActivityForResult(intent, REQUEST_EMAIL_CODE);
} catch (ActivityNotFoundException e) {
//handle error here
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
String userEmailAddress = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
}
}


I'm not sure how I would obtain the name. I've tried replacing AccountManager.KEY_ACCOUNT_NAME with different things, but nothing yielded the result and usually I got an error. Maybe now that I have the email, there is a way to get the name from using it some key?



asked 36 secs ago

David

786






How do I get the phone owner's full name through AccountPicker?

UIActivityViewController for iOS8 issue


Vote count:

1




I have issue when i open Email sheet from UIActivityViewController controller in ios8 then i attached array in it but it doesn't appear while opening the Mail


here message is String Message but it not appear in Mail sheet ? Here's what i have tried !!



NSMutableString* sub = [NSMutableString string];
[message appendFormat:@"\n"];
[sub appendString:@"Item Id : "];
[sub appendString:item.item_id];

UIImage *img = self.thumbnailImageView.image;

NSMutableArray *actItems = [[NSMutableArray alloc] init];
[actItems addObject:message];
[actItems addObject:sub];
if(img != nil)
{
[actItems addObject:img];
}

UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:actItems
applicationActivities:nil];

activityViewController.excludedActivityTypes = @[UIActivityTypePostToFacebook,
UIActivityTypePostToTwitter,
UIActivityTypeAirDrop];

[self.navigationController presentViewController:activityViewController
animated:YES
completion:^{}];

[activityViewController setValue:sub forKey:@"subject"];
activityViewController.popoverPresentationController.sourceView = parentView;


asked 2 mins ago







UIActivityViewController for iOS8 issue

Where clause in EF


Vote count:

0




we have 4 entity , Bills, BillDetails ,Products, ProductGroups


what i want to do is something like this



var qry = from bill in ctx.Bills
join billDetail in ctx.BillDetails on bill.Id equal billDetail.Bill_Id
join product in ctx.Products on billDetail.Product_Id equals product.Id
join productGroup in ctx.ProductGroups on product.ProductGroup_Id equals productGroup.Id
where
productGroup.Id == 113
select bill;


the problem is if we disable lazy loading the returnded bill dos not contains BillDetail entity, we have to return it explicitly as anonymous object


is there any way to convert it to something like this ?



var qry = ctx.Bills
.Include("BillDetails")
.Include("BillDetails.Products")
.Include("BillDetails.Products.ProductGroup")
.where(s=>s.BillDetails.Products.ProductGroup.Id == 113);


asked 50 secs ago







Where clause in EF