问:
Join multi-line strings into one string
I'm trying to parse a log file that looks like this:

```<code>24/01/2016, 11:50:17 pm: Line to skip
24/01/2016, 11:50:17 pm: Line to skip
25/01/2016, 11:51:47 pm: User1: Message one is here
25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and

can
[span]

Several lines.
24/01/2016, 11:51:47 pm: User3: My first message
27/10/2017, 12:54:03 am: +44 012 3456789 left
28/10/2017, 02:54:03 pm: User3: My second message!
</code>```

```<code>rawData <- structure(list(V1 = c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")), .Names = "V1", row.names = c(NA,
        -9L), class = "data.frame")
</code>```

Each message starts with a date, and I'm having trouble parsing messages that span multiple lines (like on line 4).

Here's what I have so far:

```<code>suppressMessages(library(lubridate))
suppressMessages(library(dplyr))
suppressMessages(library(plyr))
suppressMessages(library(tidyr))

parseR <- function(file='data/chat_log.txt',drop="44"){
  rawData <- read.delim(file, quote = "",
                  row.names = NULL,
                  stringsAsFactors = FALSE,
                  header = F)

  # remove blank lines
  # rawData<-rawData[!apply(rawData == "", 1, all),]

  empty_lines = grepl('^\\s*$', rawData)
  rawData = rawData[! empty_lines]

  # join multi line messages into single line
  # rawData$V1<-gsub("[\r\n]", " ", rawData$V2)

  sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

  sepData$message <- trimws(sepData$message)
  sepData$sender<-factor(sepData$sender)

  data <- sepData %>%
    filter(!is.na(message)) %>%
    filter(!grepl(drop, sender)) %>%
    droplevels()

  cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
  cleanData$date<-ymd(cleanData$date)
  cleanData$time<-hms(cleanData$time)

  return(cleanData)
}
</code>```

However, when I inspect the returned data frame, muliti line messages are not being parsed correctly:

```<code>> head(parseR())
        date        time sender                                                                                message
1 2016-01-25 23H 51M 47S  User1                                                                                Message one is here
2 2016-01-25  23H 53M 4S  User2 A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and
3 2016-01-24 23H 51M 47S  User3                                                                                My first message
4 2017-10-28  14H 54M 3S  User3
</code>```

Can anyone suggest a way of removing blank lines and joining text that doesn't start with a date into one string?

Desired format for line 4:

```<code>25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and can [span] Several lines.
</code>```

答:
I propose something similar to Roman's solution but in Tidyverse world:

```<code>rawData %>%
  mutate(
    MgsNo = (!substr( V1, 1, 1) %>% # take first character
                 as.numeric %>% # convert to numeric - produces NAs for non-numeric values
                 is.na) %>% # produces True(1) and False(0) ( by ! I reverse those)
      cumsum ) %>% # then cumulative sum as Mgs NO e.g. 1,1,1,0,0,1 -> 1,2,3,3,3,4
  group_by( MgsNo) %>%
  do( MgsBody = paste( .$V1 , collapse = "")) %>% # concatenate all in each MgsNo group
  select( MgsBody) %>%
  pull
</code>```

Title: Join multi-line strings into one string

Body:
I'm trying to parse a log file that looks like this:

24/01/2016, 11:50:17 pm: Line to skip
24/01/2016, 11:50:17 pm: Line to skip
25/01/2016, 11:51:47 pm: User1: Message one is here
25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and

can
[span]

Several lines.
24/01/2016, 11:51:47 pm: User3: My first message
27/10/2017, 12:54:03 am: +44 012 3456789 left
28/10/2017, 02:54:03 pm: User3: My second message!

rawData <- structure(list(V1 = c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")), .Names = "V1", row.names = c(NA,
        -9L), class = "data.frame")

Each message starts with a date, and I'm having trouble parsing messages that span multiple lines (like on line 4).

Here's what I have so far:

suppressMessages(library(lubridate))
suppressMessages(library(dplyr))
suppressMessages(library(plyr))
suppressMessages(library(tidyr))

parseR <- function(file='data/chat_log.txt',drop="44"){
  rawData <- read.delim(file, quote = "",
                  row.names = NULL,
                  stringsAsFactors = FALSE,
                  header = F)

  # remove blank lines
  # rawData<-rawData[!apply(rawData == "", 1, all),]

  empty_lines = grepl('^\\s*$', rawData)
  rawData = rawData[! empty_lines]

  # join multi line messages into single line
  # rawData$V1<-gsub("[\r\n]", " ", rawData$V2)

  sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

  sepData$message <- trimws(sepData$message)
  sepData$sender<-factor(sepData$sender)

  data <- sepData %>%
    filter(!is.na(message)) %>%
    filter(!grepl(drop, sender)) %>%
    droplevels()

  cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
  cleanData$date<-ymd(cleanData$date)
  cleanData$time<-hms(cleanData$time)

  return(cleanData)
}

However, when I inspect the returned data frame, muliti line messages are not being parsed correctly:

> head(parseR())
        date        time sender                                                                                message
1 2016-01-25 23H 51M 47S  User1                                                                                Message one is here
2 2016-01-25  23H 53M 4S  User2 A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and
3 2016-01-24 23H 51M 47S  User3                                                                                My first message
4 2017-10-28  14H 54M 3S  User3

Can anyone suggest a way of removing blank lines and joining text that doesn't start with a date into one string?

Desired format for line 4:

25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and can [span] Several lines.

Body:
I propose something similar to Roman's solution but in Tidyverse world:

rawData %>%
  mutate(
    MgsNo = (!substr( V1, 1, 1) %>% # take first character
                 as.numeric %>% # convert to numeric - produces NAs for non-numeric values
                 is.na) %>% # produces True(1) and False(0) ( by ! I reverse those)
      cumsum ) %>% # then cumulative sum as Mgs NO e.g. 1,1,1,0,0,1 -> 1,2,3,3,3,4
  group_by( MgsNo) %>%
  do( MgsBody = paste( .$V1 , collapse = "")) %>% # concatenate all in each MgsNo group
  select( MgsBody) %>%
  pull


来源: stackexchange

问:
Check if multiple values in table 1 are defined in table 2 with multiple values
There are two tables: CourseModules and Students.

A student can participate in different modules. If a student succeed the module, it will be stored in the database under StudentsModule with the moduleID.

The table courseModules defines all required modules for a student to get a certificate.

I need an overview of all students that have an certificate.

In the example you can see that the only student that has a certificate is the one with StudentID: 111221

I am completely stuck on this. It needs to be done in one query, not multiple and without using loops.

I tried the following:

```<code>SELECT StudentID, ModuleID<br>
FROM StudentsModule<br>
WHERE ModuleID ALL (
    SELECT OnderdeelID
    FROM CourseModules
    GROUP BY groupID
)
</code>```

But i am stuck.

答:
Try this</p>

```<code>select s.studentId, s.moduleId, cc.courseCount, cd.courseDone
from StudentsModule s
join CourseModulec on s.moduleId = c.moduleId
join (select count(*) as courseCount, groupId from CourseModule group by groupId) as cc on cc.groupId = c.groupId
join (select count(*) as courseDone, studentId from StudentsModule s1 join CourseModule c1 on s1.moduleId = c1.moduleId group by s1.studentId) as cd on cd.studentId = s.studentId
where cc.courseCount = cd.courseDone
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There are two tables: CourseModules and Students.

A student can participate in different modules. If a student succeed the module, it will be stored in the database under StudentsModule with the moduleID.

The table courseModules defines all required modules for a student to get a certificate.

I need an overview of all students that have an certificate.

In the example you can see that the only student that has a certificate is the one with StudentID: 111221

I am completely stuck on this. It needs to be done in one query, not multiple and without using loops.

I tried the following:

SELECT StudentID, ModuleID

FROM StudentsModule

WHERE ModuleID ALL (
    SELECT OnderdeelID
    FROM CourseModules
    GROUP BY groupID
)

But i am stuck.

Body:
Try this

select s.studentId, s.moduleId, cc.courseCount, cd.courseDone
from StudentsModule s
join CourseModulec on s.moduleId = c.moduleId
join (select count(*) as courseCount, groupId from CourseModule group by groupId) as cc on cc.groupId = c.groupId
join (select count(*) as courseDone, studentId from StudentsModule s1 join CourseModule c1 on s1.moduleId = c1.moduleId group by s1.studentId) as cd on cd.studentId = s.studentId
where cc.courseCount = cd.courseDone


问:
Rails ActiveRecord Query: Sum total article view count per category
I have articles that are able to be tagged in categories. I am struggling to create a query which will extract the sum of view count (tracked using impressionist gem) of articles within each category.

Schema:

```<code>  create_table "article_categories", force: :cascade do |t|
    t.integer "article_id"
    t.integer "category_id"
  end

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.bigint "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "impressions_count", default: 0
  end

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
</code>```

Article model

```<code>class Article < ApplicationRecord
  is_impressionable :counter_cache => true, :unique => false
  belongs_to :user
  has_many :impressions, as: :impressionable
  has_many :article_categories
  has_many :categories, through: :article_categories
