问:
Apply ksmooth to time series
I have the following problem:

I have a data frame "test" that looks more or less like this:

```<code>Date         return     price      vol
20100902     0.3        15         8.5
20100902     0.4        17         8.6
20100902     0.6        19         8.7
.....
20100903     0.2        13         8.2
20100903     0.4        17         8.6
20100903     0.8        21         9.0
.....
</code>```

So I have given values for each date (10 per day). What I would like to do now is apply ksmooth() on each date, so e.g. ksmooth(return, price, n.points = 50) for each date. This should give me 50 observations for each date. In addition, I would like a time stamp for the interpolated values. So the resulting frame should like

```<code>Date         return     price
20100620     0.3        15
20100620     0.31       15.2
20100620     0.32       15.3
20100620     0.4        17
20100620     0.6        19
.....
20100621     0.2        13
20100621     0.21       13.1
20100621     0.22       13.2
20100621     0.4        17
20100621     0.8        21
etc.
</code>```

with 50 observations per day.
So here is what I'm looking for: take the first 10 observations (e.g. date 1 = 20102006, interpolate and put a time stamp on the interpolated values (20100620). Then, take second 10 observations (date = 20100621), interpolate and put a time stamp on the interpolated values (20100621) and so on.

I'm quite new to R, but this is what I tried. I thought of using the zoo() function to that. Before implementing anything, I wanted to make my date entries unique, so I just added hours to each entry

```<code>test <- read.zoo("test.txt", format = "%Y%m%d")
test <- zoo(test, as.POSIXct(time(test)) + 1:26)
</code>```

There probably is something wrong with that, because R complained.
Then I thought of using the rollapply() function.

```<code>roll.test <- rollapply(test, 10, FUN = function(x,y) ksmooth(test$return,
+ test$price, "normal", bandwidth = 20, n.points = 50) )
</code>```

Unfortunately the result is very confusing. And the by.column = FALSE demand does not work.

I would very appreciate some help. It does not have to build upon my "trial version" at all.
Thank you very much
Dani

My data looks like this:

```<code>"date" "days" "return" "price"
"66" 20100620 91 0.18 1389.373
"67" 20100620 91 0.19 1370.57
"68" 20100620 91 0.19 1353.122
"69" 20100620 91 0.19 1336.291
"70" 20100620 91 0.20 1319.774
"71" 20100620 91 0.20 1303.341
"72" 20100620 91 0.21 1286.656
"326" 20100621 91 0.18 1386.28
"327" 20100621 91 0.18 1367.694
"328" 20100621 91 0.19 1350.375
"329" 20100621 91 0.19 1333.615
"330" 20100621 91 0.20 1317.164
"331" 20100621 91 0.20 1300.783
"332" 20100621 91 0.21 1284.113
</code>```

答:
Problem is that the ksmooth function will return a list, and those lists are saved as that by rollaplly. By the way, I don't think you even want to use rollaplly, as that does not do this for each date but "rolls" over the dataframe. I believe from your explanation that is not the desired behaviour.

I couldn't really work it out using a zoo object, as that one is quite restrictive. Maybe somebody else will show you that. You can construct that dataframe using the ddply function from the plyr package :

```<code>tt <- ddply(test,.(Date),
  function(x) {
       as.data.frame(ksmooth(x$return,x$price,"normal",bandwidth=2,n.points=50))
  })
</code>```

tt can then be transformed to a zoo object, using

```<code>tt2 <- zoo(tt, as.POSIXct(tt$Date) + 1:50)
</code>```

Alternatively, you could do it by hand using a bit of list manipulation. again, the resulting tt can be converted by the line above to a zoo object.

```<code>tt <- split(test,test$Date)

tt <- lapply(tt,function(x){
        as.data.frame(ksmooth(x$return,x$price,"normal",bandwidth=2,n.points=50))
      })

tt <- do.call(rbind,tt)
names(tt) <- c("return","price")
tt$Date <- as.Date(gsub("\\.\\d+","",rownames(tt)))
</code>```

Mind you, I used read.table() to construct test :

```<code>zz <- textConnection(
"Date    ,     return ,    price  ,    vol
20100902 ,    0.3  ,      15   ,      8.5
20100902 ,    0.4  ,      17   ,      8.6
20100902 ,    0.6  ,      19   ,      8.7
20100903 ,    0.2  ,      13   ,      8.2
20100903 ,    0.4  ,      17   ,      8.6
20100903 ,    0.8  ,      21   ,      9.0"
)
test <- read.table(zz,header=T,sep=",")
test$Date <- as.Date(as.character(test$Date),format="%Y%m%d")
close(zz)
</code>```

Title: Apply ksmooth to time series

Body:
I have the following problem:

I have a data frame "test" that looks more or less like this:

Date         return     price      vol
20100902     0.3        15         8.5
20100902     0.4        17         8.6
20100902     0.6        19         8.7
.....
20100903     0.2        13         8.2
20100903     0.4        17         8.6
20100903     0.8        21         9.0
.....

So I have given values for each date (10 per day). What I would like to do now is apply ksmooth() on each date, so e.g. ksmooth(return, price, n.points = 50) for each date. This should give me 50 observations for each date. In addition, I would like a time stamp for the interpolated values. So the resulting frame should like

Date         return     price
20100620     0.3        15
20100620     0.31       15.2
20100620     0.32       15.3
20100620     0.4        17
20100620     0.6        19
.....
20100621     0.2        13
20100621     0.21       13.1
20100621     0.22       13.2
20100621     0.4        17
20100621     0.8        21
etc.

with 50 observations per day.
So here is what I'm looking for: take the first 10 observations (e.g. date 1 = 20102006, interpolate and put a time stamp on the interpolated values (20100620). Then, take second 10 observations (date = 20100621), interpolate and put a time stamp on the interpolated values (20100621) and so on.

I'm quite new to R, but this is what I tried. I thought of using the zoo() function to that. Before implementing anything, I wanted to make my date entries unique, so I just added hours to each entry

test <- read.zoo("test.txt", format = "%Y%m%d")
test <- zoo(test, as.POSIXct(time(test)) + 1:26)

There probably is something wrong with that, because R complained.
Then I thought of using the rollapply() function.

roll.test <- rollapply(test, 10, FUN = function(x,y) ksmooth(test$return,
+ test$price, "normal", bandwidth = 20, n.points = 50) )

Unfortunately the result is very confusing. And the by.column = FALSE demand does not work.

I would very appreciate some help. It does not have to build upon my "trial version" at all.
Thank you very much
Dani

My data looks like this:

"date" "days" "return" "price"
"66" 20100620 91 0.18 1389.373
"67" 20100620 91 0.19 1370.57
"68" 20100620 91 0.19 1353.122
"69" 20100620 91 0.19 1336.291
"70" 20100620 91 0.20 1319.774
"71" 20100620 91 0.20 1303.341
"72" 20100620 91 0.21 1286.656
"326" 20100621 91 0.18 1386.28
"327" 20100621 91 0.18 1367.694
"328" 20100621 91 0.19 1350.375
"329" 20100621 91 0.19 1333.615
"330" 20100621 91 0.20 1317.164
"331" 20100621 91 0.20 1300.783
"332" 20100621 91 0.21 1284.113

Body:
Problem is that the ksmooth function will return a list, and those lists are saved as that by rollaplly. By the way, I don't think you even want to use rollaplly, as that does not do this for each date but "rolls" over the dataframe. I believe from your explanation that is not the desired behaviour.

I couldn't really work it out using a zoo object, as that one is quite restrictive. Maybe somebody else will show you that. You can construct that dataframe using the ddply function from the plyr package :

tt <- ddply(test,.(Date),
  function(x) {
       as.data.frame(ksmooth(x$return,x$price,"normal",bandwidth=2,n.points=50))
  })

tt can then be transformed to a zoo object, using

tt2 <- zoo(tt, as.POSIXct(tt$Date) + 1:50)

Alternatively, you could do it by hand using a bit of list manipulation. again, the resulting tt can be converted by the line above to a zoo object.

tt <- split(test,test$Date)

tt <- lapply(tt,function(x){
        as.data.frame(ksmooth(x$return,x$price,"normal",bandwidth=2,n.points=50))
      })

tt <- do.call(rbind,tt)
names(tt) <- c("return","price")
tt$Date <- as.Date(gsub("\\.\\d+","",rownames(tt)))

Mind you, I used read.table() to construct test :

zz <- textConnection(
"Date    ,     return ,    price  ,    vol
20100902 ,    0.3  ,      15   ,      8.5
20100902 ,    0.4  ,      17   ,      8.6
20100902 ,    0.6  ,      19   ,      8.7
20100903 ,    0.2  ,      13   ,      8.2
20100903 ,    0.4  ,      17   ,      8.6
20100903 ,    0.8  ,      21   ,      9.0"
)
test <- read.table(zz,header=T,sep=",")
test$Date <- as.Date(as.character(test$Date),format="%Y%m%d")
close(zz)


来源: stackexchange

问:
SVG fill="url(#foo)" disappears when SVGs are loaded dynamically
I am loading different SVGs dynamically within a web application built in AngularJS, I am also altering the opacity of layers within the SVGs. These SVGs have some paths with the fill pattern property as such

```<code><defs>
  <pattern id="glass-floral" patternUnits="userSpaceOnUse" width="184" height="272">
    <image xlink:href="../img/glass-floral.png" x="0" y="0" width="184" height="272"/>
  </pattern>
</defs>

<rect x="98.3" y="85.5" fill="url(#glass-floral)" width="365" height="318.8"/>
</code>```

This all works great at first- however under some conditions these # fills simply disappear:

-

Condition 1:
If I were to switch to another SVG and back.

Result::
The # fill is still visible.

-

Condition 2:
If I were to alter the opacity of the element with the # fill.

Result::
The # fill is still visible.

-

Condition 3:
If I were to both switch to another SVG & alter the opacity of the element with the # fill.

Result::
The # fill becomes invisible.

-

