问:
Angular GET Request from Paginated API (Next Page)
I need to retrieve data from a paginated rest api
I'm using the following code but I can't load the information in the template
Any suggestions on a better approach will be greatly appreciated!

component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  articles: any[];
  url = 'https://example.zendesk.com/api/v2/users.json';
  // finished = false;

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.getArticles(this.url, this.articles);
  }

  getArticles(url: string, articles: any[]) {
    this.httpClient.get(url).toPromise().then(response => {
      console.log(response['next_page']);
      if (articles === undefined) { articles = response['articles']; } else { articles = articles.concat(response['articles']); }
      console.log(articles);
      if (response['next_page'] != null) {
        this.getArticles(response['next_page'], articles);
      } else { console.log('End'); return articles; }
    });
  }

}
</code>```

html

```<code><ul *ngIf="articles">
  <li *ngFor="let article of articles">
    {{ article.title }}
  </li>
</ul>
</code>```

答:
The Answer I am Posting is a good Example for the beginners Guys.

api.service.ts!!!

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Customer } from './customer';

@Injectable({
  providedIn: 'root'
})

export class ApiService {
 apiurl="https://reqres.in/api/users";

 constructor(private http:HttpClient) { }
 getConfig(){
   return this.http.get<Customer[]>(this.apiurl);
 }
}
</code>```

The getConfig() in the above service is called in the below component.
App.Component.ts!!!

```<code>    import { Component, OnInit } from '@angular/core';
    import { Customer } from './customer';
    import { ApiService } from './api.service';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      customers:any;
      title = 'ApiTable';
      constructor(private apiservice:ApiService){}
      ngOnInit(){
        this.customers=[];
        return this.apiservice.getConfig().subscribe(data =>this.customers = data['data']);
      }
</code>```

Html!!!

API CALLED DATA USING ANGULAR

          ID
          FIRST-NAME
          LAST-NAME
          EMAIL
          AVATAR

          <input type="text" placeholder="ID" style="width:51px;">
          <input type="text" placeholder="FIRST-NAME"style="width:155px;">
          <input type="text" placeholder="LAST-NAME"style="width:155px;">
          <input type="text" placeholder="EMAIL"style="width:155px;">
          <input type="text" placeholder="AVATAR"style="width:155px;">

          {{item.id}}
          {{item.first_name}}
         {{item.last_name}}
          {{item.email}}

    <router-outlet></router-outlet>
```

Body:
I need to retrieve data from a paginated rest api
I'm using the following code but I can't load the information in the template
Any suggestions on a better approach will be greatly appreciated!

component.ts

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  articles: any[];
  url = 'https://example.zendesk.com/api/v2/users.json';
  // finished = false;

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.getArticles(this.url, this.articles);
  }

  getArticles(url: string, articles: any[]) {
    this.httpClient.get(url).toPromise().then(response => {
      console.log(response['next_page']);
      if (articles === undefined) { articles = response['articles']; } else { articles = articles.concat(response['articles']); }
      console.log(articles);
      if (response['next_page'] != null) {
        this.getArticles(response['next_page'], articles);
      } else { console.log('End'); return articles; }
    });
  }

}

html

    {{ article.title }}

Body:
The Answer I am Posting is a good Example for the beginners Guys.

api.service.ts!!!

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Customer } from './customer';

@Injectable({
  providedIn: 'root'
})

export class ApiService {
 apiurl="https://reqres.in/api/users";

 constructor(private http:HttpClient) { }
 getConfig(){
   return this.http.get<Customer[]>(this.apiurl);
 }
}

The getConfig() in the above service is called in the below component.
App.Component.ts!!!

    import { Component, OnInit } from '@angular/core';
    import { Customer } from './customer';
    import { ApiService } from './api.service';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      customers:any;
      title = 'ApiTable';
      constructor(private apiservice:ApiService){}
      ngOnInit(){
        this.customers=[];
        return this.apiservice.getConfig().subscribe(data =>this.customers = data['data']);
      }

Html!!!

    <h3 style="color: green;text-align: center;">API CALLED DATA USING ANGULAR</h3>
    <div class="container">
    <table border="3  px" class="table table-striped table-hover">
      <thead class="thead-dark">
        <tr>
          <th>ID</th>
          <th>FIRST-NAME</th>
          <th>LAST-NAME</th>
          <th>EMAIL</th>
          <th>AVATAR</th>
        </tr>
        <tr>
          <td class="bg-primary"><input type="text" placeholder="ID" style="width:51px;"></td>
          <td class="table-secondary"><input type="text" placeholder="FIRST-NAME"style="width:155px;"></td>
          <td class="table-success"><input type="text" placeholder="LAST-NAME"style="width:155px;"></td>
          <td  class="table-warning"><input type="text" placeholder="EMAIL"style="width:155px;"></td>
          <td class="table-info"><input type="text" placeholder="AVATAR"style="width:155px;"></td>

        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of customers | slice:startIndex:endIndex">
          <td class="bg-primary">{{item.id}}</td>
          <td class="table-secondary">{{item.first_name}}</td>
         <td class="table-success">{{item.last_name}}</td>
          <td class="table-warning">{{item.email}}</td>
          <td class="table-info"><img src="{{item.avatar}}"></td>
        </tr>
      </tbody>
    </table>
    </div>
    <router-outlet></router-outlet>


来源: stackexchange

问:
Laravel : convert grouped data to one row
Hello please i want to convert grouped data with duplicated keys and different values to one row.
For example :

```<code>    "book1" {
    {
        "id" : "1",
        "group" : "book1",
        "name" : "Book X",
        "buy" : "null",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "100",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "null",
        "test" : "344",
    }
 },
    "book2" {
 {
        "id" : "1",
        "group" : "book2",
        "name" : "Book Y",
        "buy" : "null",
        "test" : "null",
    }
    ....
 }
    ...