end
</code>```

Category model

```<code>class Category < ApplicationRecord
  has_many :article_categories
  has_many :articles, through: :article_categories
end
</code>```

ArticleCategory model

```<code>class ArticleCategory < ActiveRecord::Base
  belongs_to :article
  belongs_to :category
end
</code>```

Here is what i have tried so far and the errors when i test in rails console:

```<code>cat_group = Article.joins(:article_categories).group_by(&:category_ids)
// this query results in an array of articles within each category

1) cat_group.sum("impressions_count")
//TypeError: no implicit conversion of Array into String

2) cat_group.select("sum(impressions_count) AS total_count")
//ArgumentError: wrong number of arguments (given 1, expected 0)

3) Article.joins(:article_categories).group(:category_id)

//ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "articles.id" must appear in the GROUP BY clause or be used in an aggregate function
</code>```

答:
If I understand you correctly and view count is impressions_count, here is query that you can use:

```<code>Article.joins(:categories).group('categories.name').sum(:impressions_count)
</code>```

Body:
I have articles that are able to be tagged in categories. I am struggling to create a query which will extract the sum of view count (tracked using impressionist gem) of articles within each category.

Schema:

  create_table "article_categories", force: :cascade do |t|
    t.integer "article_id"
    t.integer "category_id"
  end

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.bigint "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "impressions_count", default: 0
  end

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

Article model

class Article < ApplicationRecord
  is_impressionable :counter_cache => true, :unique => false
  belongs_to :user
  has_many :impressions, as: :impressionable
  has_many :article_categories
  has_many :categories, through: :article_categories
end

Category model

class Category < ApplicationRecord
  has_many :article_categories
  has_many :articles, through: :article_categories
end

ArticleCategory model

class ArticleCategory < ActiveRecord::Base
  belongs_to :article
  belongs_to :category
end

Here is what i have tried so far and the errors when i test in rails console:

cat_group = Article.joins(:article_categories).group_by(&:category_ids)
// this query results in an array of articles within each category

1) cat_group.sum("impressions_count")
//TypeError: no implicit conversion of Array into String

2) cat_group.select("sum(impressions_count) AS total_count")
//ArgumentError: wrong number of arguments (given 1, expected 0)

3) Article.joins(:article_categories).group(:category_id)

//ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "articles.id" must appear in the GROUP BY clause or be used in an aggregate function

Body:
If I understand you correctly and view count is impressions_count, here is query that you can use:

Article.joins(:categories).group('categories.name').sum(:impressions_count)


问:
How to get values from one sub foreach and put this into parent loop and shuffle all values in array
I'm using WordPress and ACF Gallery. In each post I have a gallery with images.

I need to get all images from all galleries and shuffle they.

How I can achieve this?

Now I have this:

```<code>    <?php if ( $query->have_posts() ) : ?>
        <?php while ( $query->have_posts() ) : $query->the_post();
            $images = get_field( 'gallery' );
            $size = 'full';
            if ( $images ) : ?>
                <?php foreach( $images as $image ): ?>
                    <img class="post-gallery" src="<?php echo $image['url']; ?>">
                <?php endforeach; ?>
           <?php endif; ?>
           <?php if (has_post_thumbnail()) : ?>
                <div class="post" style="background-image: url(<?php the_post_thumbnail_url(); ?>);"></div>
<?php endif; ?>
</code>```

I think we need to put somehow all posts and posts's galleries to one array and shuffle it?

Update:  js part(Infinite+masonry+imagesLoaded+randomize blocks

```<code>    var images = $('.container-post .col-50');
for (var i = 0; i < images.length; i++) {
    var imageFirst = Math.floor(Math.random() * images.length -1) + 1;
    var imageSecond = Math.floor(Math.random() * images.length -1) +1;
    images.eq(imageFirst).before(images.eq(imageSecond));
}
var $container = $('.container-post').masonry({
    itemSelector: '.container-post .col-50',
});

$container.imagesLoaded().progress( function() {
    $container.masonry('layout');
});
var masonry = $container.data('masonry');

$container.infiniteScroll({
    outlayer: masonry,
    path: '.wp-pagenavi .page',
    append: '.container-post .col-50',
    scrollThread: 1,
    history: false,
    hideNav: '.wp-pagenavi',
    status: '.page-load-status',
});
</code>```

Have a nice day!

答:
I would personally have PHP do the heavy lifting and, as you said, create a shuffled array that JS can loop over. For example:

```<code><?php
    $collectedImages = [];
    if ($query->have_posts()) {
        while($query->have_posts()) {
            $query->the_post();
            $images = get_field('gallery');
            $size = 'full';
            if ($images === false) {
                continue;
            }

            foreach ($images as $image) {
                $collectedImages[] = $image['url'];
            }
        }
    }
    shuffle($collectedImages);

    foreach ($collectedImages as $image) {
        // Render it!
    }
?>
</code>```

More info:

shuffle() - PHP docs

Body:
I'm using WordPress and ACF Gallery. In each post I have a gallery with images.

I need to get all images from all galleries and shuffle they.

How I can achieve this?

Now I have this:

    <?php if ( $query->have_posts() ) : ?>
        <?php while ( $query->have_posts() ) : $query->the_post();
            $images = get_field( 'gallery' );
            $size = 'full';
            if ( $images ) : ?>
                <?php foreach( $images as $image ): ?>
                    <img class="post-gallery" src="<?php echo $image['url']; ?>">
                <?php endforeach; ?>
           <?php endif; ?>
           <?php if (has_post_thumbnail()) : ?>
                <div class="post" style="background-image: url(<?php the_post_thumbnail_url(); ?>);">

<?php endif; ?>

I think we need to put somehow all posts and posts's galleries to one array and shuffle it?

Update:  js part(Infinite+masonry+imagesLoaded+randomize blocks

    var images = $('.container-post .col-50');
for (var i = 0; i < images.length; i++) {
    var imageFirst = Math.floor(Math.random() * images.length -1) + 1;
    var imageSecond = Math.floor(Math.random() * images.length -1) +1;
    images.eq(imageFirst).before(images.eq(imageSecond));
}
var $container = $('.container-post').masonry({
    itemSelector: '.container-post .col-50',
});

$container.imagesLoaded().progress( function() {
    $container.masonry('layout');
});
var masonry = $container.data('masonry');

$container.infiniteScroll({
    outlayer: masonry,
    path: '.wp-pagenavi .page',
    append: '.container-post .col-50',
    scrollThread: 1,
    history: false,
    hideNav: '.wp-pagenavi',
    status: '.page-load-status',
});

Have a nice day!

Body:
I would personally have PHP do the heavy lifting and, as you said, create a shuffled array that JS can loop over. For example:

<?php
    $collectedImages = [];
    if ($query->have_posts()) {
        while($query->have_posts()) {
            $query->the_post();
            $images = get_field('gallery');
            $size = 'full';
            if ($images === false) {
                continue;
            }

            foreach ($images as $image) {
                $collectedImages[] = $image['url'];
            }
        }
    }
    shuffle($collectedImages);

    foreach ($collectedImages as $image) {
        // Render it!
    }
?>

More info:

shuffle() - PHP docs


问:
How to press "TAB" then "ENTER" key in Selenium WebDriver using Java?
I am doing automation testing using java with Selenium WebDriver. I want to click on tabs. I would like to check tab functionality.

I can use Tab key to get the button as below:

```<code>WebElement webElement = driver.findElementByXPath("");
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
</code>```

I have a form with multiple fields I want to track upon pressing key tab key is my control moving to next field successfully or not. Also I want to check upon which my control is below is my form

But how do I click one by one tab.
Basically I need to achieve press Tab key and then press Enter key to click the button.

I learning selenium.
Please help me. Thanks in advance.

答:
Try the below code.This is working fine.</p>

```<code>        Actions builder = new Actions(driver);
        builder.SendKeys(OpenQA.Selenium.Keys.Tab).Build().Perform();
        builder.Release().Perform();
        builder.SendKeys(OpenQA.Selenium.Keys.Tab).Build().Perform();
        builder.Release().Perform();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am doing automation testing using java with Selenium WebDriver. I want to click on tabs. I would like to check tab functionality.