This is to mean the styles all appear to still be applied normally in the code- but there is no actual visible fill to be seen. This behaviour exists as far as I can see in Chrome and slightly differently in Safari. Firefox seems to be immune.

I've tried manually flicking the element to another fill and back in the browser to see if perhaps something had cached, no luck. I still think this may somehow be the case, with how the # refers to an inline pattern defined in the <defs> which may not have been loaded yet by the AJAX but the cached CSS rule still floating around.

If it helps matters, both SVGs that I am switching between both have the same <defs> and CSS styling applied. Is perhaps the double case of the defined pattern causing an issue?

答:
After some investigation this appears to be an issue with the browsers (Chrome/Safari possibly others) not being able to keep up with rendering fill: url(#) and opacity for the same element at the same time, at least in cases of multiple/dynamically loaded SVGs.

To solve this, apply your opacity css to a containing  element around the element that has the fill: url(#), example below:

```<code><defs>
  <pattern id="glass-floral" patternUnits="userSpaceOnUse" width="184" height="272">
    <image xlink:href="../img/glass-floral.png" x="0" y="0" width="184" height="272"/>
  </pattern>
</defs>
<style>.opacity-class { opacity: 0.33; }</style>
<g class="opacity-class">
  <rect x="98.3" y="85.5" fill="url(#glass-floral)" width="365" height="318.8"/>
</g>
</code>```

This allows the browser to do both independently and not ruin your pretty pictures.

ContentLicense: CC BY-SA 3.0

Body:
I am loading different SVGs dynamically within a web application built in AngularJS, I am also altering the opacity of layers within the SVGs. These SVGs have some paths with the fill pattern property as such

<defs>
  <pattern id="glass-floral" patternUnits="userSpaceOnUse" width="184" height="272">
    <image xlink:href="../img/glass-floral.png" x="0" y="0" width="184" height="272"/>
  </pattern>
</defs>

<rect x="98.3" y="85.5" fill="url(#glass-floral)" width="365" height="318.8"/>

This all works great at first- however under some conditions these # fills simply disappear:

-

Condition 1:
If I were to switch to another SVG and back.

Result::
The # fill is still visible.

-

Condition 2:
If I were to alter the opacity of the element with the # fill.

Result::
The # fill is still visible.

-

Condition 3:
If I were to both switch to another SVG & alter the opacity of the element with the # fill.

Result::
The # fill becomes invisible.

-

This is to mean the styles all appear to still be applied normally in the code- but there is no actual visible fill to be seen. This behaviour exists as far as I can see in Chrome and slightly differently in Safari. Firefox seems to be immune.

I've tried manually flicking the element to another fill and back in the browser to see if perhaps something had cached, no luck. I still think this may somehow be the case, with how the # refers to an inline pattern defined in the <defs> which may not have been loaded yet by the AJAX but the cached CSS rule still floating around.

If it helps matters, both SVGs that I am switching between both have the same <defs> and CSS styling applied. Is perhaps the double case of the defined pattern causing an issue?

Body:
After some investigation this appears to be an issue with the browsers (Chrome/Safari possibly others) not being able to keep up with rendering fill: url(#) and opacity for the same element at the same time, at least in cases of multiple/dynamically loaded SVGs.

To solve this, apply your opacity css to a containing  element around the element that has the fill: url(#), example below:

<defs>
  <pattern id="glass-floral" patternUnits="userSpaceOnUse" width="184" height="272">
    <image xlink:href="../img/glass-floral.png" x="0" y="0" width="184" height="272"/>
  </pattern>
</defs>
<style>.opacity-class { opacity: 0.33; }</style>
<g class="opacity-class">
  <rect x="98.3" y="85.5" fill="url(#glass-floral)" width="365" height="318.8"/>
</g>

This allows the browser to do both independently and not ruin your pretty pictures.


问:
No Errors in PHP even with display_errors = On in php.ini
I'm setting up a LAMP stack in Vagrant (Ubuntu 16.04, Apache2, PHP7) and PHP isn't showing any errors. I have the following file that should return errors:

```<code>This is a PHP File
<?php thisisnotafunction(); ?>
<?php echo date("ThisIsAnInvalidArgument"); ?>
</code>```

Other Stack Overflow posts (post 1, post 2, post 3) state that I need to change the php.ini file to display errors.

Running $ sudo find / -name php.ini returns:

```<code>/etc/php/7.0/apache2/php.ini
/etc/php/7.0/cgi/php.ini
/etc/php/7.0/cli/php.ini
</code>```

I went into each one of those and set display_errors = On, restarted apache2, but still no errors. However, adding the follow to my index.php file does show errors:

```<code><?php
    error_reporting( E_ALL );
    ini_set( "display_errors", 1 );
    require_once( "sample.php" );
?>
</code>```

index.php now returns:

```<code>This is a PHP File
Warning: require_once(sample.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 6

Fatal error: require_once(): Failed opening required 'sample.php' (include_path='.:/usr/share/php') in /var/www/html/index.php on line 6
</code>```

So clearly my PHP setup knows how to deal with errors.

答: Use php --ini command will show you using Configuration File.

Body:
I'm setting up a LAMP stack in Vagrant (Ubuntu 16.04, Apache2, PHP7) and PHP isn't showing any errors. I have the following file that should return errors:

This is a PHP File
<?php thisisnotafunction(); ?>
<?php echo date("ThisIsAnInvalidArgument"); ?>

Other Stack Overflow posts (post 1, post 2, post 3) state that I need to change the php.ini file to display errors.

Running $ sudo find / -name php.ini returns:

/etc/php/7.0/apache2/php.ini
/etc/php/7.0/cgi/php.ini
/etc/php/7.0/cli/php.ini

I went into each one of those and set display_errors = On, restarted apache2, but still no errors. However, adding the follow to my index.php file does show errors:

<?php
    error_reporting( E_ALL );
    ini_set( "display_errors", 1 );
    require_once( "sample.php" );
?>

index.php now returns:

This is a PHP File
Warning: require_once(sample.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 6

Fatal error: require_once(): Failed opening required 'sample.php' (include_path='.:/usr/share/php') in /var/www/html/index.php on line 6

So clearly my PHP setup knows how to deal with errors.


问:
Second opinion on media streaming architecture
I am currently working on a REST API written in C And i would love to hear a second opinion on my current architecture and how it could be refactored.

So basically it's a audio streaming platform with 2 types of calls - sync and async. We are building it upon janus, more specifically audiobridge plugin.

The problem: Our current janus_audiobridge file has grown too big and its pretty hard to navigate trough it(around 5K lines of code in a single file). So i decided its time for a refactor.

My current solution and problems with it: My idea was to seperate sync and async calls in to 2 seperate files. This way all the stuff for mixing audio and rtp forwards would be in the main janus_audiobridge file and the actual endpoints would be seperate.

But the problem with this approach is that sync/async calls still use the structs and static variables from the main janus_audiobridge file. So i would have to pass them into the handler methods. Which is quite ugly.

How would you architect this kind of system?

Thanks!

答:
A quick-and-dirty solution would be to declare the variable in one of the two sources files as normal and declare it as extern in the other file. This way both files can refer to the same variable but you only have one declaration.

The better way in my opinion is to look at how other libraries handle this. The first argument to function call is usually a pointer to an internal structure that holds all the information you would put in a global. This adds one argument to most functions but is just a pointer. This avoids problems with declaring globals and makes your code reusable for different contexts at once (multiple clients or multiple endpoints) in a single process.


答:
By using t you are coercing your data.frame column into a matrix at which point, the attributes are dropped.

```<code>xy <- data.frame(a = 1:3)
attr(xy, "test") <- "some attribute"

> attributes(xy)
$names
[1] "a"

$row.names
[1] 1 2 3

$class
[1] "data.frame"

$test
[1] "some attribute"

> attributes(t(xy))
$dim
[1] 1 3

$dimnames
$dimnames[[1]]
[1] "a"

$dimnames[[2]]
NULL

> attributes(as.vector(t(xy)))
NULL
</code>```

Title: R - strange behaviour when converting Nx1 data.frame into vector

Body:
Sometimes I have transpose data.frame if I want convert it into vector :

> class(delta_older)
[1] "data.frame"
> dim(delta_older)
[1] 129   1
> head(as.vector(delta_older), 10)
   delta_wiatru
1           -31
2          -112
3          -417
4          -596
5           -13
6           353
7           888
8           359
9           -69
10          520
> head(as.vector(t(delta_older)), 10)
 [1]  -31 -112 -417 -596  -13  353  888  359  -69  520

this behaviour is because of thet the delta_older contain attributes ?

> attributes(delta_older)
$names
[1] "delta_wiatru"

$row.names
  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40
 [41]  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80
 [81]  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
[121] 121 122 123 124 125 126 127 128 129

$class
[1] "data.frame"

delta_older is product od dplyr

Body:
By using t you are coercing your data.frame column into a matrix at which point, the attributes are dropped.

xy <- data.frame(a = 1:3)
attr(xy, "test") <- "some attribute"

> attributes(xy)
$names
[1] "a"

$row.names
[1] 1 2 3

$class
[1] "data.frame"

$test
[1] "some attribute"

> attributes(t(xy))
$dim
[1] 1 3

$dimnames
$dimnames[[1]]
[1] "a"

$dimnames[[2]]
NULL

> attributes(as.vector(t(xy)))
NULL


问:
How to return static value from static query
In sql i need to get my own values.
For example :

Select House from dual ( here i need to return H ) from dual union all
select Build from dual ( here i need to return B) ...

I tired with this but i dont get it as  I want

select '18776' as instanceid from dual union all
select '18775' as instanceid from dual

答:
You can hardcode it like</p>

```<code>Select 'H' from dual
union all
select 'B' from dual
</code>```

Body:
You can hardcode it like

Select 'H' from dual
union all
select 'B' from dual


问:
How to stop sliding if only one
 using anythingSlider(jQuery plugin)?
I'm currently using the anythingSlider plugin, it works totally fine except when there is only one
.

The
s are generated from the database so sometimes there's only one.

However, the anythingSlider plugin still tries to slide through the
s, it works by sliding back to the first slide. Although this doesn't look great.

Does anybody know of a way of stopping it sliding if there's only one
?

-- EDIT --

Hi!

Can anybody else help with this? I've tried the solution by Greg and I've also tried:

```<code>if (banners<1) {
    .anythingSlider({
        startStopped: true,
        buildNavigation: false
        });
    }
</code>```

'banners' is my variable that I'm calling.

And this disables the anythingSlider function altogether.

Help please?!

-- EDIT 2 --

The original code is in the page of the html

```<code><script type="text/javascript">

var banners=[];

banners[0]="http://image.ebuyer.com/customer/promos/UK/AcerAspire5536.jpg";
//banners[1]="http://image.ebuyer.com/customer/promos/2150/banner.jpg";
//banners[2]="http://image.ebuyer.com/customer/promos/UK/257653_FerrariOne_tb20091026.jpg";
//banners[3]="http://image.ebuyer.com/customer/promos/UK/247038_compaq_images/247038_compaq_incentive_banner20090814.jpg"; //added 03/09/2009
//banners[4]="http://image.ebuyer.com/customer/promos/UK/247858-samsung-tv-comp-tb20090817.jpg"; //added 19/08/2009

var bannerLink=[];

bannerLink[0]="http://www.ebuyer.com/product/173536";
//bannerLink[1]="/special/2150";
//bannerLink[2]="/product/172295";
//bannerLink[3]="/compaq-cash-incentive";
//bannerLink[4]="/special/2101";

var bannerAlt=[];

bannerAlt[0]="Acer Aspire 5536";
//bannerAlt[1]="The X5 range for Asus";
//bannerAlt[2]="Acer Ferrari One Laptop";
//bannerAlt[3]="Buy these three products together and claim £75 cashback";
//bannerAlt[4]="Win a Samsung 46in LCV TV";

</script>
</code>```

It's then being actioned by this file: http://image.ebuyer.com/customer/promos/js/topbanners.js

```<code>// function to import css and javascript from external locations
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

// importing css and javascript
loadjscssfile("http://static.ebuyer.com/css/slider.css", "css") ////dynamically load and add this .css file

// setting the variables
var banner = document.getElementById('tehBanner');
var link = document.getElementById('tehLink');

// this function creates the tracking tags
function tracking (x) {
    if (x.indexOf("?")>=0){x+='&tb='+(i+1);}else{x+='?tb='+(i+1);}
    return x
    }

// telling the javascript to display all available variables
for (var i in banners) {
    banner.alt = bannerAlt[i];
    link.href = tracking(bannerLink[i]);
    banner.src = banners[i];
    document.write('<a href="' + bannerLink[i] + '" class="slide-link">' + '<img src="' + banners[i] + '" id="slide-image" alt="' + bannerAlt[i] + '" /></a>');
    }

// remove the original banner
$ ('a#tehLink').parent().remove();

// hide banners to begin with
$('a.slide-link').hide();

/*
    anythingSlider v1.1

    By Chris Coyier: http://css-tricks.com
    with major improvements by Doug Neiner: http://pixelgraphics.us/
    based on work by Remy Sharp: http://jqueryfordesigners.com/

    To use the navigationFormatter function, you must have a function that
    accepts two paramaters, and returns a string of HTML text.

    index = integer index (1 based);
    panel = jQuery wrapped LI item this tab references
    @return = Must return a string of HTML/Text

    navigationFormatter: function(index, panel){
        return index + " Panel"; // This would have each tab with the text 'X Panel' where X = index
    }
*/

(function($){

    $.anythingSlider = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;

        // Set up a few defaults
        base.currentPage = 1;
        base.timer = null;
        base.playing = false;

        // Add a reverse reference to the DOM object
        base.$el.data("AnythingSlider", base);

        base.init = function(){
            base.options = $.extend({},$.anythingSlider.defaults, options);

            // Cache existing DOM elements for later
            base.$wrapper = base.$el.find('> div').css('overflow', 'hidden');
            base.$slider  = base.$wrapper.find('> ul');
            base.$items   = base.$slider.find('> li');
            base.$single  = base.$items.filter(':first');

            // Build the navigation if needed
            if(base.options.buildNavigation) base.buildNavigation();

            // Get the details
            base.singleWidth = base.$single.outerWidth();
            base.pages = base.$items.length;

            // Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
            // This supports the "infinite" scrolling
            base.$items.filter(':first').before(base.$items.filter(':last').clone().addClass('cloned'));
            base.$items.filter(':last' ).after(base.$items.filter(':first').clone().addClass('cloned'));

            // We just added two items, time to re-cache the list
            base.$items = base.$slider.find('> li'); // reselect

            // Setup our forward/backward navigation
            base.buildNextBackButtons();

            // If autoPlay functionality is included, then initialize the settings
            if(base.options.autoPlay) {
                base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
                base.buildAutoPlay();
            };

            // If pauseOnHover then add hover effects
            if(base.options.pauseOnHover) {
                base.$el.hover(function(){
                    base.clearTimer();
                }, function(){
                    base.startStop(base.playing);
                });
            }

            // If a hash can not be used to trigger the plugin, then go to page 1
            if((base.options.hashTags == true && !base.gotoHash()) || base.options.hashTags == false){
                base.setCurrentPage(1);
            };
        };

        base.gotoPage = function(page, autoplay){
            // When autoplay isn't passed, we stop the timer
            if(autoplay !== true) autoplay = false;
            if(!autoplay) base.startStop(false);

            if(typeof(page) == "undefined" || page == null) {
                page = 1;
                base.setCurrentPage(1);
            };

            // Just check for bounds
            if(page > base.pages + 1) page = base.pages;
            if(page < 0 ) page = 1;

            var dir = page < base.currentPage ? -1 : 1,
                n = Math.abs(base.currentPage - page),
                left = base.singleWidth * dir * n;

            base.$wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, base.options.animationTime, base.options.easing, function () {
                if (page == 0) {
                    base.$wrapper.scrollLeft(base.singleWidth * base.pages);
                    page = base.pages;
                } else if (page > base.pages) {
                    base.$wrapper.scrollLeft(base.singleWidth);
                    // reset back to start position
                    page = 1;
                };
                base.setCurrentPage(page);

            });
        };

        base.setCurrentPage = function(page, move){
            // Set visual
            if(base.options.buildNavigation){
                base.$nav.find('.cur').removeClass('cur');
                $(base.$navLinks[page - 1]).addClass('cur');
            };

            // Only change left if move does not equal false
            if(move !== false) base.$wrapper.scrollLeft(base.singleWidth * page);

            // Update local variable
            base.currentPage = page;
        };

        base.goForward = function(autoplay){
            if(autoplay !== true) autoplay = false;
            base.gotoPage(base.currentPage + 1, autoplay);
        };

        base.goBack = function(){
            base.gotoPage(base.currentPage - 1);
        };

        // This method tries to find a hash that matches panel-X
        // If found, it tries to find a matching item
        // If that is found as well, then that item starts visible
        base.gotoHash = function(){
            if(/^#?panel-\d+$/.test(window.location.hash)){
                var index = parseInt(window.location.hash.substr(7));
                var $item = base.$items.filter(':eq(' + index + ')');
                if($item.length != 0){
                    base.setCurrentPage(index);
                    return true;
                };
            };
            return false; // A item wasn't found;
        };

        // Creates the numbered navigation links
        base.buildNavigation = function(){
            base.$nav = $("<div id='thumbNav'></div>").appendTo(base.$el);
            base.$items.each(function(i,el){
                var index = i + 1;
                var $a = $("<a href='#'></a>");

                // If a formatter function is present, use it
                if( typeof(base.options.navigationFormatter) == "function"){
                    $a.html(base.options.navigationFormatter(index, $(this)));
                } else {
                    $a.text(index);
                }
                $a.click(function(e){
                    base.gotoPage(index);

                    if (base.options.hashTags)
                        base.setHash('panel-' + index);

                    e.preventDefault();
                });
                base.$nav.append($a);
            });
            base.$navLinks = base.$nav.find('> a');
        };

        // Creates the Forward/Backward buttons
        base.buildNextBackButtons = function(){
            var $forward = $('<a class="arrow forward">></a>'),
                $back    = $('<a class="arrow back"><</a>');

            // Bind to the forward and back buttons
            $back.click(function(e){
                base.goBack();
                e.preventDefault();
            });

            $forward.click(function(e){
                base.goForward();
                e.preventDefault();
            });

            // Append elements to page
            base.$wrapper.after($back).after($forward);
        };

        // Creates the Start/Stop button
        base.buildAutoPlay = function(){

            base.$startStop = $("<a href='#' id='start-stop'></a>").html(base.playing ? base.options.stopText :  base.options.startText);
            base.$el.append(base.$startStop);
            base.$startStop.click(function(e){
                base.startStop(!base.playing);
                e.preventDefault();
            });

            // Use the same setting, but trigger the start;
            base.startStop(base.playing);
        };

        // Handles stopping and playing the slideshow
        // Pass startStop(false) to stop and startStop(true) to play
        base.startStop = function(playing){
            if(playing !== true) playing = false; // Default if not supplied is false

            // Update variable
            base.playing = playing;

            // Toggle playing and text
            base.$startStop.toggleClass("playing", playing).html( playing ? base.options.stopText : base.options.startText );

            if(playing){
                base.clearTimer(); // Just in case this was triggered twice in a row
                base.timer = window.setInterval(function(){
                    base.goForward(true);
                }, base.options.delay);
            } else {
                base.clearTimer();
            };
        };

        base.clearTimer = function(){
            // Clear the timer only if it is set
            if(base.timer) window.clearInterval(base.timer);
        };

        // Taken from AJAXY jquery.history Plugin
        base.setHash = function ( hash ) {
            // Write hash
            if ( typeof window.location.hash !== 'undefined' ) {
                if ( window.location.hash !== hash ) {
                    window.location.hash = hash;
                };
            } else if ( location.hash !== hash ) {
                location.hash = hash;
            };

            // Done
            return hash;
        };
        // <-- End AJAXY code

        // Trigger the initialization
        base.init();
    };

    $.anythingSlider.defaults = {
        easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
        autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
        startStopped: false,            // If autoPlay is on, this can force it to start stopped
        delay: 3000,                    // How long between slide transitions in AutoPlay mode
        animationTime: 600,             // How long the slide transition takes
        hashTags: true,                 // Should links change the hashtag in the URL?
        buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
        pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
        startText: "Start",             // Start text
        stopText: "Stop",               // Stop text
        navigationFormatter: null       // Details at the top of the file on this use (advanced use)
    };

    $.fn.anythingSlider = function(options){
        if(typeof(options) == "object"){
            return this.each(function(i){
                (new $.anythingSlider(this, options));

                // This plugin supports multiple instances, but only one can support hash-tag support
                // This disables hash-tags on all items but the first one
                options.hashTags = false;
            });
        } else if (typeof(options) == "number") {

            return this.each(function(i){
                var anySlide = $(this).data('AnythingSlider');
                if(anySlide){
                    anySlide.gotoPage(options);
                }
            });
        }
    };

})(jQuery);

// this function wraps the elements in the neccessary tags to work with anything Slider
$ (document).ready(function() {
    $('a.slide-link')
        .wrap('<li class="slide-list-item"></li>');
    $('li.slide-list-item')
        .wrapAll('<ul id="slide-list"></ul>');
    $('ul#slide-list')
        .wrapAll('<div class="wrapper"></div>');
    $('div.wrapper')
        .wrapAll('<div class="anythingSlider internalSlider"></div>');
    $('.anythingSlider')
        .anythingSlider({
            easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
            autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
            startStopped: false,            // If autoPlay is on, this can force it to start stopped
            delay: 7000,                    // How long between slide transitions in AutoPlay mode
            animationTime: 600,             // How long the slide transition takes
            hashTags: false,                 // Should links change the hashtag in the URL?
            buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
            pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
            startText: "Start",             // Start text
            stopText: "Stop",               // Stop text
            navigationFormatter: null       // Details at the top of the file on this use (advanced use)
        });
    $('a.slide-link').show();
    });
</code>```

It's a bit of a hash job but works fine as long as there's more than one

答:
I had this problem and could only resolve this with a new version of the plugin: v1.5.3

URL: https://github.com/ProLoser/AnythingSlider/downloads

Once you've got the latest version, only change one line:

```<code>base.setCurrentPage(startPanel, false); // added to trigger events for FX code
</code>```

When I have only one
 the anythingControls element's style is display=none.

ContentLicense: CC BY-SA 2.5

Title: How to stop sliding if only one <li> using anythingSlider(jQuery plugin)?

Body:
I'm currently using the anythingSlider plugin, it works totally fine except when there is only one
.

The
s are generated from the database so sometimes there's only one.

However, the anythingSlider plugin still tries to slide through the
s, it works by sliding back to the first slide. Although this doesn't look great.

Does anybody know of a way of stopping it sliding if there's only one
?

-- EDIT --

Hi!

Can anybody else help with this? I've tried the solution by Greg and I've also tried:

if (banners<1) {
    .anythingSlider({
        startStopped: true,
        buildNavigation: false
        });
    }

'banners' is my variable that I'm calling.

And this disables the anythingSlider function altogether.

Help please?!

-- EDIT 2 --

The original code is in the page of the html

It's then being actioned by this file: http://image.ebuyer.com/customer/promos/js/topbanners.js

// function to import css and javascript from external locations
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

// importing css and javascript
loadjscssfile("http://static.ebuyer.com/css/slider.css", "css") ////dynamically load and add this .css file

// setting the variables
var banner = document.getElementById('tehBanner');
var link = document.getElementById('tehLink');

// this function creates the tracking tags
function tracking (x) {
    if (x.indexOf("?")>=0){x+='&tb='+(i+1);}else{x+='?tb='+(i+1);}
    return x
    }

// telling the javascript to display all available variables
for (var i in banners) {
    banner.alt = bannerAlt[i];
    link.href = tracking(bannerLink[i]);
    banner.src = banners[i];
    document.write('' + '');
    }

// remove the original banner
$ ('a#tehLink').parent().remove();

// hide banners to begin with
$('a.slide-link').hide();

/*
    anythingSlider v1.1

    By Chris Coyier: http://css-tricks.com
    with major improvements by Doug Neiner: http://pixelgraphics.us/
    based on work by Remy Sharp: http://jqueryfordesigners.com/

    To use the navigationFormatter function, you must have a function that
    accepts two paramaters, and returns a string of HTML text.

    index = integer index (1 based);
    panel = jQuery wrapped LI item this tab references
    @return = Must return a string of HTML/Text

    navigationFormatter: function(index, panel){
        return index + " Panel"; // This would have each tab with the text 'X Panel' where X = index
    }
*/

(function($){

    $.anythingSlider = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;

        // Set up a few defaults
        base.currentPage = 1;
        base.timer = null;
        base.playing = false;

        // Add a reverse reference to the DOM object
        base.$el.data("AnythingSlider", base);

        base.init = function(){
            base.options = $.extend({},$.anythingSlider.defaults, options);

            // Cache existing DOM elements for later
            base.$wrapper = base.$el.find('> div').css('overflow', 'hidden');
            base.$slider  = base.$wrapper.find('> ul');
            base.$items   = base.$slider.find('> li');
            base.$single  = base.$items.filter(':first');

            // Build the navigation if needed
            if(base.options.buildNavigation) base.buildNavigation();

            // Get the details
            base.singleWidth = base.$single.outerWidth();
            base.pages = base.$items.length;

            // Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
            // This supports the "infinite" scrolling
            base.$items.filter(':first').before(base.$items.filter(':last').clone().addClass('cloned'));
            base.$items.filter(':last' ).after(base.$items.filter(':first').clone().addClass('cloned'));

            // We just added two items, time to re-cache the list
            base.$items = base.$slider.find('> li'); // reselect

            // Setup our forward/backward navigation
            base.buildNextBackButtons();

            // If autoPlay functionality is included, then initialize the settings
            if(base.options.autoPlay) {
                base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
                base.buildAutoPlay();
            };

            // If pauseOnHover then add hover effects
            if(base.options.pauseOnHover) {
                base.$el.hover(function(){
                    base.clearTimer();
                }, function(){
                    base.startStop(base.playing);
                });
            }

            // If a hash can not be used to trigger the plugin, then go to page 1
            if((base.options.hashTags == true && !base.gotoHash()) || base.options.hashTags == false){
                base.setCurrentPage(1);
            };
        };

        base.gotoPage = function(page, autoplay){
            // When autoplay isn't passed, we stop the timer
            if(autoplay !== true) autoplay = false;
            if(!autoplay) base.startStop(false);

            if(typeof(page) == "undefined" || page == null) {
                page = 1;
                base.setCurrentPage(1);
            };

            // Just check for bounds
            if(page > base.pages + 1) page = base.pages;
            if(page < 0 ) page = 1;

            var dir = page < base.currentPage ? -1 : 1,
                n = Math.abs(base.currentPage - page),
                left = base.singleWidth * dir * n;

            base.$wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, base.options.animationTime, base.options.easing, function () {
                if (page == 0) {
                    base.$wrapper.scrollLeft(base.singleWidth * base.pages);
                    page = base.pages;
                } else if (page > base.pages) {
                    base.$wrapper.scrollLeft(base.singleWidth);
                    // reset back to start position
                    page = 1;
                };
                base.setCurrentPage(page);

            });
        };

        base.setCurrentPage = function(page, move){
            // Set visual
            if(base.options.buildNavigation){
                base.$nav.find('.cur').removeClass('cur');
                $(base.$navLinks[page - 1]).addClass('cur');
            };

            // Only change left if move does not equal false
            if(move !== false) base.$wrapper.scrollLeft(base.singleWidth * page);

            // Update local variable
            base.currentPage = page;
        };

        base.goForward = function(autoplay){
            if(autoplay !== true) autoplay = false;
            base.gotoPage(base.currentPage + 1, autoplay);
        };

        base.goBack = function(){
            base.gotoPage(base.currentPage - 1);
        };

        // This method tries to find a hash that matches panel-X
        // If found, it tries to find a matching item
        // If that is found as well, then that item starts visible
        base.gotoHash = function(){
            if(/^#?panel-\d+$/.test(window.location.hash)){
                var index = parseInt(window.location.hash.substr(7));
                var $item = base.$items.filter(':eq(' + index + ')');
                if($item.length != 0){
                    base.setCurrentPage(index);
                    return true;
                };
            };
            return false; // A item wasn't found;
        };

        // Creates the numbered navigation links
        base.buildNavigation = function(){
            base.$nav = $("

").appendTo(base.$el);
            base.$items.each(function(i,el){
                var index = i + 1;
                var $a = $("");

                // If a formatter function is present, use it
                if( typeof(base.options.navigationFormatter) == "function"){
                    $a.html(base.options.navigationFormatter(index, $(this)));
                } else {
                    $a.text(index);
                }
                $a.click(function(e){
                    base.gotoPage(index);

                    if (base.options.hashTags)
                        base.setHash('panel-' + index);

                    e.preventDefault();
                });
                base.$nav.append($a);
            });
            base.$navLinks = base.$nav.find('> a');
        };

        // Creates the Forward/Backward buttons
        base.buildNextBackButtons = function(){
            var $forward = $('>'),
                $back    = $('<');

            // Bind to the forward and back buttons
            $back.click(function(e){
                base.goBack();
                e.preventDefault();
            });

            $forward.click(function(e){
                base.goForward();
                e.preventDefault();
            });

            // Append elements to page
            base.$wrapper.after($back).after($forward);
        };

        // Creates the Start/Stop button
        base.buildAutoPlay = function(){

            base.$startStop = $("").html(base.playing ? base.options.stopText :  base.options.startText);
            base.$el.append(base.$startStop);
            base.$startStop.click(function(e){
                base.startStop(!base.playing);
                e.preventDefault();
            });

            // Use the same setting, but trigger the start;
            base.startStop(base.playing);
        };

        // Handles stopping and playing the slideshow
        // Pass startStop(false) to stop and startStop(true) to play
        base.startStop = function(playing){
            if(playing !== true) playing = false; // Default if not supplied is false

            // Update variable
            base.playing = playing;

            // Toggle playing and text
            base.$startStop.toggleClass("playing", playing).html( playing ? base.options.stopText : base.options.startText );

            if(playing){
                base.clearTimer(); // Just in case this was triggered twice in a row
                base.timer = window.setInterval(function(){
                    base.goForward(true);
                }, base.options.delay);
            } else {
                base.clearTimer();
            };
        };

        base.clearTimer = function(){
            // Clear the timer only if it is set
            if(base.timer) window.clearInterval(base.timer);
        };

        // Taken from AJAXY jquery.history Plugin
        base.setHash = function ( hash ) {
            // Write hash
            if ( typeof window.location.hash !== 'undefined' ) {
                if ( window.location.hash !== hash ) {
                    window.location.hash = hash;
                };
            } else if ( location.hash !== hash ) {
                location.hash = hash;
            };

            // Done
            return hash;
        };
        // <-- End AJAXY code

        // Trigger the initialization
        base.init();
    };

    $.anythingSlider.defaults = {
        easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
        autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
        startStopped: false,            // If autoPlay is on, this can force it to start stopped
        delay: 3000,                    // How long between slide transitions in AutoPlay mode
        animationTime: 600,             // How long the slide transition takes
        hashTags: true,                 // Should links change the hashtag in the URL?
        buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
        pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
        startText: "Start",             // Start text
        stopText: "Stop",               // Stop text
        navigationFormatter: null       // Details at the top of the file on this use (advanced use)
    };

    $.fn.anythingSlider = function(options){
        if(typeof(options) == "object"){
            return this.each(function(i){
                (new $.anythingSlider(this, options));

                // This plugin supports multiple instances, but only one can support hash-tag support
                // This disables hash-tags on all items but the first one
                options.hashTags = false;
            });
        } else if (typeof(options) == "number") {

            return this.each(function(i){
                var anySlide = $(this).data('AnythingSlider');
                if(anySlide){
                    anySlide.gotoPage(options);
                }
            });
        }
    };

})(jQuery);

// this function wraps the elements in the neccessary tags to work with anything Slider
$ (document).ready(function() {
    $('a.slide-link')
        .wrap('

');
    $('li.slide-list-item')
        .wrapAll('

');
    $('ul#slide-list')
        .wrapAll('

');
    $('div.wrapper')
        .wrapAll('

');
    $('.anythingSlider')
        .anythingSlider({
            easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
            autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
            startStopped: false,            // If autoPlay is on, this can force it to start stopped
            delay: 7000,                    // How long between slide transitions in AutoPlay mode
            animationTime: 600,             // How long the slide transition takes
            hashTags: false,                 // Should links change the hashtag in the URL?
            buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
            pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
            startText: "Start",             // Start text
            stopText: "Stop",               // Stop text
            navigationFormatter: null       // Details at the top of the file on this use (advanced use)
        });
    $('a.slide-link').show();
    });

It's a bit of a hash job but works fine as long as there's more than one

Body:
I had this problem and could only resolve this with a new version of the plugin: v1.5.3

URL: https://github.com/ProLoser/AnythingSlider/downloads

Once you've got the latest version, only change one line:

base.setCurrentPage(startPanel, false); // added to trigger events for FX code

When I have only one <li> the anythingControls element's style is display=none.


问:
Handling physical keyboard's Enter key in SearchView
I've implemented a SearchView in my application which is working properly when I hit the search button while I'm using the soft keyboard (using the QueryTextListener):

```<code>viewHolder.mTextSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        new SearchForEquipmentTask(false, viewHolder.mTextSearch.getQuery().toString()).execute();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        //Log.d(TAG, "Query: " + newText);
        return false;
    }
});
</code>```

Now I'm planning to use a physical keyboard for my users to be able to work with the app, but I can't figure out how to fire the search event from the physical keyboard (onQueryTextChange is not getting invoked with that key). Same thing happens when I'm running the emulator in Android Studio. I've tried:

```<code>viewHolder.mTextSearch.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        Log.d(TAG, "Query: " + keyEvent);
        return false;
    }
});
</code>```

But the SearchView seems to ignore the listener for any key... It seems that QueryTextListener is the only way to handle searches, but how to deal with special characters? Should I switch it to EditText which is more flexible?

Any idea?

答:
That's how I've handled it:

```<code>//Grab de EditText from the SearchView
EditText editText = (EditText) viewHolder.mTextSearch
    .findViewById(android.support.v7.appcompat.R.id.search_src_text);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int keyAction, KeyEvent keyEvent) {
        if (
            //Soft keyboard search
                keyAction == EditorInfo.IME_ACTION_SEARCH ||
                        //Physical keyboard enter key
                        (keyEvent != null && KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()
                                && keyEvent.getAction() == KeyEvent.ACTION_DOWN)) {
            new SearchForEquipmentTask(false, viewHolder.mTextSearch
                .getQuery().toString()).execute();
            return true;
        }
        return false;
    }
});
</code>```

Thanks for your help!

See also:

Grab the EditText element from a SearchView

Android: how to make keyboard enter button say "Search" and handle its click?

Body:
I've implemented a SearchView in my application which is working properly when I hit the search button while I'm using the soft keyboard (using the QueryTextListener):

viewHolder.mTextSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        new SearchForEquipmentTask(false, viewHolder.mTextSearch.getQuery().toString()).execute();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        //Log.d(TAG, "Query: " + newText);
        return false;
    }
});

Now I'm planning to use a physical keyboard for my users to be able to work with the app, but I can't figure out how to fire the search event from the physical keyboard (onQueryTextChange is not getting invoked with that key). Same thing happens when I'm running the emulator in Android Studio. I've tried:

viewHolder.mTextSearch.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        Log.d(TAG, "Query: " + keyEvent);
        return false;
    }
});

But the SearchView seems to ignore the listener for any key... It seems that QueryTextListener is the only way to handle searches, but how to deal with special characters? Should I switch it to EditText which is more flexible?

Any idea?

Body:
That's how I've handled it:

//Grab de EditText from the SearchView
EditText editText = (EditText) viewHolder.mTextSearch
    .findViewById(android.support.v7.appcompat.R.id.search_src_text);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int keyAction, KeyEvent keyEvent) {
        if (
            //Soft keyboard search
                keyAction == EditorInfo.IME_ACTION_SEARCH ||
                        //Physical keyboard enter key
                        (keyEvent != null && KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()
                                && keyEvent.getAction() == KeyEvent.ACTION_DOWN)) {
            new SearchForEquipmentTask(false, viewHolder.mTextSearch
                .getQuery().toString()).execute();
            return true;
        }
        return false;
    }
});