</code>```

what i want to do is convert all this arrays with common key to one array or one row in the database where data are grouped like the example the data are grouped by group field
and what i want to do is like that :

```<code>{
  "id" : "1",
  "group" : "book1",
  "name" : "Book X",
  "buy" : "100",
  "test" : "344",
}
</code>```

Please could you help to fix by php code (laravel model) or SQL query and thank you so much !

答:
use groupBy()</p>

```<code>$data = App\ModelName::groupBy('test')->get();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hello please i want to convert grouped data with duplicated keys and different values to one row.
For example :

    "book1" {
    {
        "id" : "1",
        "group" : "book1",
        "name" : "Book X",
        "buy" : "null",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "100",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "null",
        "test" : "344",
    }
 },
    "book2" {
 {
        "id" : "1",
        "group" : "book2",
        "name" : "Book Y",
        "buy" : "null",
        "test" : "null",
    }
    ....
 }
    ...

what i want to do is convert all this arrays with common key to one array or one row in the database where data are grouped like the example the data are grouped by group field
and what i want to do is like that :

{
  "id" : "1",
  "group" : "book1",
  "name" : "Book X",
  "buy" : "100",
  "test" : "344",
}

Please could you help to fix by php code (laravel model) or SQL query and thank you so much !

Body:
use groupBy()

$data = App\ModelName::groupBy('test')->get();


问:
DrawerActivity with Tabs
I need help since I'm going crazy. I have a project, which I had already implemented the tabs. Now I want to put the Navigation Drawer.
All I want is that when I select a Drawer menu, I change the tabs, but I don't know how to reference it.
I show the code of the MainActivity:

As you can see, I have already implemented some tabs. And the Drawer Activity. Each item in the Activity drawer calls a fragment, and in turn each tab calls another fragment to display within a ViewPager.

```<code>class MainActivity : ToolbarActivity() {

private var prevBottomSelected: MenuItem? = null
private lateinit var appBarConfiguration: AppBarConfiguration

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val toolbar: Toolbar = findViewById(R.id.toolbar)
    setSupportActionBar(toolbar)

    setUpViewPager(getPagerAdapter())
    setUpBottomNavigationBar()

    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    val navView: NavigationView = findViewById(R.id.nav_view)
    val navController = findNavController(R.id.nav_host_fragment)
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    appBarConfiguration = AppBarConfiguration(
        setOf(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
            R.id.nav_tools, R.id.nav_share, R.id.nav_send
        ), drawerLayout
    )
    setupActionBarWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.drawer, menu)
    return true
}

override fun onSupportNavigateUp(): Boolean {
    val navController = findNavController(R.id.nav_host_fragment)
    return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}

private fun getPagerAdapter(): PagerAdapter{
    val adapter = PagerAdapter(supportFragmentManager)
    adapter.addFragment(InfoFragment())
    adapter.addFragment(RateFragment())
    adapter.addFragment(ChatFragment())
    return adapter
}

private fun setUpViewPager(adapter: PagerAdapter){
    viewPager.adapter = adapter
    viewPager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
        override fun onPageScrollStateChanged(state: Int) {}
        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
        override fun onPageSelected(position: Int) {
            // Selección de menu inferior, configuracion de como aparecen seleccionados
            if(prevBottomSelected == null){
                bottomNavigation.menu.getItem(0).isChecked = false
            } else {
                prevBottomSelected!!.isChecked = false
            }
            bottomNavigation.menu.getItem(position).isChecked = true
            prevBottomSelected = bottomNavigation.menu.getItem(position)
        }
    })
}

private fun setUpBottomNavigationBar(){
        bottomNavigation.setOnNavigationItemSelectedListener { item ->
            when (item.itemId){
                R.id.bottom_nav_info -> {
                    viewPager.currentItem = 0; true
                }
                R.id.bottom_nav_rates -> {
                    viewPager.currentItem = 1; true
                }
                R.id.bottom_nav_chat -> {
                    viewPager.currentItem = 2; true
                }
                else -> false
            }
        }
}}
</code>```