I can use Tab key to get the button as below:

WebElement webElement = driver.findElementByXPath("");
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);

I have a form with multiple fields I want to track upon pressing key tab key is my control moving to next field successfully or not. Also I want to check upon which my control is below is my form

But how do I click one by one tab.
Basically I need to achieve press Tab key and then press Enter key to click the button.

I learning selenium.
Please help me. Thanks in advance.

Body:
Try the below code.This is working fine.

        Actions builder = new Actions(driver);
        builder.SendKeys(OpenQA.Selenium.Keys.Tab).Build().Perform();
        builder.Release().Perform();
        builder.SendKeys(OpenQA.Selenium.Keys.Tab).Build().Perform();
        builder.Release().Perform();


问:
Array in Array in Array - Cant get data from JSON String
Original Post: Objects in Arrays...

The data I provided was only one line. I have many lines of the same with different "Bestaende" and "Menge":

```<code>[{"Ean":"","Barcode":"010241770148","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770149","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770151","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770152","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90}]
</code>```

The foreach you describe I understand, but it doesn't work as expected .

```<code>$jsonarray = json_decode($jsonfile,true);
echo 'Array 0 Menge: '.$jsonarray['0']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 1 Menge: '.$jsonarray['1']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 2 Menge: '.$jsonarray['2']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 3 Menge: '.$jsonarray['3']['Bestaende']['0']['Menge'].'<br>';
</code>```

brings out

```<code>Array 0 Menge: 1
Array 1 Menge: 1
Array 2 Menge: 1
Array 3 Menge: 1
</code>```

Okay. But when I try to foreach it (because I have a list of base data), the output is only one row. I get only one entry "1". Nothing more.

```<code>$x=0;
foreach($jsonarray[$x]['Bestaende'] as $idx => $Bestaende) {
   echo 'Print Menge: ';
   print_r($Bestaende['Menge']);
 $x++;
}
</code>```

So I try to loop over the Array to get the data. The Result is:

```<code>Array ( [Filiale] => 1 [FilialeBez] => Laden [Menge] => 1 [Gln] => [Dispo] => 0 )
Print Menge: 1
</code>```

I have a problem with the array in array in array ... Is there a better way to get the data I want?

Or is my foreach loop wrong?

答:
```<code>Try this code..
$j = '[{"Ean":"","Barcode":"010241770148","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770149","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770151","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770152","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90}]';

$a = json_decode($j,true);

foreach($a as $key => $value){
    if(!empty($value['Bestaende'])){
        foreach($value['Bestaende'] as $k=>$v){
             echo 'Print Menge: '.(!empty($v['Menge']) ? $v['Menge'] : '').'</br>';
        }
    }
}
</code>```

Body:
Original Post: Objects in Arrays...

The data I provided was only one line. I have many lines of the same with different "Bestaende" and "Menge":