Thanks for your help!

See also:

Grab the EditText element from a SearchView

Android: how to make keyboard enter button say "Search" and handle its click?


问:
Create Virtual Server Dynamically Using PHP
I am creating a webapp for multiple companies to use but i don't want all to be login through one place so i want to create virtual servers for every client whenever i want to add them. So Anyone Have Idea How I Would Be Able To Do that??</p>

答:
Try Creating PHP Bult-in Server Using :</p>

```<code>php -S localhost:8000
</code>```

Body:
Try Creating PHP Bult-in Server Using :

php -S localhost:8000


问:
Variable After Assignment is still Undefined in Callback Function in Javascript for PhantomJS
So I have the following used for phantomjs:

```<code>  var time = 1490543999999999;
  var endTime = time - 518400000000 * 10;
  var mintime = time - 518399999999;
  console.log("mintime after assignment is"+mintime);
  var loopnumber = 6;

  page.open('https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28', callback);

  function callback() {
    console.log("inside callback and loopnumber is "+loopnumber+"and time is "+time+", and mintime is "+mintime+'. URL: https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28');
    page.render('/Users/jMac-NEW/Documents/FILEMAKER OCLC/login_test33.7_brkpoint' + loopnumber + '.png');
    fs.write('/Users/jMac-NEW/Documents/FILEMAKER OCLC/login_test33.7_brkpoint' + loopnumber + 'html.html', page.content, 'w');
    time -= 518400000000;
    loopnumber++;
    if (time > endTime) {
      var mintime = time - 518399999999;
      page.open('https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28', callback);
    }
    else {
      phantom.exit();
    }
  }
</code>```