Enter the PageAdapter code. I need that when I press nav_home in the Drawer, different fragments and items appear in the tab.

```<code>class PagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT){

private val fragmentList = ArrayList<Fragment>()

override fun getItem(position: Int): Fragment {
    return fragmentList[position]
}

override fun getCount(): Int {
    return fragmentList.size
}
fun addFragment(fragment: Fragment){
    fragmentList.add(fragment)}}
</code>```

答:
Since PagerAdapter is abstrace you probebly have your implementation of it that we can't see. I guess that is the cause of the problem. If that is the case try this code for pager adapter:</p>

```<code>class pagerAdapter(fm: FragmentManager): FragmentStatePagerAdapter(fm) {
    override fun getItem(position: Int): Fragment {
        return when (position) {
            0 -> InfoFragment()
            1 -> RateFragment()
            2 -> ChatFragment()
            else -> throw RuntimeException("Unsupported fragment position")
        }
    }
    override fun getCount() = 3
}
</code>```

Title: DrawerActivity with Tabs

Body:
I need help since I'm going crazy. I have a project, which I had already implemented the tabs. Now I want to put the Navigation Drawer.
All I want is that when I select a Drawer menu, I change the tabs, but I don't know how to reference it.
I show the code of the MainActivity:

As you can see, I have already implemented some tabs. And the Drawer Activity. Each item in the Activity drawer calls a fragment, and in turn each tab calls another fragment to display within a ViewPager.

class MainActivity : ToolbarActivity() {

private var prevBottomSelected: MenuItem? = null
private lateinit var appBarConfiguration: AppBarConfiguration

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val toolbar: Toolbar = findViewById(R.id.toolbar)
    setSupportActionBar(toolbar)

    setUpViewPager(getPagerAdapter())
    setUpBottomNavigationBar()

    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    val navView: NavigationView = findViewById(R.id.nav_view)
    val navController = findNavController(R.id.nav_host_fragment)
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    appBarConfiguration = AppBarConfiguration(
        setOf(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
            R.id.nav_tools, R.id.nav_share, R.id.nav_send
        ), drawerLayout
    )
    setupActionBarWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.drawer, menu)
    return true
}

override fun onSupportNavigateUp(): Boolean {
    val navController = findNavController(R.id.nav_host_fragment)
    return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}

private fun getPagerAdapter(): PagerAdapter{
    val adapter = PagerAdapter(supportFragmentManager)
    adapter.addFragment(InfoFragment())
    adapter.addFragment(RateFragment())
    adapter.addFragment(ChatFragment())
    return adapter
}

private fun setUpViewPager(adapter: PagerAdapter){
    viewPager.adapter = adapter
    viewPager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
        override fun onPageScrollStateChanged(state: Int) {}
        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
        override fun onPageSelected(position: Int) {
            // Selección de menu inferior, configuracion de como aparecen seleccionados
            if(prevBottomSelected == null){
                bottomNavigation.menu.getItem(0).isChecked = false
            } else {
                prevBottomSelected!!.isChecked = false
            }
            bottomNavigation.menu.getItem(position).isChecked = true
            prevBottomSelected = bottomNavigation.menu.getItem(position)
        }
    })
}

private fun setUpBottomNavigationBar(){
        bottomNavigation.setOnNavigationItemSelectedListener { item ->
            when (item.itemId){
                R.id.bottom_nav_info -> {
                    viewPager.currentItem = 0; true
                }
                R.id.bottom_nav_rates -> {
                    viewPager.currentItem = 1; true
                }
                R.id.bottom_nav_chat -> {
                    viewPager.currentItem = 2; true
                }
                else -> false
            }
        }
}}