[{"Ean":"","Barcode":"010241770148","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770149","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770151","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
 {"Ean":"","Barcode":"010241770152","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90}]

The foreach you describe I understand, but it doesn't work as expected .

$jsonarray = json_decode($jsonfile,true);
echo 'Array 0 Menge: '.$jsonarray['0']['Bestaende']['0']['Menge'].'
';
echo 'Array 1 Menge: '.$jsonarray['1']['Bestaende']['0']['Menge'].'
';
echo 'Array 2 Menge: '.$jsonarray['2']['Bestaende']['0']['Menge'].'
';
echo 'Array 3 Menge: '.$jsonarray['3']['Bestaende']['0']['Menge'].'
';

brings out

Array 0 Menge: 1
Array 1 Menge: 1
Array 2 Menge: 1
Array 3 Menge: 1

Okay. But when I try to foreach it (because I have a list of base data), the output is only one row. I get only one entry "1". Nothing more.

$x=0;
foreach($jsonarray[$x]['Bestaende'] as $idx => $Bestaende) {
   echo 'Print Menge: ';
   print_r($Bestaende['Menge']);
 $x++;
}

So I try to loop over the Array to get the data. The Result is:

Array ( [Filiale] => 1 [FilialeBez] => Laden [Menge] => 1 [Gln] => [Dispo] => 0 )
Print Menge: 1

I have a problem with the array in array in array ... Is there a better way to get the data I want?

Or is my foreach loop wrong?


问:
Angular, how to make other elements false when one element is true
i need help to make other elements condition's false when one element's condition is true and if it is possible only one that can be true at a time. I'm not sure what i wrote is correct. Can anyone help me, please?

showProduct: boolean = false;
showCustomer: boolean = false;
showSupplier: boolean = false;

if (showProduct = true) {
  this.showCustomer = false;
  this.showSupplier = false;
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>

<div *ngIf="showProduct" align="center">
  <app-product></app-product>
</div>

<div *ngIf="showCustomer" align="center">
  <app-customer></app-customer>
</div>

<div *ngIf="showSupplier" align="center">
  <app-supplier></app-supplier>
</div></code>```

Please let me know if more snippets are needed. Thank you in advance.

答:
so something like this while creating a dummy object obj and mainobject mainObj to bind on the UI.</p>

```<code>showProduct: boolean = false;
showCustomer: boolean = false;
showSupplier

mainObj = {};
obj = {
    showProduct: false,
    showCustomer: false,
    showSupplier: false
}

<a href="#" (click)="updateObj('showProduct')"></a>
<a href="#" (click)="updateObj('showCustomer')"></a>
<a href="#" (click)="updateObj('showSupplier')"></a>

function updateObj(prope){
    mainObj = Object.assign(obj, mainObj);
    mainObj[prope] = true;
}

<div *ngIf="mainObj.showProduct" align="center">
  <app-product></app-product>
</div>

<div *ngIf="mainObj.showCustomer" align="center">
  <app-customer></app-customer>
</div>

<div *ngIf="mainObj.showSupplier" align="center">
  <app-supplier></app-supplier>
</div>
</code>```

Body:
i need help to make other elements condition's false when one element's condition is true and if it is possible only one that can be true at a time. I'm not sure what i wrote is correct. Can anyone help me, please?

showProduct: boolean = false;
showCustomer: boolean = false;
showSupplier: boolean = false;

if (showProduct = true) {
  this.showCustomer = false;
  this.showSupplier = false;
}

  <app-product></app-product>

  <app-customer></app-customer>

  <app-supplier></app-supplier>

Please let me know if more snippets are needed. Thank you in advance.

Body:
so something like this while creating a dummy object obj and mainobject mainObj to bind on the UI.

showProduct: boolean = false;
showCustomer: boolean = false;
showSupplier

mainObj = {};
obj = {
    showProduct: false,
    showCustomer: false,
    showSupplier: false
}

<a href="#" (click)="updateObj('showProduct')"></a>
<a href="#" (click)="updateObj('showCustomer')"></a>
<a href="#" (click)="updateObj('showSupplier')"></a>

function updateObj(prope){
    mainObj = Object.assign(obj, mainObj);
    mainObj[prope] = true;
}

<div *ngIf="mainObj.showProduct" align="center">
  <app-product></app-product>
</div>

<div *ngIf="mainObj.showCustomer" align="center">
  <app-customer></app-customer>
</div>

<div *ngIf="mainObj.showSupplier" align="center">
  <app-supplier></app-supplier>
</div>


问:
php  how to pass value to another page when click the href? and how to retrieve the value from another page?
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

```<code>                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '<label class="label1">' . $row->name . '</label><br><br>';
                    echo '<a href="#"><img src="' . $row->image . '" class="poster"></a>';
                    echo '<div class = "section3"><a href="synopsis.php?id="' . $row->id . '" >asd</a>&nbsp &nbsp <a href="">Buy Now</a>';
                }
            }

            ?>
</code>```

答:
in the first page

```<code>echo '<a href="next_page.php?next_id='. $row->id.'"><img src="' . $row->image . '" class="poster"></a>';
</code>```

to retrieve

```<code>$_GET['next_id'];
</code>```

Title: php <a href> how to pass value to another page when click the href? and how to retrieve the value from another page?

Body:
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '' . $row->name . '

';
                    echo 'image . '" class="poster">';
                    echo '
id . '" >asd&nbsp &nbsp Buy Now';
                }
            }

            ?>

Body:
in the first page

echo '<a href="next_page.php?next_id='. $row->id.'"><img src="' . $row->image . '" class="poster"></a>';

to retrieve

$_GET['next_id'];


问:
Empty pages in RDLC-Report
I have a rdlc report that conains a tablix, nothing other. The Tablix expands in horizontal direction to show days and in the vertical direction to show groups.

The tablix works as expected, as long as I set the width of the content area equal to the width of the tablix.

If I expand the content size to its fixed size (approximately PageWidth-PageBorders) and run the report, every second page is an empty page.

However the tablix only uses one page. Every odd page is absolutely empty. It seems that the tablix adds its horizontal expansion to the currently definied content width and calculates then the overflow.

The reportviewer Version is 3 (2010 Redistributable)

Does someone have a solution for this odd behaviour?

Update

If I export the report to excel, I see that there is on the right site of the tablix a column that is exactly as long as the generated items for the days. It seems realy to be a bug or a feature I don't see how to deactivate.

I also have tried to create the same construction from a table, and it resulted in the same problem, what not is astonishing, because the table is internally also a tablix.

Update 1

If I set the property "ConsumeContainerWhitespace" of the report to true, the above test version works. But if I place then other elements in the "white" area, the effect reocurrs.

答:
You need to make sure your RDLC Report have :

ConsumeContainerWhiteSpace = true (open by click F4)

Report Body Size <= Page Size+margin Size. (open by Ctrl + Alt + D)

ContentLicense: CC BY-SA 2.5

Title: Empty pages in RDLC-Report


问:
Unable to plot line in the animation
I have created an animated line in Matplotlib which moves from left to right of the curve using my script below:

```<code>from __future__ import division
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation

X =  #Time scale in milliseconds, converted to seconds

# Data to plot the curves
Y1 = data_orig[410:524,4]
Y2 = data_orig[410:524,3]
Y3 = data_orig[410:524,2]

plt.plot(X, Y1, 'r--', X, Y2, 'b--', X, Y3, 'g--')
plt.grid(True)

plt.xlabel('Time [s]')
plt.ylabel('Force [N]')

X_MIN = 0.0  //0
X_MAX = 0.6  //600
Y_MIN = -300
Y_MAX = 1500
X_VALS = np.arange(X_MIN, X_MAX+1);

def update_line(num, line):
    i = X_VALS[num]
    line.set_data( [i, i], [Y_MIN, Y_MAX])
    return line,

#l , v = plt.plot(0, -200, 600, 1500, linewidth=2, color= 'gold')
l , v = plt.plot(0.0, -200, 0.6, 1500, linewidth=2, color= 'gold')

anim = animation.FuncAnimation(fig, update_line, len(X_VALS), fargs=(l, ), interval=15, blit=False, repeat=False)

plt.show()
</code>```

Problem: The line works if the values in X_MIN and X_MAX is set to 0 and 600 respectively. But when I divide this by 1000(to convert to seconds, the line disappears. There is no error which pops as well.

Before (with 0 and 600)

After (with 0.0 and 0.6)

What I am doing wrong? How could I solve this?

答:
Possible problem lies in the following line:

```<code>X_VALS = np.arange(X_MIN, X_MAX+1);
</code>```

You did not specify some step size, therefore when X_MIN and X_MAX is 0 and 0.6, X_VALS only is an array with two entries, [0, 1]

So, a possible minimal version works pretty well:

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

def update_line(num, line):
    i = X_VALS[num]
    line.set_data([i, i], [Y_MIN, Y_MAX])
    return line,

X_MIN = 0.0
X_MAX = 0.6
Y_MIN = -300
Y_MAX = 1500
step_size = 0.01

fig = plt.figure()
plt.plot([X_MIN, X_MAX], [Y_MIN, Y_MAX], 'r--',)
plt.grid(True)

plt.xlabel('Time [s]')
plt.ylabel('Force [N]')

X_VALS = np.arange(X_MIN, X_MAX + step_size, step_size)

l, v = plt.plot(0.0, -200, 0.6, 1500, linewidth=2, color= 'gold')

anim = animation.FuncAnimation(fig, update_line, len(X_VALS), fargs=(l, ), interval=15, blit=False, repeat=False)

plt.show()
</code>```

Title: Unable to plot line in the animation

Body:
I have created an animated line in Matplotlib which moves from left to right of the curve using my script below:

from __future__ import division
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation

X =  #Time scale in milliseconds, converted to seconds

# Data to plot the curves
Y1 = data_orig[410:524,4]
Y2 = data_orig[410:524,3]
Y3 = data_orig[410:524,2]

plt.plot(X, Y1, 'r--', X, Y2, 'b--', X, Y3, 'g--')
plt.grid(True)

plt.xlabel('Time [s]')
plt.ylabel('Force [N]')

X_MIN = 0.0  //0
X_MAX = 0.6  //600
Y_MIN = -300
Y_MAX = 1500
X_VALS = np.arange(X_MIN, X_MAX+1);

def update_line(num, line):
    i = X_VALS[num]
    line.set_data( [i, i], [Y_MIN, Y_MAX])
    return line,

#l , v = plt.plot(0, -200, 600, 1500, linewidth=2, color= 'gold')
l , v = plt.plot(0.0, -200, 0.6, 1500, linewidth=2, color= 'gold')

anim = animation.FuncAnimation(fig, update_line, len(X_VALS), fargs=(l, ), interval=15, blit=False, repeat=False)

plt.show()

Problem: The line works if the values in X_MIN and X_MAX is set to 0 and 600 respectively. But when I divide this by 1000(to convert to seconds, the line disappears. There is no error which pops as well.

Before (with 0 and 600)

After (with 0.0 and 0.6)

What I am doing wrong? How could I solve this?

Body:
Possible problem lies in the following line:

X_VALS = np.arange(X_MIN, X_MAX+1);

You did not specify some step size, therefore when X_MIN and X_MAX is 0 and 0.6, X_VALS only is an array with two entries, [0, 1]

So, a possible minimal version works pretty well:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

def update_line(num, line):
    i = X_VALS[num]
    line.set_data([i, i], [Y_MIN, Y_MAX])
    return line,

X_MIN = 0.0
X_MAX = 0.6
Y_MIN = -300
Y_MAX = 1500
step_size = 0.01

fig = plt.figure()
plt.plot([X_MIN, X_MAX], [Y_MIN, Y_MAX], 'r--',)
plt.grid(True)

plt.xlabel('Time [s]')
plt.ylabel('Force [N]')

X_VALS = np.arange(X_MIN, X_MAX + step_size, step_size)

l, v = plt.plot(0.0, -200, 0.6, 1500, linewidth=2, color= 'gold')

anim = animation.FuncAnimation(fig, update_line, len(X_VALS), fargs=(l, ), interval=15, blit=False, repeat=False)

plt.show()


问:
What is the meaning of 2D stride in convolution?
I know what meaning stride has when it is just an integer number (by which step you should apply filter to image). But what about (1, 1) or even more dimensional stride?

答:
The stride defines how the filter is moved along the input image (tensor). Nothing stops you from striding along different axes differently, e.g., stride=[1, 2] means move 1px at a time along 0 axis, and 2px at a time along 1 axis. This particular combination isn't common, but possible.

Tensorflow API goes even further and allows custom striding for all axes of the 4D input tensor (see tf.nn.conv2d). Using this API it's not uncommon to set strides=[1, 2, 2, 1], which makes perfect sense: it should process each image (the first 1) and each input channel (the last 1), but apply 2x2 striding of the spatial dimensions. As far as the convolution is concerned, the operation is applicable for any strides array, however not values are equally useful.

Highly recommend this CS231n tutorial for more detail on this.


问:
How to update center coordinates of Google map every X seconds in Unity C#?
I am making pokemon go-like game. I want to update my map wherever I go using my GPS. But for now, I want to update the coordinates. Shall I use for loop?

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GoogleMap : MonoBehaviour {
    public RawImage image;
    string url;

    public float lon, lat;

    LocationInfo locationInfo;

    public enum mapType {roadmap, satellite, hybrid, terrain}
    public mapType mapSelected;
    public int scale;

    IEnumerator Map(){
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc";
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=14.679046,120.540874&zoom=19&size=640x640&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&scale=2";
        url = "https://maps.googleapis.com/maps/api/staticmap?&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&center=14.679155295230377,120.54045265601641&zoom=18&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text%7Cvisibility:off&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=640x640&scale=2";
        WWW www = new WWW (url);
        yield return www;
        image.texture = www.texture;
        image.SetNativeSize ();
    }

    // Use this for initialization
    void Start () {
        image = gameObject.GetComponent<RawImage> ();
        StartCoroutine (Map());
    }

    // Update is called once per frame
    void Update () {

    }
}
</code>```

答:
You can use raw NMEA data from GPS via NmeaListener like in this answer on java:

```<code>public class CustomNmeaListener implements GpsStatus.NmeaListener{

    private GoogleMap mGoogleMap;
    private Marker mMarkerPosition = null;
    private BitmapDescriptor mMarkerMoveDescriptor;
    private BitmapDescriptor mMarkerStopDescriptor;

    public CustomNmeaListener(GoogleMap googleMap, int markerMoveResource, int markerStopResource){
        this.mGoogleMap = googleMap;

        mMarkerMoveDescriptor = BitmapDescriptorFactory.fromResource(markerMoveResource);
        mMarkerStopDescriptor = BitmapDescriptorFactory.fromResource(markerStopResource);
    }

    @Override
    public void onNmeaReceived(long timestamp, String nmea) {
        double latitude;
        double longitude;
        float speed;
        float angle;

        // parse NMEA RMC sentence
        // Example $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
        //   nmea    [0]   [1]  [2]  [3]   [4]   [5]   [6] [7]   [8]   [9]   [10]  [11]
        if (nmea.startsWith("$GPRMC")) {

            String[] nmeaParts = nmea.split(",");

            // if RMC data valid ("active")
            if (nmeaParts[2].equals("A")) {
                latitude = parseLatitude(nmeaParts[3], nmeaParts[4]);
                longitude = parseLongitude(nmeaParts[5], nmeaParts[6]);
                speed = parseSpeed(nmeaParts[7]);
                angle = parseAngle(nmeaParts[8]);

                // remove marker on "old" position
                if (mMarkerPosition != null) {
                    mMarkerPosition.remove();
                }

                MarkerOptions positionMarkerOptions;

                if (speed > 0) {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerMoveDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(angle);
                } else {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerStopDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(0);
                }
                mMarkerPosition = mGoogleMap.addMarker(positionMarkerOptions);
            }
        }

    }

    static float parseLatitude(String lat, String sign) {
        float latitude = Float.parseFloat(lat.substring(2)) / 60.0f;
        latitude +=  Float.parseFloat(lat.substring(0, 2));
        if(sign.startsWith("S")) {
            latitude = -latitude;
        }
        return latitude;
    }

    static float parseLongitude(String lon, String sign) {
        float longitude = Float.parseFloat(lon.substring(3)) / 60.0f;
        longitude +=  Float.parseFloat(lon.substring(0, 3));
        if(sign.startsWith("W")) {
            longitude = -longitude;
        }
        return longitude;
    }

    static float parseSpeed(String knots) {
        float speed;
        try {
            speed = Float.parseFloat(knots);
        } catch (Exception e) {
            speed = 0;
        }
        return speed;
    }

    static float parseAngle(String ang) {
        float angle;
        try {
            angle = Float.parseFloat(ang);
        } catch (Exception e) {
            angle = 0;
        }
        return angle;
    }
}
</code>```

and you can set update interval via LocationManager.requestLocationUpdates() like that way:

```<code> try {
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            <your_update_interval>,
            LOCATION_DISTANCE,
            this
    );
 } catch (java.lang.SecurityException ex) {
    Log.d(TAG, "fail to request location update, ignore", ex);
 }
</code>```

Body:
I am making pokemon go-like game. I want to update my map wherever I go using my GPS. But for now, I want to update the coordinates. Shall I use for loop?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GoogleMap : MonoBehaviour {
    public RawImage image;
    string url;

    public float lon, lat;

    LocationInfo locationInfo;

    public enum mapType {roadmap, satellite, hybrid, terrain}
    public mapType mapSelected;
    public int scale;

    IEnumerator Map(){
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc";
        //url = "https://maps.googleapis.com/maps/api/staticmap?center=14.679046,120.540874&zoom=19&size=640x640&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&scale=2";
        url = "https://maps.googleapis.com/maps/api/staticmap?&key=AIzaSyB41TT9I-4eK5zcl_n4tarK79QzgyVD4lc&center=14.679155295230377,120.54045265601641&zoom=18&format=png&maptype=roadmap&style=element:geometry%7Ccolor:0x1d2c4d&style=element:labels.text.fill%7Ccolor:0x8ec3b9&style=element:labels.text.stroke%7Ccolor:0x1a3646&style=feature:administrative.country%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:administrative.land_parcel%7Celement:labels.text.fill%7Ccolor:0x64779e&style=feature:administrative.province%7Celement:geometry.stroke%7Ccolor:0x4b6878&style=feature:landscape.man_made%7Celement:geometry.stroke%7Ccolor:0x334e87&style=feature:landscape.natural%7Celement:geometry%7Ccolor:0x023e58&style=feature:poi%7Celement:geometry%7Ccolor:0x283d6a&style=feature:poi%7Celement:labels.text.fill%7Ccolor:0x6f9ba5&style=feature:poi%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:poi.business%7Cvisibility:off&style=feature:poi.park%7Celement:geometry.fill%7Ccolor:0x023e58&style=feature:poi.park%7Celement:labels.text%7Cvisibility:off&style=feature:poi.park%7Celement:labels.text.fill%7Ccolor:0x3C7680&style=feature:road%7Celement:geometry%7Ccolor:0x304a7d&style=feature:road%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:road%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:road.highway%7Celement:geometry%7Ccolor:0x2c6675&style=feature:road.highway%7Celement:geometry.stroke%7Ccolor:0x255763&style=feature:road.highway%7Celement:labels.text.fill%7Ccolor:0xb0d5ce&style=feature:road.highway%7Celement:labels.text.stroke%7Ccolor:0x023e58&style=feature:transit%7Celement:labels.text.fill%7Ccolor:0x98a5be&style=feature:transit%7Celement:labels.text.stroke%7Ccolor:0x1d2c4d&style=feature:transit.line%7Celement:geometry.fill%7Ccolor:0x283d6a&style=feature:transit.station%7Celement:geometry%7Ccolor:0x3a4762&style=feature:water%7Celement:geometry%7Ccolor:0x0e1626&style=feature:water%7Celement:labels.text.fill%7Ccolor:0x4e6d70&size=640x640&scale=2";
        WWW www = new WWW (url);
        yield return www;
        image.texture = www.texture;
        image.SetNativeSize ();
    }

    // Use this for initialization
    void Start () {
        image = gameObject.GetComponent<RawImage> ();
        StartCoroutine (Map());
    }

    // Update is called once per frame
    void Update () {

    }
}

Body:
You can use raw NMEA data from GPS via NmeaListener like in this answer on java:

public class CustomNmeaListener implements GpsStatus.NmeaListener{

    private GoogleMap mGoogleMap;
    private Marker mMarkerPosition = null;
    private BitmapDescriptor mMarkerMoveDescriptor;
    private BitmapDescriptor mMarkerStopDescriptor;

    public CustomNmeaListener(GoogleMap googleMap, int markerMoveResource, int markerStopResource){
        this.mGoogleMap = googleMap;

        mMarkerMoveDescriptor = BitmapDescriptorFactory.fromResource(markerMoveResource);
        mMarkerStopDescriptor = BitmapDescriptorFactory.fromResource(markerStopResource);
    }

    @Override
    public void onNmeaReceived(long timestamp, String nmea) {
        double latitude;
        double longitude;
        float speed;
        float angle;

        // parse NMEA RMC sentence
        // Example $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
        //   nmea    [0]   [1]  [2]  [3]   [4]   [5]   [6] [7]   [8]   [9]   [10]  [11]
        if (nmea.startsWith("$GPRMC")) {

            String[] nmeaParts = nmea.split(",");

            // if RMC data valid ("active")
            if (nmeaParts[2].equals("A")) {
                latitude = parseLatitude(nmeaParts[3], nmeaParts[4]);
                longitude = parseLongitude(nmeaParts[5], nmeaParts[6]);
                speed = parseSpeed(nmeaParts[7]);
                angle = parseAngle(nmeaParts[8]);

                // remove marker on "old" position
                if (mMarkerPosition != null) {
                    mMarkerPosition.remove();
                }

                MarkerOptions positionMarkerOptions;

                if (speed > 0) {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerMoveDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(angle);
                } else {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerStopDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(0);
                }
                mMarkerPosition = mGoogleMap.addMarker(positionMarkerOptions);
            }
        }

    }

    static float parseLatitude(String lat, String sign) {
        float latitude = Float.parseFloat(lat.substring(2)) / 60.0f;
        latitude +=  Float.parseFloat(lat.substring(0, 2));
        if(sign.startsWith("S")) {
            latitude = -latitude;
        }
        return latitude;
    }

    static float parseLongitude(String lon, String sign) {
        float longitude = Float.parseFloat(lon.substring(3)) / 60.0f;
        longitude +=  Float.parseFloat(lon.substring(0, 3));
        if(sign.startsWith("W")) {
            longitude = -longitude;
        }
        return longitude;
    }

    static float parseSpeed(String knots) {
        float speed;
        try {
            speed = Float.parseFloat(knots);
        } catch (Exception e) {
            speed = 0;
        }
        return speed;
    }

    static float parseAngle(String ang) {
        float angle;
        try {
            angle = Float.parseFloat(ang);
        } catch (Exception e) {
            angle = 0;
        }
        return angle;
    }
}

and you can set update interval via LocationManager.requestLocationUpdates() like that way:

 try {
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            <your_update_interval>,
            LOCATION_DISTANCE,
            this
    );
 } catch (java.lang.SecurityException ex) {
    Log.d(TAG, "fail to request location update, ignore", ex);
 }


问:
Find elements by offset position with jQuery
Is there a simple method to fetch all elements at a specific offset position (by using jQuery)? Or do I have to check the offset of each element in the DOM?</p>

答: Call document.elementFromPoint.

Body: Call document.elementFromPoint.


答:
You can change the logic of your code:

Show product
Show customer
Show supplier

  <app-product></app-product>

  <app-customer></app-customer>

  <app-supplier></app-supplier>

```
</div>
</div>
</p>

<p>In your component's class:</p>

```show: string = 'product';
```

Title: Angular, how to make other elements false when one element is true

Body:
You can change the logic of your code:

<a href="#" (click)="show='product'">Show product</a>
<a href="#" (click)="show='customer'">Show customer</a>
<a href="#" (click)="show='supplier'">Show supplier</a>

<div *ngIf="show==='product'" align="center">
  <app-product></app-product>
</div>

<div *ngIf="show==='customer'" align="center">
  <app-customer></app-customer>
</div>

<div *ngIf="show==='supplier'" align="center">
  <app-supplier></app-supplier>
</div>

In your component's class:

show: string = 'product';


问:
Polymer - How to remove an item from iron-list?
This live snippet builds a web-component which uses iron-list. Each item in the list has a delete button which, on click, removes the item from the list.
When an item is removed, all the next items shift up, but the last item displayed stays rather than disapear as it should be.

According to this stackoverflow, simply by firing the event resize on the iron-list should be enough. But in my snippet, this doesn't help. Nether the iron-resize or the notifyResize function from the official iron-list documentation.

<link rel="import"  href="https://polygit.org/components/polymer/polymer-element.html">
<link rel="import"  href="https://polygit.org/components/iron-list/iron-list.html">
<link rel="import"  href="https://polygit.org/components/paper-button/paper-button.html">

<dom-module id="my-list">
  <template>

    <iron-list id="list" items="{{items}}">

      <template>

            {{item}}

          <paper-button on-tap="_onDeleteClicked"
          style="background: red; color: white;">Remove</paper-button>

      </template>

    </iron-list>

  </template>

</dom-module>

<my-list></my-list>```

答:
"It's simple! The css display property of the root element, in the iron-list's template, must not be set. Then just wrap your flexbox in another simple div."

Here's the live snippet solved:

<link rel="import"  href="https://polygit.org/components/polymer/polymer-element.html">
<link rel="import"  href="https://polygit.org/components/iron-list/iron-list.html">
<link rel="import"  href="https://polygit.org/components/paper-button/paper-button.html">

<dom-module id="my-list">
  <template>

    <iron-list id="list" items="{{items}}">

      <template>

            {{item}}

          <paper-button on-tap="_onDeleteClicked"
          style="background: red; color: white;">Remove</paper-button>

      </template>

    </iron-list>

  </template>

</dom-module>

<my-list></my-list>```

Body:
"It's simple! The css display property of the root element, in the iron-list's template, must not be set. Then just wrap your flexbox in another simple div."

Here's the live snippet solved:

<script src="https://polygit.org/components/webcomponentsjs/webcomponents-loader.js"></script>

<link rel="import"  href="https://polygit.org/components/polymer/polymer-element.html">
<link rel="import"  href="https://polygit.org/components/iron-list/iron-list.html">
<link rel="import"  href="https://polygit.org/components/paper-button/paper-button.html">

<dom-module id="my-list">
  <template>

    <iron-list id="list" items="{{items}}">

      <template>
         <!--YOU MUST NO CHANGE THE CSS DISPLAY PROPERTY OF THE ROOT ELEMENT OF THE TEMPLATE!-->
        <div>

         <div style="display:flex; justify-content: space-between; align-items: center;">

          <div style="margin: 20px; ">
            {{item}}
          </div>

          <paper-button on-tap="_onDeleteClicked"
          style="background: red; color: white;">Remove</paper-button>
         </div>

        </div>
      </template>

    </iron-list>

  </template>

  <script>
    class MyList extends Polymer.Element {
      static get is() { return "my-list"; }

      // set this element's employees property
      constructor() {
        super();
        this.items = [1,2,3,4];
      }

      _onDeleteClicked(event){
        this.splice("items", event.model.index, 1);
        this.$.list.notifyResize();
      }
    }
  customElements.define(MyList.is, MyList);
  </script>

</dom-module>

<my-list></my-list>


问:
Need insight on how to build javascript fetch API
I am creating a web app with django rest framework as backend and react as frontend. The react app i generated from create-react-app. To make api call, i use fetch Api. I see some repetition in my api call that need to a reafactor. But i know which pattern is better here.

Here is the code:

Api.js

```<code>let _options = {headers: new Headers({'Content-Type': 'application/json'})}

const _url = {
  'users': '/api/users/',
  'obtain-token': '/api/obtain-token/',
  'verify-token': '/api/verify-token/',
  'refresh-token': '/api/refresh-token/'
}

const _fetch = (request) => {
  return fetch(request)
    .then(res => {
      if ( ! res.ok) {
        let err = {
          'status': res.status,
          'statusText': res.statusText,
          'data': {}
        }
        return res.json().then(
          data => {
            err.data = data
            return Promise.reject(new Error(JSON.stringify(err)))
          },
          () => Promise.reject(new Error(JSON.stringify(err)))
        )
      }

      return res.json()
    })
    .catch(err => {
      return Promise.reject(err)
    })
}

export const obtainToken = (username, password) => {
  const credential = {username, password}

  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify(credential)

  const request = new Request(_url['obtain-token'], options)

  return _fetch(request)
}

export const verifyToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['verify-token'], options)

  return _fetch(request)
}

export const refreshToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['refresh-token'], options)

  return _fetch(request)
}

export const getUser = (username, token='') => {
  let options = _options
  options.method = 'GET'
  if (token) options.headers.append('Authorization', `JWT ${token}`)

  const request = new Request(`${_url['users']}/${username}`, options)

  return _fetch(request)
}
</code>```

What i like from this code is, when i need to request a resource, i just run a function with needed parameter without knowing it is get or post or else, and i dont need to pass header configuration and url.

```<code>// example api call
let token = '4346h9r7yt47t9...'

verifyToken(token)
  .then(data => {
    // server response json available here

    token = data.token
  })
  .catch(err => {
    // handle network error and bad response here

    console.log(err)
  })
</code>```

Im follwing @challenger solution. And manage to get it shorter with this:

```<code>// Change _build function name to makeRequest and export it
const makeRequest = (name, _url='', body=undefined, headers={}) => {
  let [method, url] = source[name]
  let options = {
     headers: new Headers({
       'Content-Type': 'application/json',
       ...headers,
     })
   }
  options.method = method
  if (body) options.body = JSON.stringify(body)
  return _fetch(url+_url, options)
}

export default makeRequest
</code>```

But, of course to call this function i need to supply the appended url, and a custom header if needed. But as this project goes it's proved that appended url (use by user detail resource) and costum header (use by resource that need authentication) is needed.

答:
```<code>let source = {
  'getUser': (..._p) => ['GET', `/api/users/${_p[0]}`, undefined, {'Authorization': `JWT ${_p[1]}`}],
  'obtainToken': (..._p) => ['POST','/api/obtain-token/', {username:_p[0], password:_p[1]}],
  'verifyToken': (..._p) => ['POST','/api/verify-token/', {token:_p[0]}],
  'refreshToken': (..._p) => ['POST', '/api/refresh-token/',{token:_p[0]}]
}

const requests = {}
Object.keys(source).forEach(key => {
  requests[key] = (...params) => {
    let [method, url, body, headers ={}] = source[key](...params)
    let options = {
       headers: new Headers({
         'Content-Type': 'application/json',
         ...headers,
       })
     }
    options.method = method
    if (body) options.body = JSON.stringify(body)
    return _fetch(new Request(url, options))
  }
})

export default requests
</code>```

it needs more testing and review..

Body:
I am creating a web app with django rest framework as backend and react as frontend. The react app i generated from create-react-app. To make api call, i use fetch Api. I see some repetition in my api call that need to a reafactor. But i know which pattern is better here.

Here is the code:

Api.js

let _options = {headers: new Headers({'Content-Type': 'application/json'})}

const _url = {
  'users': '/api/users/',
  'obtain-token': '/api/obtain-token/',
  'verify-token': '/api/verify-token/',
  'refresh-token': '/api/refresh-token/'
}

const _fetch = (request) => {
  return fetch(request)
    .then(res => {
      if ( ! res.ok) {
        let err = {
          'status': res.status,
          'statusText': res.statusText,
          'data': {}
        }
        return res.json().then(
          data => {
            err.data = data
            return Promise.reject(new Error(JSON.stringify(err)))
          },
          () => Promise.reject(new Error(JSON.stringify(err)))
        )
      }

      return res.json()
    })
    .catch(err => {
      return Promise.reject(err)
    })
}

export const obtainToken = (username, password) => {
  const credential = {username, password}

  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify(credential)

  const request = new Request(_url['obtain-token'], options)

  return _fetch(request)
}

export const verifyToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['verify-token'], options)

  return _fetch(request)
}