This is output for the first console.log:

```<code>mintime after assignment is1490025600000000
</code>```

But when it comes to the console.log in the callback(), this is the output:

```<code>inside callback and loopnumber is 6and time is 1490543999999999, and mintime is undefined. URL: https://myactivity.google.com/item?min=undefined&max=1490543999999999&product=5,6,7,10,11,12,13,15,19,20,25,27,28
</code>```

Why is mintime = undefined, when the other variables (loopnumber and time) are not?

答:
There's a concept in Javascript called hoisting - if a variable is declared after it's been used, script interpreter automatically moves it's declaration to the top of current scope internally.

So your script actually reads to js like this:

```<code>function callback() {
    var mintime; // <-- declaration moved here

    // mintime is not yet defined
    console.log("and time is "+time+", and mintime is "+mintime);
    // ...
    if (time > endTime) {
      mintime = time - 518399999999; // it's been declared already and now it's defined
    }
    else {
      phantom.exit();
    }
  }
</code>```

So the solution is simple: remove var from assignment to mintime in callback, this way variable will be assigned to the outer (window) scope mintime, just like you wanted.

Body:
So I have the following used for phantomjs:

  var time = 1490543999999999;
  var endTime = time - 518400000000 * 10;
  var mintime = time - 518399999999;
  console.log("mintime after assignment is"+mintime);
  var loopnumber = 6;

  page.open('https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28', callback);

  function callback() {
    console.log("inside callback and loopnumber is "+loopnumber+"and time is "+time+", and mintime is "+mintime+'. URL: https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28');
    page.render('/Users/jMac-NEW/Documents/FILEMAKER OCLC/login_test33.7_brkpoint' + loopnumber + '.png');
    fs.write('/Users/jMac-NEW/Documents/FILEMAKER OCLC/login_test33.7_brkpoint' + loopnumber + 'html.html', page.content, 'w');
    time -= 518400000000;
    loopnumber++;
    if (time > endTime) {
      var mintime = time - 518399999999;
      page.open('https://myactivity.google.com/item?min=' + mintime + '&max=' + time + '&product=5,6,7,10,11,12,13,15,19,20,25,27,28', callback);
    }
    else {
      phantom.exit();
    }
  }