Enter the PageAdapter code. I need that when I press nav_home in the Drawer, different fragments and items appear in the tab.

class PagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT){

private val fragmentList = ArrayList<Fragment>()

override fun getItem(position: Int): Fragment {
    return fragmentList[position]
}

override fun getCount(): Int {
    return fragmentList.size
}
fun addFragment(fragment: Fragment){
    fragmentList.add(fragment)}}

Body:
Since PagerAdapter is abstrace you probebly have your implementation of it that we can't see. I guess that is the cause of the problem. If that is the case try this code for pager adapter:

class pagerAdapter(fm: FragmentManager): FragmentStatePagerAdapter(fm) {
    override fun getItem(position: Int): Fragment {
        return when (position) {
            0 -> InfoFragment()
            1 -> RateFragment()
            2 -> ChatFragment()
            else -> throw RuntimeException("Unsupported fragment position")
        }
    }
    override fun getCount() = 3
}


问:
Session attribute access and converting to int?
I have stored user id in Session using following command in Servlet:

```<code>HttpSession session = request.getSession();
session.setAttribute("user", user.getId());
</code>```

Now, I want to access that user id from another Servlet:

```<code>HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)
</code>```

Question:

How can I cast to int and send the id to DAO for SELECT statement

答:
I'm not good at JAVA but I used to do it like

Integer.parseInt(session.getAttribute("user").toString())

Try once, but just be sure to check null for session.getAttribute("user") before calling toString

ContentLicense: CC BY-SA 3.0

Body:
I have stored user id in Session using following command in Servlet:

HttpSession session = request.getSession();
session.setAttribute("user", user.getId());

Now, I want to access that user id from another Servlet:

HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)

Question:

How can I cast to int and send the id to DAO for SELECT statement


问:
as.numeric creates NA when there are blank spaces
When using mutate_at to change variables in my data to either character, numeric or factors, I have issues with the numeric ones:

```<code>library(dplyr)

f <- c('V1', 'V2')
c <- c('V3', 'V4')
n <- c('V5', 'V6')

data <- data.frame(V1 = c(0,2,""),
                   V2 = c("", 3, 4),
                   V3 = c(1, 2, 3),
                   V4 = c(0, 0, ""),
                   V5 = c(-1, -1, ""),
                   V6 = c(0, 1, ""))

data <- data %>%
        mutate_at(f, as.factor) %>%
        mutate_at(c, as.character) %>%
        mutate_at(n, as.numeric)
</code>```

In this specific case, I get as a result something weird:

```<code>    V1 V2 V3 V4 V5 V6
  1  0     1  0  2  2
  2  1  3  2  0  2  3
  3     4  3     1  1
</code>```

In other cases, as in my original data, I get NA in place of blank spaces.

Can someone help?

答:
How about using readr::parse_guess to do suitable conversions?

```<code>library(dplyr)
library(readr)
data %>% mutate_all(~parse_guess(as.character(.x)))
#  V1 V2 V3 V4 V5 V6
#1  0 NA  1  0 -1  0
#2  2  3  2  0 -1  1
#3 NA  4  3 NA NA NA
</code>```

Body:
When using mutate_at to change variables in my data to either character, numeric or factors, I have issues with the numeric ones:

library(dplyr)

f <- c('V1', 'V2')
c <- c('V3', 'V4')
n <- c('V5', 'V6')

data <- data.frame(V1 = c(0,2,""),
                   V2 = c("", 3, 4),
                   V3 = c(1, 2, 3),
                   V4 = c(0, 0, ""),
                   V5 = c(-1, -1, ""),
                   V6 = c(0, 1, ""))

data <- data %>%
        mutate_at(f, as.factor) %>%
        mutate_at(c, as.character) %>%
        mutate_at(n, as.numeric)

In this specific case, I get as a result something weird:

    V1 V2 V3 V4 V5 V6
  1  0     1  0  2  2
  2  1  3  2  0  2  3
  3     4  3     1  1

In other cases, as in my original data, I get NA in place of blank spaces.

Can someone help?

Body:
How about using readr::parse_guess to do suitable conversions?

library(dplyr)
library(readr)
data %>% mutate_all(~parse_guess(as.character(.x)))
#  V1 V2 V3 V4 V5 V6
#1  0 NA  1  0 -1  0
#2  2  3  2  0 -1  1
#3 NA  4  3 NA NA NA