export const refreshToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['refresh-token'], options)

  return _fetch(request)
}

export const getUser = (username, token='') => {
  let options = _options
  options.method = 'GET'
  if (token) options.headers.append('Authorization', `JWT ${token}`)

  const request = new Request(`${_url['users']}/${username}`, options)

  return _fetch(request)
}

What i like from this code is, when i need to request a resource, i just run a function with needed parameter without knowing it is get or post or else, and i dont need to pass header configuration and url.

// example api call
let token = '4346h9r7yt47t9...'

verifyToken(token)
  .then(data => {
    // server response json available here

    token = data.token
  })
  .catch(err => {
    // handle network error and bad response here

    console.log(err)
  })

Im follwing @challenger solution. And manage to get it shorter with this:

// Change _build function name to makeRequest and export it
const makeRequest = (name, _url='', body=undefined, headers={}) => {
  let [method, url] = source[name]
  let options = {
     headers: new Headers({
       'Content-Type': 'application/json',
       ...headers,
     })
   }
  options.method = method
  if (body) options.body = JSON.stringify(body)
  return _fetch(url+_url, options)
}

export default makeRequest

But, of course to call this function i need to supply the appended url, and a custom header if needed. But as this project goes it's proved that appended url (use by user detail resource) and costum header (use by resource that need authentication) is needed.