This is output for the first console.log:

mintime after assignment is1490025600000000

But when it comes to the console.log in the callback(), this is the output:

inside callback and loopnumber is 6and time is 1490543999999999, and mintime is undefined. URL: https://myactivity.google.com/item?min=undefined&max=1490543999999999&product=5,6,7,10,11,12,13,15,19,20,25,27,28

Why is mintime = undefined, when the other variables (loopnumber and time) are not?

Body:
There's a concept in Javascript called hoisting - if a variable is declared after it's been used, script interpreter automatically moves it's declaration to the top of current scope internally.

So your script actually reads to js like this:

function callback() {
    var mintime; // <-- declaration moved here

    // mintime is not yet defined
    console.log("and time is "+time+", and mintime is "+mintime);
    // ...
    if (time > endTime) {
      mintime = time - 518399999999; // it's been declared already and now it's defined
    }
    else {
      phantom.exit();
    }
  }

So the solution is simple: remove var from assignment to mintime in callback, this way variable will be assigned to the outer (window) scope mintime, just like you wanted.


问:
Rails ActiveRecord Find / Search by Date
I am trying to find records by 'created_at' date - the database column type is 'datetime' and
I am using the UI DatePicker from jQuery

my url look like this: "localhost:3000/users_supported?selected_date=2012-10-31"