问:
Connect css fonts locally
I searched on the Internet how to connect fonts to the site, with a link to a local file, but could not find a complete answer anywhere. Please explain by points and in full what needs to be done to connect fonts to HTML and CSS files.</p>

答:
You can go through with following steps

```<code>Step 1: Download the font
Step 2: Create a WebFont Kit for cross-browsing
Step 3: Upload the font files to your website
Step 4: Update and upload your CSS file
Step 5: Use the custom font in your CSS declarations.
</code>```

for reference please check below link

https://www.pagecloud.com/blog/how-to-add-custom-fonts-to-any-website

Hope this will help :) Happy Coding :)

Title: Connect css fonts locally

Body:
You can go through with following steps

Step 1: Download the font
Step 2: Create a WebFont Kit for cross-browsing
Step 3: Upload the font files to your website
Step 4: Update and upload your CSS file
Step 5: Use the custom font in your CSS declarations.

for reference please check below link

https://www.pagecloud.com/blog/how-to-add-custom-fonts-to-any-website

Hope this will help :) Happy Coding :)


问:
how to add single quote inside the php when passing argument for onclick javascript function?
Anyone know how should I write to get long hash value inside the single quote but when writing this code inside the php.

For example at the moment my code is below which I know its wrong:

```<code>$raw_tbody .= "<td width='10%'><a onclick='customRuleEdit('{$row['hash']}')' >";
</code>```

So when I write like above its display on HTML side like below: (Which is wrong as you can see the single and double quotes)

```<code><a onclick="customRuleEdit(" f6710ecaa686546bb424525686c792823f8d5193')'="">
</code>```

What I want is as below Output:

```<code><a onclick="customRuleEdit('f6710ecaa686546bb424525686c792823f8d5193')">
</code>```

So anyone knows what I should write to make the output like above??

Thanks

答:
```<code>Try this code for helpful..

 $raw_tbody .= "<td width='10%'><a onclick=\"customRuleEdit('{$row['hash']}')\" >";
</code>```

Body:
Anyone know how should I write to get long hash value inside the single quote but when writing this code inside the php.

For example at the moment my code is below which I know its wrong:

$raw_tbody .= "";

So when I write like above its display on HTML side like below: (Which is wrong as you can see the single and double quotes)

What I want is as below Output:

So anyone knows what I should write to make the output like above??

Thanks


问:
Concatenate strings from array in PHP ignoring blanks
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);
```

<p>However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?</p>

<pre class="lang-php prettyprint-override"><code>public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}
</code>```

答:
Apply trim() function on each array element. See the following example:

```<code><?php

$arrayOfStrings = ['a', ' b c',null, ' ','def '];

echo implode(' ', array_filter($arrayOfStrings, function($element) {
    return trim($element);
}));
</code>```

The code above outputs "a  b c def ". Notice the space after "def ".

This means trim() function with array_filter() function's callback function doesn't trim space from the right side. To address this issue, you should use trim() function with array_filter() and array_map() functions. Because array_map() function removes spaces from both sides. See the following example:

```<code><?php

echo implode(' ', array_filter(array_map('trim', $arrayOfStrings)));
</code>```

The code above outputs "a  b c def"

By the way thanks to @jspit for the good catch!

Body:
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);

However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?

public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}

Body:
Apply trim() function on each array element. See the following example:

<?php

$arrayOfStrings = ['a', ' b c',null, ' ','def '];

echo implode(' ', array_filter($arrayOfStrings, function($element) {
    return trim($element);
}));

The code above outputs "a  b c def ". Notice the space after "def ".

This means trim() function with array_filter() function's callback function doesn't trim space from the right side. To address this issue, you should use trim() function with array_filter() and array_map() functions. Because array_map() function removes spaces from both sides. See the following example:

<?php

echo implode(' ', array_filter(array_map('trim', $arrayOfStrings)));

The code above outputs "a  b c def"

By the way thanks to @jspit for the good catch!


问:
Node_modules/rxjs/Rx"' has no exported member 'Rx'
Can you tell me why below behavior with rxjs/Rx? I'm using VS code V 1.14.1.

This works:

```<code>import * as Rx from 'rxjs/Rx';
</code>```

and

```<code>import Rx from 'rxjs/Rx';
</code>```

But This is not working.

```<code>import { Rx } from 'rxjs/Rx';
</code>```

node_modules/rxjs/Rx"' has no exported member 'Rx'.