Body:
let source = {
  'getUser': (..._p) => ['GET', `/api/users/${_p[0]}`, undefined, {'Authorization': `JWT ${_p[1]}`}],
  'obtainToken': (..._p) => ['POST','/api/obtain-token/', {username:_p[0], password:_p[1]}],
  'verifyToken': (..._p) => ['POST','/api/verify-token/', {token:_p[0]}],
  'refreshToken': (..._p) => ['POST', '/api/refresh-token/',{token:_p[0]}]
}

const requests = {}
Object.keys(source).forEach(key => {
  requests[key] = (...params) => {
    let [method, url, body, headers ={}] = source[key](...params)
    let options = {
       headers: new Headers({
         'Content-Type': 'application/json',
         ...headers,
       })
     }
    options.method = method
    if (body) options.body = JSON.stringify(body)
    return _fetch(new Request(url, options))
  }
})

export default requests

it needs more testing and review..


问:
How to change a tabLayout clickable background color?
I know clickable background's can made a selector xml. But it's giving me following error(app:tabBackground):

Caused by: android.content.res.Resources$NotFoundException: File res/color/tab_selector.xml from drawable resource ID #0x7f050062

My Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.khash.copytimejava.MainActivity"
    android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabBackground="@color/tab_selector"
            app:tabTextColor="@android:color/white"
            app:tabTextAppearance="@style/TabLayoutTextStyle"
            app:tabSelectedTextColor="@android:color/white"/>

        <FrameLayout
            android:id="@+id/frame_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>