So far i am doing good :) and my query in controller looks like this:

```<code>@support_histories = current_agent.support_histories.where(:created_at => Date.parse(params[:selected_date]))
</code>```

How to properly extract records by 'date' only from the 'datetime' db column

I tried doing this in Rails Console, but no luck there:

```<code>sh = SupportHistory.where(:created_at => DateTime.parse('2012-10-31'))
sh = SupportHistory.where(:created_at => Date.parse('2012-10-31'))
sh = SupportHistory.where(:created_at => DateTime.strptime('2012-10-31', '%Y-%m-%d'))
</code>```

I got records if i do like mentioned below, but that's not useful to me as i am trying to find record by 'date' not by 'DateTime'

```<code>sh = SupportHistory.where(:created_at => '2012-10-31 19:49:57')
</code>```

答:
A simple solution I use sometimes is to cast the date(time) field as text on the database rather than parse the string into date on application side. For your case that would be:

```<code>where('CAST(created_at AS text) LIKE ?', params[:selected_date])
</code>```

Might not be the most effective on the database (depending on the context you use it in) but saves a lot of pita on the application side.

Body:
I am trying to find records by 'created_at' date - the database column type is 'datetime' and
I am using the UI DatePicker from jQuery

my url look like this: "localhost:3000/users_supported?selected_date=2012-10-31"

So far i am doing good :) and my query in controller looks like this:

@support_histories = current_agent.support_histories.where(:created_at => Date.parse(params[:selected_date]))

How to properly extract records by 'date' only from the 'datetime' db column

I tried doing this in Rails Console, but no luck there:

sh = SupportHistory.where(:created_at => DateTime.parse('2012-10-31'))
sh = SupportHistory.where(:created_at => Date.parse('2012-10-31'))
sh = SupportHistory.where(:created_at => DateTime.strptime('2012-10-31', '%Y-%m-%d'))

I got records if i do like mentioned below, but that's not useful to me as i am trying to find record by 'date' not by 'DateTime'

sh = SupportHistory.where(:created_at => '2012-10-31 19:49:57')

Body:
A simple solution I use sometimes is to cast the date(time) field as text on the database rather than parse the string into date on application side. For your case that would be:

where('CAST(created_at AS text) LIKE ?', params[:selected_date])

Might not be the most effective on the database (depending on the context you use it in) but saves a lot of pita on the application side.

ContentLicense: CC BY-SA 4.0


问:
In Android EditText, how to force writing uppercase?
In my Android application I have different EditText where the user can enter information. But I need to force user to write in uppercase letters.
Do you know a function to do that?

答:
Simply, Add below code to your EditText of your xml file.

```<code>android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
</code>```

And if you want to allow both uppercase text and digits then use below code.

```<code>android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
</code>```

Body:
Simply, Add below code to your EditText of your xml file.

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

And if you want to allow both uppercase text and digits then use below code.

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"


问:
Autolayout not working properly
I have UIView in separate .xib file and I make UICollectionView in it.

To add collectionViewCell I made separate .xib file.

Now below collectionview I want to add UIView.but my problem is I set height of collectionview dynamically by using code.

But when I add this using autolayout constraint to add view below bottom of the collectionview but view will add on distance where It put on UI.

I want that first setup collectionview than view placed below it.

Problem screenshot 1

Below UIView constraint I have already set 2

Thanks
Nirav Zalavadia

答:
Instead of adding the UIView below the UICollectionView, place the UIView in the bottom of the screen.

Then, use a constraint from the bottom of the UICollection view to the top of the UIView.

Title: Autolayout not working properly


问:
Can i use ng-model with <p> tag?
I am new to angular-js and i think this is a basic question how to get the value from a paragraph tag in angular-js? I tried with using ng-model but doesn't giving the value.Can anyone help me?</p>

答:
Ng-model is not supported for P,H tags,,,

if you want to bind tags then use ng-class

{{localUser.yourdata}}

{{localUser.yourdata}}

hope this is help full

Title: Can i use ng-model with <p> tag?

Body:
Ng-model is not supported for P,H tags,,,

if you want to bind tags then use ng-class

<p ng-class="localUser.yourdata">{{localUser.yourdata}}</p>

<h1 ng-class="localUser.yourdata">{{localUser.yourdata}}</h1>

hope this is help full


问:
is there any reasonable number of subviews?
I want to create something similiar to EMD Periodic Table application. I'm wondering how they did this animation when first creen appears. There is over 50 rectangles and they appear with animation. Does it make sense to add 50 subviews and manage them separately? Is it proper way to achieve this effect?

itunes.apple.com/us/app/emd-pte/id377393859?mt=8

--
Piotr

答:
Try it and see :) It should be OK with just UIViews but there might be an issue on older phones with framerate.