答:
I had this issue recently. Fixed it using below steps

remove node_modules using rm -rf node_modules/

set rxjs v6.0.0, rxjs-compat v6.0.0 in package.json

run npm install

run ionic serve

Body:
Can you tell me why below behavior with rxjs/Rx? I'm using VS code V 1.14.1.

This works:

import * as Rx from 'rxjs/Rx';

and

import Rx from 'rxjs/Rx';

But This is not working.

import { Rx } from 'rxjs/Rx';

node_modules/rxjs/Rx"' has no exported member 'Rx'.


问:
React cannot update during an existing state transition
I have a react app with react-countdown-circle-timer installed.
When the onComplete() method of the circle timer fires, I am setting the state but I get this warning:
Warning: Cannot update during an existing state transition (such as within 'render').

```<code>import React from 'react';
import { CountdownCircleTimer } from 'react-countdown-circle-timer';

export default class Test extends React.Component {

    constructor() {
        super();
        this.state = {
            userMustWait: false
        }
    }

    render() {
        return (
            <CountdownCircleTimer
                isPlaying
                durationSeconds={3}
                colors={[["#004777", 0.33], ["#F7B801", 0.33], ["#A30000"]]}
                onComplete={() => { this.setState({ userMustWait: false }) }}
            />)
    }
}
</code>```

答:
You have to write function instead doing in render itself</p>

```<code>onclick(){
   this.setState({ userMustWait: false })
}

render() {
        return (
            <CountdownCircleTimer
                isPlaying
                durationSeconds={3}
                colors={[["#004777", 0.33], ["#F7B801", 0.33], ["#A30000"]]}
                onComplete={() => this.onclick()}
            />)
    }
</code>```

Body:
I have a react app with react-countdown-circle-timer installed.
When the onComplete() method of the circle timer fires, I am setting the state but I get this warning:
Warning: Cannot update during an existing state transition (such as within 'render').

import React from 'react';
import { CountdownCircleTimer } from 'react-countdown-circle-timer';

export default class Test extends React.Component {

    constructor() {
        super();
        this.state = {
            userMustWait: false
        }
    }

    render() {
        return (
            <CountdownCircleTimer
                isPlaying
                durationSeconds={3}
                colors={[["#004777", 0.33], ["#F7B801", 0.33], ["#A30000"]]}
                onComplete={() => { this.setState({ userMustWait: false }) }}
            />)
    }
}

Body:
You have to write function instead doing in render itself

onclick(){
   this.setState({ userMustWait: false })
}

render() {
        return (
            <CountdownCircleTimer
                isPlaying
                durationSeconds={3}
                colors={[["#004777", 0.33], ["#F7B801", 0.33], ["#A30000"]]}
                onComplete={() => this.onclick()}
            />)
    }


问:
How to get SUM of f3 but Grouped by f2
I want to get all comments count grouped by category. eg

```<code>f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43
</code>```

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique

答:
Based on the pastebin you posted,

this should work

```<code>SELECT QV, SUM(invalid_votes) FROM `results` GROUP BY QV
</code>```

I get the following result

```<code>QV      SUM(invalid_votes)
0544    15
0545    12
</code>```

Title: How to get SUM of f3 but Grouped by f2

Body:
I want to get all comments count grouped by category. eg

f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique

Body:
Based on the pastebin you posted,

this should work

SELECT QV, SUM(invalid_votes) FROM `results` GROUP BY QV

I get the following result

QV      SUM(invalid_votes)
0544    15
0545    12


问:
How to assign variables in a mailgun email template (Node js)?
I've made a google cloud function in which I send an email with some variables I receive from another place.
I'm using mailgun.js and I'm trying to send the email with a template I've already created in mailgun.
The issue is that I can't find a way to replace the placeholder variables in my template.

This is the code:

```<code>mg.messages.create('domain', {
    from: 'email',
    to: [email],
    subject: 'subject',
    template: 'template',
    // How to replace the template variables???
  })
  .then(res => console.log('Resolved >>>>> ', res))
  .catch(err => console.log('MAILGUN ERROR >>>> ', err))
</code>```

The mailgun docs says this:

```<code>var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  h:X-Mailgun-Variables: '{"title": "API Documentation", "body": "Sending messages with templates"}' // Notice this
};
</code>```

As far as I know one cannot write "h:X-Mailgun-Variables" as a key in any object.

Does anybody know where or how do I need to put it?