</code>```

My tab selector xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorBlueWithAlpha" android:state_selected="true"></item>
    <item android:color="@color/colorBlueWithAlpha" android:state_pressed="true"></item>
    <item android:color="@color/colorPrimary"></item>
</selector>
</code>```

When i change

```<code>app:tabBackground="@color/tab_selector"
</code>```

to

```<code>app:tabBackground="@android:color/colorPrimary"
</code>```

it's working correctly.

Why it's giving me .Resources$NotFoundException?

Error Log after moved it drawable folder(and named tab_color):

```<code>FATAL EXCEPTION: main Process: com.example.khash.time, PID: 31922
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khash.time/com.example.khash.time.MainActivity}: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.content.res.Resources.loadDrawable(Resources.java:3457)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)
    at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: <item> tag requires a 'drawable' attribute or child tag defining a drawable
    at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:181)
    at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:990)
    at android.graphics.drawable.Drawable.createFromXml(Drawable.java:930)
    at android.content.res.Resources.loadDrawable(Resources.java:3453)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)         at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Step 1: Buddy create an xml file in your res/values folder and name it as colors.

Step 2: In that file colors give your required color as:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="tab_selector">#008080</color>
</resources>
</code>```

Instead of #008080 use color of your choice.

Body:
I know clickable background's can made a selector xml. But it's giving me following error(app:tabBackground):

Caused by: android.content.res.Resources$NotFoundException: File res/color/tab_selector.xml from drawable resource ID #0x7f050062

My Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.khash.copytimejava.MainActivity"
    android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabBackground="@color/tab_selector"
            app:tabTextColor="@android:color/white"
            app:tabTextAppearance="@style/TabLayoutTextStyle"
            app:tabSelectedTextColor="@android:color/white"/>

        <FrameLayout
            android:id="@+id/frame_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>

My tab selector xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorBlueWithAlpha" android:state_selected="true"></item>
    <item android:color="@color/colorBlueWithAlpha" android:state_pressed="true"></item>
    <item android:color="@color/colorPrimary"></item>
</selector>

When i change

app:tabBackground="@color/tab_selector"

to

app:tabBackground="@android:color/colorPrimary"

it's working correctly.

Why it's giving me .Resources$NotFoundException?

Error Log after moved it drawable folder(and named tab_color):