Failing that, openGL would be the way forward - have a look at cocos2d (http://www.cocos2d-iphone.org/) which makes accelerated 2d work pretty easy.

Though if you really want the perspective effect, you will probably have to go all the way into openGL proper.


问:
Inserting Value into User Defined Type
I have defined SchemaTuple as:

```<code>create type SchemaTuple as ("table" text, "attributes" text);
</code>```

I would like to insert values into this but I am not sure how to go about this.

I tried declaring a variable first:

```<code>tuple SchemaTuple;
</code>```

and then:

```<code>INSERT INTO tuple (table, attributes) VALUES ('tablename','attributename');
</code>```

The problem is, I get the error:

```<code>ERROR:  syntax error at or near ","
</code>```

where , refers to (table,attributes)

Can someone please let me know the correct way to do this?

答:
You cannot insert a value into a type directly. You'll have either create a table for the type , or use the type as the type of an attribute in a table.
For instance:

```<code>--create type
CREATE TYPE PersonType AS (
    ID INTEGER,
    NAME CHAR(50)
);

CREATE TABLE Student OF PersonType (
    ID WITH OPTIONS NOT NULL,
    NAME WITH OPTIONS NOT NULL
);

INSERT INTO Student VALUES (100, 'Joe');
</code>```

or

```<code>CREATE TABLE Transcript (
    COURSE CHAR(10),
    STDNT PersonType
);
</code>```

and then insert the value to Transcript table with value for STDNT specified as a Row type.

Title: Inserting Value into User Defined Type

Body:
I have defined SchemaTuple as:

create type SchemaTuple as ("table" text, "attributes" text);

I would like to insert values into this but I am not sure how to go about this.

I tried declaring a variable first:

tuple SchemaTuple;

and then:

INSERT INTO tuple (table, attributes) VALUES ('tablename','attributename');

The problem is, I get the error:

ERROR:  syntax error at or near ","

where , refers to (table,attributes)

Can someone please let me know the correct way to do this?

Body:
You cannot insert a value into a type directly. You'll have either create a table for the type , or use the type as the type of an attribute in a table.
For instance:

--create type
CREATE TYPE PersonType AS (
    ID INTEGER,
    NAME CHAR(50)
);

CREATE TABLE Student OF PersonType (
    ID WITH OPTIONS NOT NULL,
    NAME WITH OPTIONS NOT NULL
);

INSERT INTO Student VALUES (100, 'Joe');

or

CREATE TABLE Transcript (
    COURSE CHAR(10),
    STDNT PersonType
);

and then insert the value to Transcript table with value for STDNT specified as a Row type.


问:
Highstock, split tooltip and opposite xAxis?
I'm displaying the x-axis of my Highstock chart at the top of the chart area with xAxis: { opposite: true}.

However the tooltip continues to show the x-axis value at the bottom of the chart, see for example here http://jsfiddle.net/ckj7kf2y/

Is there any way I can change the positioning of this be at the top, close to the x-axis?

Bonus points if someone knows why the tooltip.positioner callback isn't called when tooltip: { split: true }

答:
It's possible to wrap core code to add this feature like in this demo: http://jsfiddle.net/ygmbwxtx/

```<code>(function(H){
    H.wrap(H.Tooltip.prototype, 'renderSplit', function (proceed) {
        proceed.apply(this, [].slice.call(arguments, 1));

      var tooltip = this,
        topAxis = tooltip.options.topAxis,
        axisTT = tooltip.tt,
        top = tooltip.chart.plotTop;

      if (topAxis) {
        axisTT.attr({
            y: top - axisTT.height,
          anchorY: top + 10
        });
      }
    });
}(Highcharts))
</code>```

and in chart's options:

```<code>...
    tooltip: {
        split: true,
        topAxis: true
...
</code>```

Bonus: positioner is not used for split tooltip - split uses own logic for positioning

Body:
It's possible to wrap core code to add this feature like in this demo: http://jsfiddle.net/ygmbwxtx/

(function(H){
    H.wrap(H.Tooltip.prototype, 'renderSplit', function (proceed) {
        proceed.apply(this, [].slice.call(arguments, 1));

      var tooltip = this,
        topAxis = tooltip.options.topAxis,
        axisTT = tooltip.tt,
        top = tooltip.chart.plotTop;

      if (topAxis) {
        axisTT.attr({
            y: top - axisTT.height,
          anchorY: top + 10
        });
      }
    });
}(Highcharts))

and in chart's options:

...
    tooltip: {
        split: true,
        topAxis: true
...

Bonus: positioner is not used for split tooltip - split uses own logic for positioning


问:
Trouble formatting json objects with lodash _.groupBy
I'm having trouble reformatting an object in order to group by lists.

```<code>// input
{
    'M': [
        {name: Bob, id: 1},
        {name: John, id: 2},
        {name: John, id: 3},
    ],
    'F': [
        {name: Liz, id: 4},
        {name: Mary, id: 5},
        {name: Mary, id: 6},
    ]
}

// desired output
{
    'M': [
        'Bob': [ {name: Bob, id: 1},]
        'John': [ {name: John, id: 2}, {name: John, id: 3} ]
    ],
    'F': [
        'Liz': [ {name: Liz, id: 4} ]
        'Mary': [ {name: Mary, id: 5}, {name: Mary, id: 6} ]
    ]
}
</code>```

My current script is only returning the 'M' key and I'm not what is causing it

```<code>for (var key in obj) {
    var data = _.groupBy(obj[key], 'name')
    return data;
}
</code>```

I've also tried

```<code>  Object.keys(obj).forEach(obj, key => {
    var data = _.groupBy(obj[key], 'name')
    return data;
  })
</code>```

but it throws TypeError: #<Object> is not a function

答:
You can use mapValues to group each gender groups by their names through groupBy.

```<code>var output = _.mapValues(input, names => _.groupBy(names, 'name'));
</code>```

var input = {
    'M': [
        {name: 'Bob', id: 1},
        {name: 'John', id: 2},
        {name: 'John', id: 3},
    ],
    'F': [
        {name: 'Liz', id: 4},
        {name: 'Mary', id: 5},
        {name: 'Mary', id: 6},
    ]
};

var output = _.mapValues(input, names => _.groupBy(names, 'name'));

console.log(output);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body > div { min-height: 100%; top: 0; }</code>```

```

Body:
I'm having trouble reformatting an object in order to group by lists.

// input
{
    'M': [
        {name: Bob, id: 1},
        {name: John, id: 2},
        {name: John, id: 3},
    ],
    'F': [
        {name: Liz, id: 4},
        {name: Mary, id: 5},
        {name: Mary, id: 6},
    ]
}

// desired output
{
    'M': [
        'Bob': [ {name: Bob, id: 1},]
        'John': [ {name: John, id: 2}, {name: John, id: 3} ]
    ],
    'F': [
        'Liz': [ {name: Liz, id: 4} ]
        'Mary': [ {name: Mary, id: 5}, {name: Mary, id: 6} ]
    ]
}

My current script is only returning the 'M' key and I'm not what is causing it

for (var key in obj) {
    var data = _.groupBy(obj[key], 'name')
    return data;
}

I've also tried

  Object.keys(obj).forEach(obj, key => {
    var data = _.groupBy(obj[key], 'name')
    return data;
  })

but it throws TypeError: #<Object> is not a function

Body:
You can use mapValues to group each gender groups by their names through groupBy.

var output = _.mapValues(input, names => _.groupBy(names, 'name'));

var input = {
    'M': [
        {name: 'Bob', id: 1},
        {name: 'John', id: 2},
        {name: 'John', id: 3},
    ],
    'F': [
        {name: 'Liz', id: 4},
        {name: 'Mary', id: 5},
        {name: 'Mary', id: 6},
    ]
};

var output = _.mapValues(input, names => _.groupBy(names, 'name'));

console.log(output);

body > div { min-height: 100%; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
Left join with group by linq lambda expression c#?
I want to write left join using linq lambda expression. I have tried query using join but now I want to create using left join so any one can help me how can do.

Here this is my query:

```<code>var UserList = db.UserInfo
                .Join(db.Course, u => u.id, c => c.userid, (u, c) =>
                new { u, c }).GroupBy(r => r.u.id)
                .Select(g => g.OrderByDescending(r => r.c.datetime)
                .FirstOrDefault()).OrderByDescending(a => a.u.datetime).ToList();
</code>```

Using this query, I don't want user data those who are not in course table, so I want to this data also in course table in userid in or not.

答:
you can use

```<code>var qry = Foo.GroupJoin(
      Bar,
      foo => foo.Foo_Id,
      bar => bar.Foo_Id,
      (x,y) => new { Foo = x, Bars = y })
.SelectMany(
      x => x.Bars.DefaultIfEmpty(),
      (x,y) => new { Foo=x.Foo, Bar=y});
</code>```

ref: How do you perform a left outer join using linq extension methods

Body:
I want to write left join using linq lambda expression. I have tried query using join but now I want to create using left join so any one can help me how can do.

Here this is my query:

var UserList = db.UserInfo
                .Join(db.Course, u => u.id, c => c.userid, (u, c) =>
                new { u, c }).GroupBy(r => r.u.id)
                .Select(g => g.OrderByDescending(r => r.c.datetime)
                .FirstOrDefault()).OrderByDescending(a => a.u.datetime).ToList();

Using this query, I don't want user data those who are not in course table, so I want to this data also in course table in userid in or not.

Body:
you can use

var qry = Foo.GroupJoin(
      Bar,
      foo => foo.Foo_Id,
      bar => bar.Foo_Id,
      (x,y) => new { Foo = x, Bars = y })
.SelectMany(
      x => x.Bars.DefaultIfEmpty(),
      (x,y) => new { Foo=x.Foo, Bar=y});

ref: How do you perform a left outer join using linq extension methods


问:
Mapping a List<string> to a delimited string with Fluent NHibernate
My model looks something like this:

```<code>public class Product
{
    public string Name {get; set;}
    public string Description {get; set;}
    public double Price {get; set;}
    public List<string> Features {get; set;}
}
</code>```

I want my database table to be flat - the List should be stored as a delimited string:
Feature one|Feature two|Feature three for example.

When retrieved from the db, it should place each of those items back into a List

Is this possible?

答:
I'm doing the very same in my current project, only I'm persisting a collection of enums as pipe-delimited numbers. It works the same way.</p>

```<code>public class Product
{
    protected string _features; //this is where we'll store the pipe-delimited string
    public List<string> Features {
        get
        {
            if(string.IsNullOrEmpty(_features)
                return new List<String>();
            return _features.Split(new[]{"|"}, StringSplitOptions.None).ToList();
        }
        set
        {
            _features = string.Join("|",value);
        }
    }
}

public class ProductMapping : ClassMap<Product>
{
    protected ProductMapping()
    {
        Map(x => x.Features).CustomType(typeof(string)).Access.CamelCaseField(Prefix.Underscore);
    }
}
</code>```

Body:
My model looks something like this:

public class Product
{
    public string Name {get; set;}
    public string Description {get; set;}
    public double Price {get; set;}
    public List<string> Features {get; set;}
}

I want my database table to be flat - the List should be stored as a delimited string:
Feature one|Feature two|Feature three for example.

When retrieved from the db, it should place each of those items back into a List

Is this possible?

Body:
I'm doing the very same in my current project, only I'm persisting a collection of enums as pipe-delimited numbers. It works the same way.

public class Product
{
    protected string _features; //this is where we'll store the pipe-delimited string
    public List<string> Features {
        get
        {
            if(string.IsNullOrEmpty(_features)
                return new List<String>();
            return _features.Split(new[]{"|"}, StringSplitOptions.None).ToList();
        }
        set
        {
            _features = string.Join("|",value);
        }
    }
}

public class ProductMapping : ClassMap<Product>
{
    protected ProductMapping()
    {
        Map(x => x.Features).CustomType(typeof(string)).Access.CamelCaseField(Prefix.Underscore);
    }
}


问:
windows scheduler to run a batch script (.bat) every x-minutes?
I'm trying to get windows scheduler to run a particular .bat script every 30 minutes or so, but the options only allow for once a day execution.

Is there a way I can get it to run a .bat script every 30 minutes?

答:
You can use the following to create a new scheduler

```<code>SCHTASKS /Create /SC MINUTE /MO 30 /TN MyTaskName /TR "c:/myBat.bat"
</code>```

If you need additional settings, use

```<code>SCHTASKS /Create /?
</code>```

Body:
You can use the following to create a new scheduler

SCHTASKS /Create /SC MINUTE /MO 30 /TN MyTaskName /TR "c:/myBat.bat"

If you need additional settings, use

SCHTASKS /Create /?


问:
Codenameone Connect to Google Drive
This may be a dumb questions, but I haven't found an answer after lots of searching. I need to do two things, I need to allow my app to login to google, then save a file the users google drive.

I've found some steps on how to connect to google drive, but either its outdated or I don't have the correct libraries because it fails to compile:  https://www.codenameone.com/google-login.html

Any help would be greatly appreciated.

答:
For the login part there are good instructions in this blog post

Another sample of code to login to Google in this demo

You'll need to set the scope of the OAuth2 login to the appropriate Google Drive Scope

For saving files to drive, you should use ConnectionRequest to create the HTTP requests directly to their REST API.

Title: Codenameone Connect to Google Drive


问:
SYMFONY3 in prod look for TWIG template in wrong folder instead of custom bundle indicated in routing.yml and AppKernel.php
I am implementing a SYMFONY 3 project in production mode for the first time.

I follow OceanDigital tutorial and the standard doc.

I went thru a bunch of issues linked to user writing rights that I've solved, and I do get now a SYMFONY ERROR page (one step closer to victory) with this message:

Unable to find template "MyBundle:std_page:home.html.twig" (looked
  into: /[folder to symf project]/app/Resources/views,
  /[folder to symf project]/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form,
  /[folder to symf project]/vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views).

If I look in my [my symf project]\app\config\routing.yml, I have:

```<code>my_bundle:
  resource: "@MyBundle/Resources/config/routing.yml"
  options:
      expose: true
</code>```

In [my symf project]\app\AppKernel.php, in the registerBundles() function, I have:

```<code>class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            ....
             new MyBundle\MyBundle(),
           .....
         ]
    }
}
</code>```

And the file regarding the template that should be fetched [my symf project]\src\MyBundle\Ressources\views/std_page/home.html.twig  exists.

What did I not set up right, in production mode, to have it looking for the TWIG template in the folder [my symf project]\src\MyBundle\Ressources\views/?

答:
After some search it happens to be a mistake similar to the one described in that SO thread.

In my controller I had:

```<code>return $this->render('MyBundle:Std_page:home.html.twig',$parameters);
</code>```

Instead of:

```<code>return $this->render('MyBundle:std_page:home.html.twig',$parameters);
</code>```

The development was made on a WINDOWS 10 OS, and it is set up in production on a UBUNTU 16.04. It seems that UBUNTU is stricter than WINDOWS regarding the letter case.

Body:
I am implementing a SYMFONY 3 project in production mode for the first time.

I follow OceanDigital tutorial and the standard doc.

I went thru a bunch of issues linked to user writing rights that I've solved, and I do get now a SYMFONY ERROR page (one step closer to victory) with this message:

Unable to find template "MyBundle:std_page:home.html.twig" (looked
  into: /[folder to symf project]/app/Resources/views,
  /[folder to symf project]/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form,
  /[folder to symf project]/vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views).

If I look in my [my symf project]\app\config\routing.yml, I have:

my_bundle:
  resource: "@MyBundle/Resources/config/routing.yml"
  options:
      expose: true

In [my symf project]\app\AppKernel.php, in the registerBundles() function, I have:

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            ....
             new MyBundle\MyBundle(),
           .....
         ]
    }
}

And the file regarding the template that should be fetched [my symf project]\src\MyBundle\Ressources\views/std_page/home.html.twig  exists.

What did I not set up right, in production mode, to have it looking for the TWIG template in the folder [my symf project]\src\MyBundle\Ressources\views/?

Body:
After some search it happens to be a mistake similar to the one described in that SO thread.

In my controller I had:

return $this->render('MyBundle:Std_page:home.html.twig',$parameters);

Instead of:

return $this->render('MyBundle:std_page:home.html.twig',$parameters);

The development was made on a WINDOWS 10 OS, and it is set up in production on a UBUNTU 16.04. It seems that UBUNTU is stricter than WINDOWS regarding the letter case.


问:
Create a one-sided distance map
I create with this code a black square of zeros with a white vertical line of ones at the middle and I want to create a distance map with respect to this line but only at the left side of the vertical line. How can I do this? </p>

<p>The following code yields a distance map on both sides of the line. </p>

```<code>c=zeros(500,500);
c(:,250)=1;
figure, imshow(c)

[D, idx]= bwdist(c,'euclidean')
</code>```

答:
You can compute the distance map for the entire image and then just zero-out (or set the values to NaN) the side that you aren't interested in

```<code>D = bwdist(c, 'euclidean');
D(:,251:end) = NaN;
</code>```

A more robust way (without hard-coding any columns) would be to modify c before calling bwdist by setting anything to the right of the line to 1 so that the resulting distance for each of those pixels is 0. You could do this by computing the cumulative sum across the rows

```<code>D = bwdist(cumsum(c, 2) > 0, 'euclidean');
</code>```

Title: Create a one-sided distance map

Body:
I create with this code a black square of zeros with a white vertical line of ones at the middle and I want to create a distance map with respect to this line but only at the left side of the vertical line. How can I do this?

The following code yields a distance map on both sides of the line.

c=zeros(500,500);
c(:,250)=1;
figure, imshow(c)

[D, idx]= bwdist(c,'euclidean')

Body:
You can compute the distance map for the entire image and then just zero-out (or set the values to NaN) the side that you aren't interested in

D = bwdist(c, 'euclidean');
D(:,251:end) = NaN;

A more robust way (without hard-coding any columns) would be to modify c before calling bwdist by setting anything to the right of the line to 1 so that the resulting distance for each of those pixels is 0. You could do this by computing the cumulative sum across the rows

D = bwdist(cumsum(c, 2) > 0, 'euclidean');


问:
Why can we not return a structure to a function?
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

```<code>#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}
</code>```

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

答:
```<code>typedef struct
{
    int feet;
    float inch;
} distance;
</code>```

Then get rid of the 'struct' declarations everywhere else...

Note: many thanks to @Lundin for correction:)