I thought that it should be sent as a header but neither mailgun/mailgun-js nor highlycaffeinated/mailgun-js specifies how to pass headers.

答:
You can set h:X-Mailgun-Variables as a key by using quotes around the key.

You need to access the value within the object using bracket notation however.

For example

```<code>const foo = {
  "ba ar": "foobar",
  "test" : "test"
}

console.log(foo["ba ar"], foo.test)
// #> foobar test

//doesn't work
console.log(foo."ba ar")

</code>```

Body:
I've made a google cloud function in which I send an email with some variables I receive from another place.
I'm using mailgun.js and I'm trying to send the email with a template I've already created in mailgun.
The issue is that I can't find a way to replace the placeholder variables in my template.

This is the code:

mg.messages.create('domain', {
    from: 'email',
    to: [email],
    subject: 'subject',
    template: 'template',
    // How to replace the template variables???
  })
  .then(res => console.log('Resolved >>>>> ', res))
  .catch(err => console.log('MAILGUN ERROR >>>> ', err))

The mailgun docs says this:

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  h:X-Mailgun-Variables: '{"title": "API Documentation", "body": "Sending messages with templates"}' // Notice this
};

As far as I know one cannot write "h:X-Mailgun-Variables" as a key in any object.

Does anybody know where or how do I need to put it?

I thought that it should be sent as a header but neither mailgun/mailgun-js nor highlycaffeinated/mailgun-js specifies how to pass headers.

Body:
You can set h:X-Mailgun-Variables as a key by using quotes around the key.

You need to access the value within the object using bracket notation however.

For example

const foo = {
  "ba ar": "foobar",
  "test" : "test"
}

console.log(foo["ba ar"], foo.test)
// #> foobar test

//doesn't work
console.log(foo."ba ar")


问:
How do i type file name and press enter for uploading file while using selenium
first week coding. I am creating a programme in python to automatically upload invoices into a job management system. I am using selenium to navigate through webpages and click upload. i am prompt with the upload file box and all i want to do is type the file name and press enter.

The upload file box opens and is ready for me to type how do i do this then carry on using selenium?

答:
As we know selenium doesn't support windows based pop up handling so use Autoit tool to write a script with desired file name.

Inject same script in your selenium test function.


问:
Translator Text API 3.0: Transliterate
I have followed this document and tried in postman to check for output by giving these parameters and headers

```<code>Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json
Content-Length:32

Query Params:
api-version:3.0
language:hi
fromScript:Deva
toScript:Latn

body :
[
    {"Text":"मैं हूँ ना"}
]
</code>```