FATAL EXCEPTION: main Process: com.example.khash.time, PID: 31922
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khash.time/com.example.khash.time.MainActivity}: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/tab_color.xml from drawable resource ID #0x7f070075
    at android.content.res.Resources.loadDrawable(Resources.java:3457)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)
    at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: <item> tag requires a 'drawable' attribute or child tag defining a drawable
    at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:181)
    at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:990)
    at android.graphics.drawable.Drawable.createFromXml(Drawable.java:930)
    at android.content.res.Resources.loadDrawable(Resources.java:3453)
    at android.content.res.Resources.getDrawable(Resources.java:1897)
    at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:353)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
    at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
    at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
    at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1518)
    at android.support.design.widget.TabLayout.createTabView(TabLayout.java:932)         at android.support.design.widget.TabLayout.newTab(TabLayout.java:569)
    at com.example.khash.time.MainActivity.setupTabLayout(MainActivity.java:44)
    at com.example.khash.time.MainActivity.onCreate(MainActivity.java:30)
    at android.app.Activity.performCreate(Activity.java:5605)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
    at android.app.ActivityThread.access$900(ActivityThread.java:174)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5756)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)

Body:
Step 1: Buddy create an xml file in your res/values folder and name it as colors.

Step 2: In that file colors give your required color as:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="tab_selector">#008080</color>
</resources>

Instead of #008080 use color of your choice.


问:
Angularjs: directive not working with Jslider plugin
Right now I'm working on a project in which I need to use JSlider plugin of jquery with Angularjs. I tried to use this plugin into a directive and within directive I put this in $evalAsync so that I assign the values dynamically to Jslider after content loaded and before page rendering. The way I did this is mentioned below:-

```<code>var sliderDirective = angular.module("sliderModule",[]);
sliderDirective.directive("slider",function(){
return {
restrict: 'AE',
replace: true,
template: '<input id="slider" name="price" type="slider" value="{{filters.price}}">',

link: function(scope, elem, attrs) {

  scope.$evalAsync(function(scope){

            elem.slider({
             from: 0,
             to: 3000,
             step: 50,
             smooth: true,
             round: 0,
             limits: false,
             scale: ['$0','|','$500','|','$1,000','|','$1,500','|','$2,000','|','$2,500','|','$3,000+'],
             skin: "blue",
             onstatechange:function(value){
                scope.filters.price = value;
              }
          })

        })
      }
    }
  })
</code>```

I'm setting the values dynamically that are being passing in link function's scope variable. But the problem is this that the slider doesn't get these dynamic values and shows only single pointer with value zero. So, anybody who has some solution for this problem. Also, there is a possibility that I followed a wrong way of doing this so please make me correct in that case.

答:
Recently I have used RANGE SLIDER in angularJS.

```<code><form>
    <div class="choose_industry">
        <div class="form-group">
            <label class="control-label col-xs-12 col-sm-4 col-md-2 col-lg-2 " for="name">What Industry?</label>
            <div class="col-xs-12 col-sm-8 col-md-10 col-lg-10">
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio1" value="cdl" ng-model="leg_ser.industry">
                    <label for="radio1">
                        Commercial Trucking Transportation
                    </label>
                </div>
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio2" value="non_cdl" ng-model="leg_ser.industry">
                    <label for="radio2">
                        Other Industries
                    </label>
                </div>
            </div>
        </div>
    </div>

    <div class="employee_counting">
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Number of Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-user"></i></span>
                <input type="number" class="form-control" placeholder="Employees" name="Number of Employees" ng-model="leg_ser.num_of_emp">
                <!-- <span>Total Number of Employees</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0</span>
                <span class="pull-right">25k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="25000" value="0" class="slider" id="myRange" ng-model="leg_ser.num_of_emp">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Enrollment Percentage (%)?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-percent"></i></span>
                <input type="number" class="form-control" placeholder="Percentage" name="Enrollment Percentage" ng-model="leg_ser.enroll_per">
                <!-- <span>Estimated Percentage that will enroll</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0%</span>
                <span class="pull-right">100%</span>
                <div id="slidecontainer">
                    <input type="range" min="1" max="100" value="1" class="slider" id="myRange" ng-model="leg_ser.enroll_per">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Annual Cost per Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-dollar"></i></span>
                <input type="number" class="form-control" placeholder="Cost" name="Annual Cost per Employees" ng-model="leg_ser.annual_cost">
                <!-- <span>Avarage Salary and benifits per Employee</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">$0</span>
                <span class="pull-right">$300k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="300000" value="0" class="slider" id="myRange" ng-model="leg_ser.annual_cost">
                </div>
            </div>
        </div>
    </div>
</form>
</code>```

Add following code in the script tag

```<code><!-- RANGE SLIDER JS START -->
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>
<!-- RANGE SLIDER JS OVER -->
</code>```

Above script working good for me, should work for you too.

Body:
Right now I'm working on a project in which I need to use JSlider plugin of jquery with Angularjs. I tried to use this plugin into a directive and within directive I put this in $evalAsync so that I assign the values dynamically to Jslider after content loaded and before page rendering. The way I did this is mentioned below:-

var sliderDirective = angular.module("sliderModule",[]);
sliderDirective.directive("slider",function(){
return {
restrict: 'AE',
replace: true,
template: '<input id="slider" name="price" type="slider" value="{{filters.price}}">',

link: function(scope, elem, attrs) {

  scope.$evalAsync(function(scope){

            elem.slider({
             from: 0,
             to: 3000,
             step: 50,
             smooth: true,
             round: 0,
             limits: false,
             scale: ['$0','|','$500','|','$1,000','|','$1,500','|','$2,000','|','$2,500','|','$3,000+'],
             skin: "blue",
             onstatechange:function(value){
                scope.filters.price = value;
              }
          })

        })
      }
    }
  })

I'm setting the values dynamically that are being passing in link function's scope variable. But the problem is this that the slider doesn't get these dynamic values and shows only single pointer with value zero. So, anybody who has some solution for this problem. Also, there is a possibility that I followed a wrong way of doing this so please make me correct in that case.

Body:
Recently I have used RANGE SLIDER in angularJS.

<form>
    <div class="choose_industry">
        <div class="form-group">
            <label class="control-label col-xs-12 col-sm-4 col-md-2 col-lg-2 " for="name">What Industry?</label>
            <div class="col-xs-12 col-sm-8 col-md-10 col-lg-10">
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio1" value="cdl" ng-model="leg_ser.industry">
                    <label for="radio1">
                        Commercial Trucking Transportation
                    </label>
                </div>
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio2" value="non_cdl" ng-model="leg_ser.industry">
                    <label for="radio2">
                        Other Industries
                    </label>
                </div>
            </div>
        </div>
    </div>

    <div class="employee_counting">
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Number of Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-user"></i></span>
                <input type="number" class="form-control" placeholder="Employees" name="Number of Employees" ng-model="leg_ser.num_of_emp">
                <!-- <span>Total Number of Employees</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0</span>
                <span class="pull-right">25k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="25000" value="0" class="slider" id="myRange" ng-model="leg_ser.num_of_emp">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Enrollment Percentage (%)?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-percent"></i></span>
                <input type="number" class="form-control" placeholder="Percentage" name="Enrollment Percentage" ng-model="leg_ser.enroll_per">
                <!-- <span>Estimated Percentage that will enroll</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0%</span>
                <span class="pull-right">100%</span>
                <div id="slidecontainer">
                    <input type="range" min="1" max="100" value="1" class="slider" id="myRange" ng-model="leg_ser.enroll_per">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Annual Cost per Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-dollar"></i></span>
                <input type="number" class="form-control" placeholder="Cost" name="Annual Cost per Employees" ng-model="leg_ser.annual_cost">
                <!-- <span>Avarage Salary and benifits per Employee</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">$0</span>
                <span class="pull-right">$300k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="300000" value="0" class="slider" id="myRange" ng-model="leg_ser.annual_cost">
                </div>
            </div>
        </div>
    </div>
</form>

Add following code in the script tag

<!-- RANGE SLIDER JS START -->
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>
<!-- RANGE SLIDER JS OVER -->

Above script working good for me, should work for you too.


问:
need implementation of Fuzzy Kohonen Networks (Fuzzy self organizing maps)
I have the SOM toolbox with the original implmentation of a Kohonen network. I am looking for a fuzzy kohonen network implmentation. Does anyone have it or know where I can get it?</p>

答:
libraries containing Kohonen implementations in various languages:

Encog Artificial Intelligence Framework for Java

http://code.google.com/p/encog-java/

Encog Artificial Intelligence Framework for DotNet

http://code.google.com/p/encog-cs/

Encog for C/C++/ObjectiveC - Machine Learning Framework

http://code.google.com/p/encog-cpp/

Kohonen Self-Organizing Map Library - C/Python

http://code.google.com/p/ksom/