Body:
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

Body:
typedef struct
{
    int feet;
    float inch;
} distance;

Then get rid of the 'struct' declarations everywhere else...

Note: many thanks to @Lundin for correction:)


问:
Firebase Push Notification xcode console received notification but in device it is not working ios Objective c
I am using firebase for PushNotification but there is problem. The notification is received in xcode console not received in device. I am doing everything right but no success to get notification in device

```<code>2017-03-31 16:40:44.265 [7188] <Warning> [Firebase/Analytics][I-ACS003016] Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2017-03-31 16:40:44.531 [7188] <Notice> [Firebase/Crash][I-CRA000004] Successfully initialized
2017-03-31 16:40:44.541: <FIRMessaging/INFO> FIRMessaging library version 1.2.2
2017-03-31 16:40:44.552 [7188:141393] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
2017-03-31 16:40:44.666 [7188] <Notice> [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3700000 started
2017-03-31 16:40:44.758 [7188] <Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2017-03-31 16:40:45.124 [7188:141393] Unable to register for remote notifications: Error Domain=NSCocoaErrorDomain Code=3010 "REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION" UserInfo={NSLocalizedDescription=REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION}
2017-03-31 16:40:45.816 [7188:141393] Connected to FCM.
2017-03-31 16:40:45.920 [7188] <Notice> [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled
</code>```

答:
Do you test on a physical, real device or on the simulator? On iOS Simulator you cannot register and receive push notifications :)

If you are working a on a real device, not the simulator, be reminded to call the following functions to register for push.
    application.registerUserNotificationSettings(...)

Prior to the call:
https://developer.apple.com/reference/uikit/uiapplication/1623078-registerforremotenotifications

So altogether:

```<code>if application.respondsToSelector("registerUserNotificationSettings:") {
        if #available(iOS 8.0, *) {
            let types:UIUserNotificationType = ([.Alert, .Sound, .Badge])
            let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        } else {
            application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
        }
    }
    else {
        // Register for Push Notifications before iOS 8
        application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
    }
</code>```

Some helpful debugging output could also be:

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let pushSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Badge ,UIUserNotificationType.Sound ,UIUserNotificationType.Alert], categories: nil)
    application.registerUserNotificationSettings(pushSettings)
    return true
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    application.registerForRemoteNotifications()
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let token=deviceToken.description
    print(token)
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print(error)
}
</code>```

Body:
I am using firebase for PushNotification but there is problem. The notification is received in xcode console not received in device. I am doing everything right but no success to get notification in device

2017-03-31 16:40:44.265 [7188] <Warning> [Firebase/Analytics][I-ACS003016] Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2017-03-31 16:40:44.531 [7188] <Notice> [Firebase/Crash][I-CRA000004] Successfully initialized
2017-03-31 16:40:44.541: <FIRMessaging/INFO> FIRMessaging library version 1.2.2
2017-03-31 16:40:44.552 [7188:141393] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
2017-03-31 16:40:44.666 [7188] <Notice> [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3700000 started
2017-03-31 16:40:44.758 [7188] <Notice> [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2017-03-31 16:40:45.124 [7188:141393] Unable to register for remote notifications: Error Domain=NSCocoaErrorDomain Code=3010 "REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION" UserInfo={NSLocalizedDescription=REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION}
2017-03-31 16:40:45.816 [7188:141393] Connected to FCM.
2017-03-31 16:40:45.920 [7188] <Notice> [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled

Body:
Do you test on a physical, real device or on the simulator? On iOS Simulator you cannot register and receive push notifications :)

If you are working a on a real device, not the simulator, be reminded to call the following functions to register for push.
    application.registerUserNotificationSettings(...)

Prior to the call:
https://developer.apple.com/reference/uikit/uiapplication/1623078-registerforremotenotifications

So altogether:

if application.respondsToSelector("registerUserNotificationSettings:") {
        if #available(iOS 8.0, *) {
            let types:UIUserNotificationType = ([.Alert, .Sound, .Badge])
            let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        } else {
            application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
        }
    }
    else {
        // Register for Push Notifications before iOS 8
        application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
    }

Some helpful debugging output could also be:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let pushSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Badge ,UIUserNotificationType.Sound ,UIUserNotificationType.Alert], categories: nil)
    application.registerUserNotificationSettings(pushSettings)
    return true
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    application.registerForRemoteNotifications()
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let token=deviceToken.description
    print(token)
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print(error)
}