{"error":{"code":400000,"message":"One of the request inputs is not
  valid."}}

I'm not able to get the output. can anyone pls help me here.

答:
in headers no need of content-length</p>

```<code>Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json
</code>```

Title: Translator Text API 3.0: Transliterate

Body:
I have followed this document and tried in postman to check for output by giving these parameters and headers

Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json
Content-Length:32

Query Params:
api-version:3.0
language:hi
fromScript:Deva
toScript:Latn

body :
[
    {"Text":"मैं हूँ ना"}
]

{"error":{"code":400000,"message":"One of the request inputs is not
  valid."}}

I'm not able to get the output. can anyone pls help me here.

Body:
in headers no need of content-length

Headers:
Ocp-Apim-Subscription-Key:****************
Content-Type:application/json


问:
Mapping of multiple columns categorical values in pandas
Suppose that I have a dataframe with three columns with categorical data, and I want to transform the three categorical columns into a single value and map to the original dataframe. I understand that this is possible with a single column with this, but how about multiple columns?

Example: From this

```<code>>>>df = pd.DataFrame({'id':['0', '1', '2', '3','4'],
...                   'x':['tall', 'short', 'tall', 'short', 'tall'],
...                   'y':['fat', 'thin', 'thin', 'fat', 'fat'],
...                   'z':['male', 'female', 'female', 'male', 'male']},
...                   dtype='category')

>>>df
  id      x     y       z
0  0   tall   fat    male
1  1  short  thin  female
2  2   tall  thin  female
3  3  short   fat    male
4  4   tall   fat    male
</code>```

to this by mapping with the columns: x, y and z

```<code>>>>df
  id      x     y       z  map
0  0   tall   fat    male    0
1  1  short  thin  female    1
2  2   tall  thin  female    2
3  3  short   fat    male    3
4  4   tall   fat    male    0
</code>```

答:
This is groupby().ngroup():

```<code>df['map'] = df.groupby(['x','y','z'], sort=False).ngroup()
</code>```

Or, if your data are string type, you can concatenate the columns, possibly with some special character, and use the single column approach:

```<code># add('&') may not be needed
df['map'] = pd.factorize(df[['x','y','z']].add('&').sum(1))[0]
</code>```

Output:

```<code>   id      x     y       z  map
0   0   tall   fat    male    0
1   1  short  thin  female    1
2   2   tall  thin  female    2
3   3  short   fat    male    3
4   4   tall   fat    male    0
</code>```

Body:
Suppose that I have a dataframe with three columns with categorical data, and I want to transform the three categorical columns into a single value and map to the original dataframe. I understand that this is possible with a single column with this, but how about multiple columns?

Example: From this

>>>df = pd.DataFrame({'id':['0', '1', '2', '3','4'],
...                   'x':['tall', 'short', 'tall', 'short', 'tall'],
...                   'y':['fat', 'thin', 'thin', 'fat', 'fat'],
...                   'z':['male', 'female', 'female', 'male', 'male']},
...                   dtype='category')

>>>df
  id      x     y       z
0  0   tall   fat    male
1  1  short  thin  female
2  2   tall  thin  female
3  3  short   fat    male
4  4   tall   fat    male

to this by mapping with the columns: x, y and z

>>>df
  id      x     y       z  map
0  0   tall   fat    male    0
1  1  short  thin  female    1
2  2   tall  thin  female    2
3  3  short   fat    male    3
4  4   tall   fat    male    0

Body:
This is groupby().ngroup():

df['map'] = df.groupby(['x','y','z'], sort=False).ngroup()

Or, if your data are string type, you can concatenate the columns, possibly with some special character, and use the single column approach:

# add('&') may not be needed
df['map'] = pd.factorize(df[['x','y','z']].add('&').sum(1))[0]

Output:

   id      x     y       z  map
0   0   tall   fat    male    0
1   1  short  thin  female    1
2   2   tall  thin  female    2
3   3  short   fat    male    3
4   4   tall   fat    male    0


问:
How best to reduce CPU time used by a datastore put
I have a cron job which I run every three minutes, which pulls some data from a remote API, and then stores it in my local datastore. However, this is taking a huge amount of CPU time  in the datastore put operation. I suspect I'm probably doing something really stupid which can be optimised a lot:

```<code>result = urllib2.urlopen(url).read()
foos = json.loads(result)['foo']
bars = json.loads(result)['bar']

models = []
for foo in foos:
    d = FooContainer()
    d.Property = foo.Value #in real code, this is setting a load of values based off foo
    models.append(d)

for bar in bars:
    d = BarContainer()
    d.Property = bar.Value #in real code, this is setting a load of properties based off bar
    models.append(d)

db.put(models)
</code>```

As you can see, I'm storing every piece of data returned as a new "row" in my local datastore tables. Is there some technique I can use to reduce the huge datastore CPU time used by this cron job?

答:
~2k cpu_ms looks about right. You are seeing 46k api cpu_ms because the datastore can only write max. 10 entities per second (governed by the api), and you are writing 450+ entities, thus 450+/10 is around 46k cpu_ms.

The api usage doesn't count directly against the bottom line of your quota, only the real ~2k will. So don't worry about it, you're just fine.

Body:
I have a cron job which I run every three minutes, which pulls some data from a remote API, and then stores it in my local datastore. However, this is taking a huge amount of CPU time  in the datastore put operation. I suspect I'm probably doing something really stupid which can be optimised a lot:

result = urllib2.urlopen(url).read()
foos = json.loads(result)['foo']
bars = json.loads(result)['bar']

models = []
for foo in foos:
    d = FooContainer()
    d.Property = foo.Value #in real code, this is setting a load of values based off foo
    models.append(d)

for bar in bars:
    d = BarContainer()
    d.Property = bar.Value #in real code, this is setting a load of properties based off bar
    models.append(d)

db.put(models)

As you can see, I'm storing every piece of data returned as a new "row" in my local datastore tables. Is there some technique I can use to reduce the huge datastore CPU time used by this cron job?


问:
React native calendar missing day of the month
https://raw.githubusercontent.com/wix/react-native-calendars/master/demo/calendar.gif

The gif abow show the content of react-native calendar.
As you can see, it's have only 5 line therefore some month will miss someday. is there anyway to make the row to 6?

答: It will automatically add the 6th row if needed. try May 2020, it has the same scenario as you described, you will get 6 rows in this month.