问:
Spring Boot shows the String instead of the HTML file from an Angular2 Single Page app
I'm trying to map all GET requests to unmapped url of the site to show the index.html file.

So, I created the following @RestController:

```<code>@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "index.html";
}
</code>```

My index.html is in resources/static/index.html. I also tried the following controller:

```<code>@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "/static/index.html";
}
</code>```

However, in both cases, browser literally shows the strings index.html and /static/index.html respectively instead of showing the html file. I tried a lot of different other approaches to similar questions here but can't get it to resolve... Please help.

EDIT:

My fill @RequestController class:

```<code>@RestController
public class FeedbackController {
    @Autowired
    private FeedbackService feedbackService;

    @RequestMapping(method=RequestMethod.POST, value="/feedback")
    public Feedback addFeedback(@RequestBody Feedback feedback) {
        return feedbackService.addFeedback(feedback);
    }

    @RequestMapping(method=RequestMethod.GET)
    public String redirectToIndex() {
        return "index.html";
    }

}
</code>```

My pom.xml:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</code>```

答:
If you are using Thymeleaf as the template resolver in your SpringBoot Project.

e.g:

```<code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</code>```

then put your index.html inside src/main/resources/templates. This is where Thymeleaf looks for the static resources!

Your RestController should have the following

```<code>@Controller
public class FeedbackController {
@Autowired
private FeedbackService feedbackService;

@RequestMapping(method=RequestMethod.POST, value="/feedback")
@ResponseBody
public Feedback addFeedback(@RequestBody Feedback feedback) {
    return feedbackService.addFeedback(feedback);
}

@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "index";
}

}
</code>```

You may need to put your Security config correct to have this accessible.

Body:
I'm trying to map all GET requests to unmapped url of the site to show the index.html file.

So, I created the following @RestController:

@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "index.html";
}

My index.html is in resources/static/index.html. I also tried the following controller:

@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "/static/index.html";
}

However, in both cases, browser literally shows the strings index.html and /static/index.html respectively instead of showing the html file. I tried a lot of different other approaches to similar questions here but can't get it to resolve... Please help.

EDIT:

My fill @RequestController class:

@RestController
public class FeedbackController {
    @Autowired
    private FeedbackService feedbackService;

    @RequestMapping(method=RequestMethod.POST, value="/feedback")
    public Feedback addFeedback(@RequestBody Feedback feedback) {
        return feedbackService.addFeedback(feedback);
    }

    @RequestMapping(method=RequestMethod.GET)
    public String redirectToIndex() {
        return "index.html";
    }

}

My pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Body:
If you are using Thymeleaf as the template resolver in your SpringBoot Project.

e.g:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

then put your index.html inside src/main/resources/templates. This is where Thymeleaf looks for the static resources!

Your RestController should have the following

@Controller
public class FeedbackController {
@Autowired
private FeedbackService feedbackService;

@RequestMapping(method=RequestMethod.POST, value="/feedback")
@ResponseBody
public Feedback addFeedback(@RequestBody Feedback feedback) {
    return feedbackService.addFeedback(feedback);
}

@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "index";
}

}

You may need to put your Security config correct to have this accessible.


来源: stackexchange

问:
set startDate of one datepicker as selected date from another datepicker
I have two datepicker in my page to seletect From and To dates. From datepicker's end date is set to today and To datepicker's end date is set to today. Also i need to set startdate for To datepicker to selected date from From datepicker. Please help me.

here is my code

```<code><input type="text" placeholder="From" id="reportFrom" name="reportFrom" value="<?php echo $reportFrom?>">
<input type="text" placeholder="To" id="reportTo" name="reportTo" value="<?php echo $reportTo;?>">
</code>```

Script:

```<code>$('#reportFrom').datepicker({
        autoHide: true,
        autoclose: true,
        endDate: new Date(),
        onSelect: function(dateStr)
        {
            $("#reportTo").val(dateStr);
            $("#reportTo").datepicker("option",{ startDate: new Date(dateStr)});
        }
    });
    $('#reportTo').datepicker({
        autoHide: true,
        autoclose: true,
        //startDate : $('#reportFrom').val(),
        endDate: new Date()
    });
</code>```

答:
This is the HTML:

```<code><input type="text" id="dateFrom" />
<input type="text" id="dateTo" />
</code>```

and this is the jquery:

```<code>$(document).ready(function () {

    $("#dateFrom").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 0,
        onSelect: function (date) {
            var date2 = $('#dateFrom').datepicker('getDate');
            date2.setDate(date2.getDate());
            $('#dateTo').datepicker('setDate', date2);
            //sets minDate to dt1 date
            $('#dateTo').datepicker('option', 'minDate', date2);
        }
    });
    $('#dateTo').datepicker({
        dateFormat: "dd-M-yy",
        onClose: function () {
            var dt1 = $('#dateFrom').datepicker('getDate');
            console.log(dt1);
            var dt2 = $('#dateTo').datepicker('getDate');
            if (dt2 == dt1) {
                var minDate = $('#dateTo').datepicker('option', 'minDate');
                $('#dateTo').datepicker('setDate', minDate);
            }
        }
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two datepicker in my page to seletect From and To dates. From datepicker's end date is set to today and To datepicker's end date is set to today. Also i need to set startdate for To datepicker to selected date from From datepicker. Please help me.

here is my code

<input type="text" placeholder="From" id="reportFrom" name="reportFrom" value="<?php echo $reportFrom?>">
<input type="text" placeholder="To" id="reportTo" name="reportTo" value="<?php echo $reportTo;?>">

Script:

$('#reportFrom').datepicker({
        autoHide: true,
        autoclose: true,
        endDate: new Date(),
        onSelect: function(dateStr)
        {
            $("#reportTo").val(dateStr);
            $("#reportTo").datepicker("option",{ startDate: new Date(dateStr)});
        }
    });
    $('#reportTo').datepicker({
        autoHide: true,
        autoclose: true,
        //startDate : $('#reportFrom').val(),
        endDate: new Date()
    });

Body:
This is the HTML:

<input type="text" id="dateFrom" />
<input type="text" id="dateTo" />

and this is the jquery:

$(document).ready(function () {

    $("#dateFrom").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 0,
        onSelect: function (date) {
            var date2 = $('#dateFrom').datepicker('getDate');
            date2.setDate(date2.getDate());
            $('#dateTo').datepicker('setDate', date2);
            //sets minDate to dt1 date
            $('#dateTo').datepicker('option', 'minDate', date2);
        }
    });
    $('#dateTo').datepicker({
        dateFormat: "dd-M-yy",
        onClose: function () {
            var dt1 = $('#dateFrom').datepicker('getDate');
            console.log(dt1);
            var dt2 = $('#dateTo').datepicker('getDate');
            if (dt2 == dt1) {
                var minDate = $('#dateTo').datepicker('option', 'minDate');
                $('#dateTo').datepicker('setDate', minDate);
            }
        }
    });
});


问:
TFS overlay branch mappings
Can Microsoft's Team Foundation overlay multiple branches to a single source branch?

I'm trying to map 3 locations from the depot to 1 location in my workspace, like below:

```<code>//workspace/Project/Source/...  //depot/Project/Source/...
+//workspace/Project/Source/...  //depot/branch1/Source/...
+//workspace/Project/Source/...  //depot/branch2/Source/...
</code>```

There is a single source directory and im trying to overlay two branches one with fixes another with pending changes.

The version is TFS 2017

答:
One workspace does not allow the same TFS folder to be mapped to more than one local directory. We could also not map multiple server branches to the same local folder/location which already be mapped.

If you do this it will not overlay the files, instead it will pop up the error message something like below screenshot:

You have to either merge changes in the server first and than get latest version for your local files or keep local folder with the different subfolders(the same structure) as server side.

Title: TFS overlay branch mappings

Body:
Can Microsoft's Team Foundation overlay multiple branches to a single source branch?

I'm trying to map 3 locations from the depot to 1 location in my workspace, like below:

//workspace/Project/Source/...  //depot/Project/Source/...
+//workspace/Project/Source/...  //depot/branch1/Source/...
+//workspace/Project/Source/...  //depot/branch2/Source/...

There is a single source directory and im trying to overlay two branches one with fixes another with pending changes.

The version is TFS 2017


问:
How to Get the Tag Identifier in Core NFC
How can I get the ID of an NFC tag (not the ID of the message payload) using Core NFC?

I am looking for something similiar to this function that exists in Android: https://developer.android.com/reference/android/nfc/Tag.html#getId()

答:
The use of _foundTags will cause rejection:

1.2 Binary Rejected

Guideline 2.5.1 - Performance - Software Requirements

Your app uses or references the following non-public APIs:

_foundTags

The use of non-public APIs is not permitted on the App Store because
  it can lead to a poor user experience should these APIs change.

Continuing to use or conceal non-public APIs in future submissions of
  this app may result in the termination of your Apple Developer
  account, as well as removal of all associated apps from the App Store.

Next Steps

If you are using third-party libraries, please update to the most
  recent version of those libraries. If you do not have access to the
  libraries' source, you may be able to search the compiled binary using
  the "strings" or "otool" command line tools. The "strings" tool can
  output a list of the methods that the library calls and "otool -ov"
  will output the Objective-C class structures and their defined
  methods. These tools can help you narrow down where the problematic
  code resides. You could also use the "nm" tool to verify if any
  third-party libraries are calling these APIs.

Resources

For information on the "nm" tool, please review the "nm tool" Xcode
  manual page.

If there are no alternatives for providing the functionality your app
  requires, you can file an enhancement request.


问:
how would i remove some portion of
 from a table in php?
this is my table -

```<code> <table>
     <tr>
      <td>ABC</td>
     </tr>
     <tr>
      <td> </td>
     </tr>
 </table>
</code>```

and I want to remove this one table row:

```<code><tr>
   <td> </td>
</tr>
</code>```

my expected output is:

```<code> <table>
   <tr>
     <td>ABC</td>
   </tr>
 </table>
</code>```

is it possible??please help me

答:
Just add id to your table :

```<code><table id="tableid">
         <tr>
          <td>ABC</td>
         </tr>
         <tr>
          <td> </td>
         </tr>
       </table>
</code>```

This script find  , if found then remove !

```<code>$('#tableid tr').each(function() {
    if ($(this).find('td').html()==' ') $(this).remove();
});
</code>```

If you want to find some text and then remove then replace html() with text()

```<code>$('#tableid tr').each(function() {
    if ($(this).find('td').text()=='ABC') $(this).remove();
});
</code>```

Title: how would i remove some portion of <tr><td> from a table in php?

Body:
this is my table -

      ABC

and I want to remove this one table row:

my expected output is:

     ABC

is it possible??please help me

Body:
Just add id to your table :

<table id="tableid">
         <tr>
          <td>ABC</td>
         </tr>
         <tr>
          <td>&nbsp;</td>
         </tr>
       </table>

This script find &nbsp;, if found then remove !

$('#tableid tr').each(function() {
    if ($(this).find('td').html()=='&nbsp;') $(this).remove();
});

If you want to find some text and then remove then replace html() with text()

$('#tableid tr').each(function() {
    if ($(this).find('td').text()=='ABC') $(this).remove();
});


问:
Date.getTime() in Java returning different time in different server
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

```<code>public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}
</code>```

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!

答:
java.time

I recommend you use java.time, also known as JSR-310, for this. The classes you use, Date and SimpleDateFormat, are long outdated, and SimpleDateFormat in particular has a reputation for producing surprising results, which one may say also happened in your case. The modern API is generally so much nicer to work with.

As I think you have suspected already, your issue comes from the fact that your servers are running different time zones, and the conversion of a date to millis since the epoch is a time zone dependent operation since the epoch is always the same point in time (Jan 1 1970 at midnight in UTC). As mweiss I am using UTC for the conversion to make sure it gives the same result no matter the time zone of the server:

```<code>    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    String now = "11/03/2018";
    LocalDate date = LocalDate.parse(now, dtf);
    long millisInUtc = date.atStartOfDay(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
    System.out.println(millisInUtc);
</code>```

As my code stands, it prints

```<code>1541203200000
</code>```

This is between the values you got in India and US because UTC is between those two time zones. If you consider it more correct to use for example Asia/Kolkata time, simply substitute ZoneId.of("Asia/Kolkata") instead of ZoneOffset.UTC in the code, and you should get the same output as you already got when you ran your code on your server in India (please remember to rename the variable too).

My code is a bit longer than yours. I consider this an advantage in this case. Yes, indeed. The code using java.time is making explicit that we are using the time at the start of the day (0:00 midnight) and that we are using a time zone or offset for the conversion. This forces you as the coder to think about these issues, and you will be very unlikely to write code that produces results that differ unexpectedly across time zones, that is, your issue would never arise. At the same time it makes explicit to the reader that the operation depends on time zone, and that you have made a conscious choice of which zone to use. These advantageous are well worth a few more code lines.

Body:
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!

Body:
java.time

I recommend you use java.time, also known as JSR-310, for this. The classes you use, Date and SimpleDateFormat, are long outdated, and SimpleDateFormat in particular has a reputation for producing surprising results, which one may say also happened in your case. The modern API is generally so much nicer to work with.

As I think you have suspected already, your issue comes from the fact that your servers are running different time zones, and the conversion of a date to millis since the epoch is a time zone dependent operation since the epoch is always the same point in time (Jan 1 1970 at midnight in UTC). As mweiss I am using UTC for the conversion to make sure it gives the same result no matter the time zone of the server:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    String now = "11/03/2018";
    LocalDate date = LocalDate.parse(now, dtf);
    long millisInUtc = date.atStartOfDay(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
    System.out.println(millisInUtc);

As my code stands, it prints

1541203200000

This is between the values you got in India and US because UTC is between those two time zones. If you consider it more correct to use for example Asia/Kolkata time, simply substitute ZoneId.of("Asia/Kolkata") instead of ZoneOffset.UTC in the code, and you should get the same output as you already got when you ran your code on your server in India (please remember to rename the variable too).

My code is a bit longer than yours. I consider this an advantage in this case. Yes, indeed. The code using java.time is making explicit that we are using the time at the start of the day (0:00 midnight) and that we are using a time zone or offset for the conversion. This forces you as the coder to think about these issues, and you will be very unlikely to write code that produces results that differ unexpectedly across time zones, that is, your issue would never arise. At the same time it makes explicit to the reader that the operation depends on time zone, and that you have made a conscious choice of which zone to use. These advantageous are well worth a few more code lines.


问:
How to generate random number as an id / primary key of an object in Django
How do you generate a unique, random number to set as the primary key of an object in django?

EDIT - The random number doesn't have to be the primary key, but it needs to be unique for each object such that I can reference/get/call the object by that number.

答:
Here is how you can do it with a Django model:</p>

```<code>from django.db import models
from django.contrib.auth.models import User
from random import randint

class Account(models.Model):
    id = models.BigAutoField(primary_key=True)
    user = models.OneToOneField(User, related_name='account',on_delete=models.CASCADE)

    def save(self):
        if not self.id:
            is_unique = False
            while not is_unique:
                id = randint(1000000000000000000, 1999999999999999999) # 19 digits: 1, random 18 digits
                is_unique = Account.objects.filter(id=id).exists()
            self.id = id
        super(Account, self).save()
</code>```

Body:
Here is how you can do it with a Django model:

from django.db import models
from django.contrib.auth.models import User
from random import randint

class Account(models.Model):
    id = models.BigAutoField(primary_key=True)
    user = models.OneToOneField(User, related_name='account',on_delete=models.CASCADE)

    def save(self):
        if not self.id:
            is_unique = False
            while not is_unique:
                id = randint(1000000000000000000, 1999999999999999999) # 19 digits: 1, random 18 digits
                is_unique = Account.objects.filter(id=id).exists()
            self.id = id
        super(Account, self).save()

ContentLicense: CC BY-SA 4.0


问:
Import crypto-js in an angular 2 project (created with angular-cli)
I'm trying to import crypto-js in my angular2 project.

I followed several SO questions and also angular-cli guide, but at the end I still have the error Cannot find module 'crypto-js'

What I tried :

npm install crypto-js --save

and

typings install dt~crypto-js --global --save

then I modified the file angular-cli-build.js

```<code>var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'crypto-js/**/*.+(js|js.map)'
    ]
  });
};
</code>```

and the file src/system-config.ts

```<code>const map: any = {
    'crypto-js': 'vendor/crypto-js'
};

/** User packages configuration. */
const packages: any = {
    'crypto-js': {
        format: 'cjs'
    }
};
</code>```

After using

import * as CryptoJS from 'crypto-js';

I still have my error. Did I miss something ?

Thanks

答:
You can try following as a solution:</p>

```<code>1. npm install --save @types/crypto-js

2. import { AES } from "crypto-js";

3. AES.encrypt('my message', 'secret key');
</code>```

Body:
I'm trying to import crypto-js in my angular2 project.

I followed several SO questions and also angular-cli guide, but at the end I still have the error Cannot find module 'crypto-js'

What I tried :

npm install crypto-js --save

and

typings install dt~crypto-js --global --save

then I modified the file angular-cli-build.js

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'crypto-js/**/*.+(js|js.map)'
    ]
  });
};

and the file src/system-config.ts

const map: any = {
    'crypto-js': 'vendor/crypto-js'
};

/** User packages configuration. */
const packages: any = {
    'crypto-js': {
        format: 'cjs'
    }
};

After using

import * as CryptoJS from 'crypto-js';

I still have my error. Did I miss something ?

Thanks

Body:
You can try following as a solution:

1. npm install --save @types/crypto-js

2. import { AES } from "crypto-js";

3. AES.encrypt('my message', 'secret key');


问:
How to know if a string is already escaped special with special characters?
I have this URL:

```<code>"http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
</code>```

So I needs to escape these Arabic values else it will not able to create URL object.

I am doing it like this,

```<code>let originalString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
</code>```

This will be the output of escapedString:

http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg

So far so good. But when I force to try to escape an already escaped URL then the result is weird.

How to check if a string is already encoded?

答:
you can do it smoothly:

```<code>extension String {
    func isEscaped() -> Bool {
        return self.removingPercentEncoding != self
    }
}
</code>```

then

```<code>let yourEscapedString = "http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg"
print(yourEscapedString.isEscaped()) // true

let yourNotEscapedString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
print(yourNotEscapedString.isEscaped()) // false
</code>```

Body:
I have this URL:

"http://www.somedomain.com/folder/مرحبا المستخدم.jpg"

So I needs to escape these Arabic values else it will not able to create URL object.

I am doing it like this,

let originalString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

This will be the output of escapedString:

http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg

So far so good. But when I force to try to escape an already escaped URL then the result is weird.

How to check if a string is already encoded?

Body:
you can do it smoothly:

extension String {
    func isEscaped() -> Bool {
        return self.removingPercentEncoding != self
    }
}

then

let yourEscapedString = "http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg"
print(yourEscapedString.isEscaped()) // true

let yourNotEscapedString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
print(yourNotEscapedString.isEscaped()) // false


问:
Spark Streaming design questions
I don't have any specific query but design question.  I am new to spark/streaming hence forgive me  if I am asking dumb question. Please delete it if question is inappropriate for this forum.

So basically we have requirement where we have to process huge amount of data every hour and produce o/p for reporting in kibana (elastic search). Lets suppose we have two data model as shown below. DataModel-1 represent the hash tag and userid of people who tweeted with that hash. Second data Model DataModel-2 contain zip and users how are in that zip. DataModel-1 data is stream data and we get almost 40K events per second. DataModel-2 don't change that frequently. In output we need data through which we can see a trend of tag for given zip. Like in given time zip how many users are tweeting with given tag.

I have below questions

We can use spark stream with kafka? However my concern is will we able to scale with 40k feed per second. Though we will get answer as we have started the POC on it. But just wanted to know about others experience and tuning we can apply to achieve it.

If I am going with batch processing like every 1 hour what should be good data store where I can save tweet and later process it. Will Oracle and MySQL will be good for storing the data and then loading it in spark? Or I should dump it in hdfs?

What can good reporting platform  apart from Kibana?

DataModel-1 [{
      hash: #IAMHAPPY,
      users: [123,134,4566,78899] }]

DataModel-2 [{
      zip: zip1
      users: [123,134] },{
      zip: zip2
      users: [4566,78899] }]

Report Data Model [
      {
          zip: zip1,
          hash: [#IAMHAPPY]
      },
      {
          zip: zip2,
          hash: [#IAMHAPPY]
      } ]

答:
Yes. I think with your task 40K messages/s not something hard to reach out. But...

If you're going to process every 1 hour, DON'T use spark streaming. You can store data in 1 hour to HDFS then process it with normal offline spark application. It's much more reasonable way than streaming in your usecase.

I have no idea but ELK is good.

Title: Spark Streaming design questions


问:
TreeMap Key, Value pair exists, but .get(Key) returns the value as null
I have this code (below) that when I print the treemap, I can clearly see the key,value pairs. Every key has a value (no null values in the output). When I get the first key, it will give me the key, but when I try to get the value based on the key, it will return null.

```<code>TreeMap<String, Double> cosinesimilarityvalues = simvalfordoc.returnsortedcosinesimilarityvalues();
System.out.println(cosinesimilarityvalues);
String topkey = cosinesimilarityvalues.firstKey();
System.out.println(topkey);
Double topvalue = cosinesimilarityvalues.get(topkey);
System.out.println(topvalue);
topones.put(topkey, topvalue);
</code>```

Here is part of an output :

```<code>{article04_C9,article08_C12=0.0, article04_C9,article18_C10=0.0, article04_C9,article07_C1=0.0, article04_C9,article03_C10=0.0, article04_C9,article01_C10=0.0, article04_C9,article07_C10=0.0, article04_C9,article17_C10=0.0, article04_C9,article10_C10=0.0, article04_C9,article05_C10=0.0, article04_C9,article11_C10=0.0, article04_C9,article02_C10=0.0, article04_C9,article13_C10=0.0, article04_C9,article02_C13=5.676594773265355E-4, article04_C9,article02_C11=6.228132014119322E-4, article04_C9,article06_C10=6.732460014209593E-4, article04_C9,article12_C10=0.0011438670619737105, article04_C9,article03_C3=0.0011907203907551985, article04_C9,article03_C11=0.0012323612320990097}
</code>```

So I should be getting article04_C9,article08_C12 as firstKey() (which I do)
but when I go to retrieve the value associated with that key, it returns null.

Here is the code that I'm using to populate the treemap

```<code>HashMap<String, Double> cosinesimilarityvalues = new HashMap<String, Double>();
TreeMap<String, Double> sortedcosinesimilarityvalues = new TreeMap<String, Double>();
public void comparecosinesimilarityvalues(List<tfidfvalues> matrix, tfidfvalues currentvector) {
    String articlename = currentvector.returnarticlename();
    String foldername = currentvector.returnfoldername();
    ArrayList<Double> tfidfval = currentvector.returntfidfvaluesforrow();
    articlefolder = articlename+ "_" + foldername;
    CosineSimilarity calculator = new CosineSimilarity();
    for(int i = 0; i < matrix.size(); i++) {
        String compvectorarticlename = matrix.get(i).returnarticlename();
        String compvectorfoldername = matrix.get(i).returnfoldername();
        ArrayList<Double> compvector = matrix.get(i).returntfidfvaluesforrow();

        Double cosinesimilarity = calculator.CosineSimilarityCalc(tfidfval, compvector);

        String comparingwhat = compvectorarticlename + "_" + compvectorfoldername;

        String comparingthese = articlefolder + "," + comparingwhat;
        cosinesimilarityvalues.put(comparingthese, cosinesimilarity);
    }

    Iterator<Map.Entry<String, Double>> iterator = cosinesimilarityvalues.entrySet().iterator();
    while(iterator.hasNext()) {
        Map.Entry<String, Double> entry = iterator.next();
        if((entry.getValue() > 0.989 && entry.getValue() < 1) || entry.getValue() > 1) {
            iterator.remove();
        }
    }

    sortedcosinesimilarityvalues = sortMapByValue(cosinesimilarityvalues);
}

public TreeMap<String, Double> returnsortedcosinesimilarityvalues() {
    return sortedcosinesimilarityvalues;
}
</code>```

Here is the function I am using to sort by value...if that helps

from : https://www.programcreek.com/2013/03/java-sort-map-by-value/

```<code>class ValueComparator implements Comparator<String>{

    HashMap<String, Double> map = new HashMap<String, Double>();

    public ValueComparator(HashMap<String, Double> map){
        this.map.putAll(map);
    }

    @Override
    public int compare(String s1, String s2) {
        if(map.get(s1) >= map.get(s2)){
            return 1;
        }else{
            return -1;
        }
    }
}

public TreeMap<String, Double> sortMapByValue(HashMap<String, Double> map){
    Comparator<String> comparator = new ValueComparator(map);
    //TreeMap is a map sorted by its keys.
    //The comparator is used to sort the TreeMap by keys.
    TreeMap<String, Double> result = new TreeMap<String, Double>(comparator);
    result.putAll(map);
    return result;
}
</code>```

I'm not sure what I'm doing wrong. Please help!

Thanks!

UPDATE

I was able to retrieve the top key and top value via

```<code>Map.Entry<String, Double> entry1 = cosinesimilarityvalues.firstEntry();
String topkey = entry1.getKey();
Double topvalue = entry1.getValue();
</code>```

but I have no idea why this works and the other method does not work.
Although my code now works, I wish I could find out what the difference is!

答:
Usually a Map starts "misbehaving" if its internal state is inconsistent. With a TreeMap, as in your case, that would be caused by a Comparator which is not stable, meaning it doesn't always return the same result for the same input values.

Not having access to the whole code it's hard to pinpoint the cause, one thing to notice is however that your TreeMap becomes inconsistent if you modify it after the initial creation within the sort method. That's because your comparator relies on the state of the map at the time it's instantiated, any later changes are not seen by the comparator.

The firstKey() and firstEntry() methods don't use the comparator for retrieval, they simply go all the way "left" in the binary tree that backs the TreeMap. However get(key) uses the comparator to find the key in the tree, which in your case does not work correctly.

Another possible cause from this answer to a similar question is that your comparator does not respect the requirement

```<code>sgn(compare(x, y)) == -sgn(compare(y, x))
</code>```

That is, if two entries A and B have the same value, comparing (A,B) with your code yields 1, and comparing (B,A) yields 1 as well, so the order of the 2 elements is not properly defined. You should also handle the case of

```<code>map.get(s1).equals(map.get(s2))
</code>```

when comparing two entries and return 0. Note the usage of equals and not ==, as you don't want to compare two Double objects by reference, but by value instead.

Body:
I have this code (below) that when I print the treemap, I can clearly see the key,value pairs. Every key has a value (no null values in the output). When I get the first key, it will give me the key, but when I try to get the value based on the key, it will return null.

TreeMap<String, Double> cosinesimilarityvalues = simvalfordoc.returnsortedcosinesimilarityvalues();
System.out.println(cosinesimilarityvalues);
String topkey = cosinesimilarityvalues.firstKey();
System.out.println(topkey);
Double topvalue = cosinesimilarityvalues.get(topkey);
System.out.println(topvalue);
topones.put(topkey, topvalue);

Here is part of an output :

{article04_C9,article08_C12=0.0, article04_C9,article18_C10=0.0, article04_C9,article07_C1=0.0, article04_C9,article03_C10=0.0, article04_C9,article01_C10=0.0, article04_C9,article07_C10=0.0, article04_C9,article17_C10=0.0, article04_C9,article10_C10=0.0, article04_C9,article05_C10=0.0, article04_C9,article11_C10=0.0, article04_C9,article02_C10=0.0, article04_C9,article13_C10=0.0, article04_C9,article02_C13=5.676594773265355E-4, article04_C9,article02_C11=6.228132014119322E-4, article04_C9,article06_C10=6.732460014209593E-4, article04_C9,article12_C10=0.0011438670619737105, article04_C9,article03_C3=0.0011907203907551985, article04_C9,article03_C11=0.0012323612320990097}

So I should be getting article04_C9,article08_C12 as firstKey() (which I do)
but when I go to retrieve the value associated with that key, it returns null.

Here is the code that I'm using to populate the treemap

HashMap<String, Double> cosinesimilarityvalues = new HashMap<String, Double>();
TreeMap<String, Double> sortedcosinesimilarityvalues = new TreeMap<String, Double>();
public void comparecosinesimilarityvalues(List<tfidfvalues> matrix, tfidfvalues currentvector) {
    String articlename = currentvector.returnarticlename();
    String foldername = currentvector.returnfoldername();
    ArrayList<Double> tfidfval = currentvector.returntfidfvaluesforrow();
    articlefolder = articlename+ "_" + foldername;
    CosineSimilarity calculator = new CosineSimilarity();
    for(int i = 0; i < matrix.size(); i++) {
        String compvectorarticlename = matrix.get(i).returnarticlename();
        String compvectorfoldername = matrix.get(i).returnfoldername();
        ArrayList<Double> compvector = matrix.get(i).returntfidfvaluesforrow();

        Double cosinesimilarity = calculator.CosineSimilarityCalc(tfidfval, compvector);

        String comparingwhat = compvectorarticlename + "_" + compvectorfoldername;

        String comparingthese = articlefolder + "," + comparingwhat;
        cosinesimilarityvalues.put(comparingthese, cosinesimilarity);
    }

    Iterator<Map.Entry<String, Double>> iterator = cosinesimilarityvalues.entrySet().iterator();
    while(iterator.hasNext()) {
        Map.Entry<String, Double> entry = iterator.next();
        if((entry.getValue() > 0.989 && entry.getValue() < 1) || entry.getValue() > 1) {
            iterator.remove();
        }
    }

    sortedcosinesimilarityvalues = sortMapByValue(cosinesimilarityvalues);
}

public TreeMap<String, Double> returnsortedcosinesimilarityvalues() {
    return sortedcosinesimilarityvalues;
}

Here is the function I am using to sort by value...if that helps

from : https://www.programcreek.com/2013/03/java-sort-map-by-value/

class ValueComparator implements Comparator<String>{

    HashMap<String, Double> map = new HashMap<String, Double>();

    public ValueComparator(HashMap<String, Double> map){
        this.map.putAll(map);
    }

    @Override
    public int compare(String s1, String s2) {
        if(map.get(s1) >= map.get(s2)){
            return 1;
        }else{
            return -1;
        }
    }
}

public TreeMap<String, Double> sortMapByValue(HashMap<String, Double> map){
    Comparator<String> comparator = new ValueComparator(map);
    //TreeMap is a map sorted by its keys.
    //The comparator is used to sort the TreeMap by keys.
    TreeMap<String, Double> result = new TreeMap<String, Double>(comparator);
    result.putAll(map);
    return result;
}

I'm not sure what I'm doing wrong. Please help!

Thanks!

UPDATE

I was able to retrieve the top key and top value via

Map.Entry<String, Double> entry1 = cosinesimilarityvalues.firstEntry();
String topkey = entry1.getKey();
Double topvalue = entry1.getValue();

but I have no idea why this works and the other method does not work.
Although my code now works, I wish I could find out what the difference is!

Body:
Usually a Map starts "misbehaving" if its internal state is inconsistent. With a TreeMap, as in your case, that would be caused by a Comparator which is not stable, meaning it doesn't always return the same result for the same input values.

Not having access to the whole code it's hard to pinpoint the cause, one thing to notice is however that your TreeMap becomes inconsistent if you modify it after the initial creation within the sort method. That's because your comparator relies on the state of the map at the time it's instantiated, any later changes are not seen by the comparator.

The firstKey() and firstEntry() methods don't use the comparator for retrieval, they simply go all the way "left" in the binary tree that backs the TreeMap. However get(key) uses the comparator to find the key in the tree, which in your case does not work correctly.

Another possible cause from this answer to a similar question is that your comparator does not respect the requirement

sgn(compare(x, y)) == -sgn(compare(y, x))

That is, if two entries A and B have the same value, comparing (A,B) with your code yields 1, and comparing (B,A) yields 1 as well, so the order of the 2 elements is not properly defined. You should also handle the case of

map.get(s1).equals(map.get(s2))

when comparing two entries and return 0. Note the usage of equals and not ==, as you don't want to compare two Double objects by reference, but by value instead.


问:
Automating a button click issue
I'm having some trouble with automating a button test.
How can I automate a test with Java&Selenium to auto-click this following button?

```<code><button class="btn btn-default primary-bg btn-lg">Submit</button>
</code>```

I tried this:

```<code>driver.findElement(By.xpath("//button[@class= .btn btn-default primary-bg btn-lg']")).click();
</code>```

What am I doing wrong? What other solutions are there?

答:
Try to add ' after class=

```<code>     driver.findElement(By.xpath("//button[@class=' .btn btn-default primary-bg btn-lg']")).click();
</code>```

Or maybe

```<code>     driver.findElement(By.xpath("//button[@class='btn btn-default primary-bg btn-lg']")).click();
</code>```

Title: Automating a button click issue

Body:
I'm having some trouble with automating a button test.
How can I automate a test with Java&Selenium to auto-click this following button?

<button class="btn btn-default primary-bg btn-lg">Submit</button>

I tried this:

driver.findElement(By.xpath("//button[@class= .btn btn-default primary-bg btn-lg']")).click();

What am I doing wrong? What other solutions are there?

Body:
Try to add ' after class=

     driver.findElement(By.xpath("//button[@class=' .btn btn-default primary-bg btn-lg']")).click();

Or maybe

     driver.findElement(By.xpath("//button[@class='btn btn-default primary-bg btn-lg']")).click();


问:
Remove array from multidimentional array using id in php
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

```<code>Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)
</code>```

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

```<code>foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }
</code>```

答:
try this code which remove all array value which value is No</p>

```<code>$cart = array(
    0 => array
    (
        'id' => 11109,
        'value' => 'Yes',
        'field_id' => 234
    ),
    1 => array
    (
        'id' => 11109,
        'value' => 'Yes',
        'field_id' => 123
    ),
    2 => array
    (
        'id' => 11110,
        'value' => 'No',
        'field_id' => 234
    ),
    3 => array
    (
        'id' => 11110,
        'value' => 'No',
        'field_id' => 237
    ),
    4 => array
    (
        'id' => 11111,
        'value' => 'No',
        'field_id' => 237
    ),
);

$found = array();
$i = 0;
foreach ($cart as $key => $data) {
    if ($data['field_id'] == 234 && $data['value'] == 'No') {

        $found[$i]['id'] = $data['id'];
        $found[$i]['value'] = $data['value'];
        $found[$i]['field_id'] = $data['field_id'];
        $i++;

    }
}

echo "```";
print_r($found);
</code>```

<p>then Output Is:</p>

```<code>  Array
(
    [0] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 234
        )

)
</code>```

Body:
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }

Body:
try this code which remove all array value which value is No

$cart = array(
    0 => array
    (
        'id' => 11109,
        'value' => 'Yes',
        'field_id' => 234
    ),
    1 => array
    (
        'id' => 11109,
        'value' => 'Yes',
        'field_id' => 123
    ),
    2 => array
    (
        'id' => 11110,
        'value' => 'No',
        'field_id' => 234
    ),
    3 => array
    (
        'id' => 11110,
        'value' => 'No',
        'field_id' => 237
    ),
    4 => array
    (
        'id' => 11111,
        'value' => 'No',
        'field_id' => 237
    ),
);

$found = array();
$i = 0;
foreach ($cart as $key => $data) {
    if ($data['field_id'] == 234 && $data['value'] == 'No') {

        $found[$i]['id'] = $data['id'];
        $found[$i]['value'] = $data['value'];
        $found[$i]['field_id'] = $data['field_id'];
        $i++;

    }
}

echo "<pre>";
print_r($found);

then Output Is:

  Array
(
    [0] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 234
        )

)


问:
react-bootstrap navbar not rendering correctly
I'm trying to make a navbar using react-bootstrap, but when I render it I get this:

I'm not getting any error messages, and I can't find any documentation explaining what I've got, but clearly I'm doing something wrong. Any ideas?

This is the code I'm using:

```<code>import React from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap/lib/';

const Toolbar = () => {
  return (
    <Navbar staticTop collapseOnSelect>
      <Navbar.Header>
        <Navbar.Brand>
          <a href="test">Brandname Goes Here</a>
        </Navbar.Brand>
        <Navbar.Toggle />
      </Navbar.Header>
      <Navbar.Collapse>
        <Nav>
          <NavItem eventKey={1}>Contact Us</NavItem>
          <NavItem eventKey={2}>About Us</NavItem>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  )
}

export default Toolbar;
</code>```

答:
go to react-bootsrap getting started tab

and copy the link under the  description into your index.html  tag, and if you installed react-bootstrap using npm, then you can import the navbar like so:
import { Navbar, Nav, NavItem } from 'react-bootstrap';

Body:
I'm trying to make a navbar using react-bootstrap, but when I render it I get this:

I'm not getting any error messages, and I can't find any documentation explaining what I've got, but clearly I'm doing something wrong. Any ideas?

This is the code I'm using:

import React from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap/lib/';

const Toolbar = () => {
  return (
    <Navbar staticTop collapseOnSelect>
      <Navbar.Header>
        <Navbar.Brand>
          Brandname Goes Here
        </Navbar.Brand>
        <Navbar.Toggle />
      </Navbar.Header>
      <Navbar.Collapse>

          <NavItem eventKey={1}>Contact Us</NavItem>
          <NavItem eventKey={2}>About Us</NavItem>

      </Navbar.Collapse>
    </Navbar>
  )
}

export default Toolbar;

Body:
go to react-bootsrap getting started tab

and copy the link under the <!-- Latest compiled and minified CSS --> description into your index.html <head> tag, and if you installed react-bootstrap using npm, then you can import the navbar like so:
import { Navbar, Nav, NavItem } from 'react-bootstrap';


问:
AngularJS how to use $scope.$broadcast inside Directive Link
I'm new to AngularJs, I would like to know how can I use broadcast inside my Directive Link, Please take a look, Thank You,

Here is my directive,

```<code>myApp.directive("displayArticleDivDirective", function($parse,$rootScope) {
        return {
            scope: {
              id: "=",
              status: "@"
            },
            link: function($scope, $element, $attrs) {

                var clickingCallback = function() {
                var id = $scope.id;
                var status = $scope.status;

                    console.log(id); /* id is displayed */

                    $scope.$broadcast("ScopeDisplayArticleDiv",{ id: id , article_status: status}); /* this does not execute, nothing happens here */

              };
              $element.bind('click', clickingCallback);
            }
        };
    });
</code>```

Here is my listener .$on

```<code>$scope.$on("ScopeDisplayArticleDiv", function(event,target){
            /* Nothing Happens Here */
                console.log('test');
});
</code>```

The ScopeDisplayArticleDiv wont broadcast, it wont fire and there's no error on my console. I dont know why its not firing,
A working sample would be highly appreciated, Thank You!

答:
Try changing $broadcast to $emit.

They both function very similarly, but $broadcast sends a message down the scope hierarchy, whereas $emit sends it upwards. Assuming your listener is on your controller, or at least above the scope of the directive, that should do the trick.

here's more info on it:
http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx

and a photo from that link depicting what I was describing:
http://www.dotnettricks.com/img/angularjs/emit-broadcast.png

EDIT: alternatively, you could pass a callback function into the directive that would be called each time the click handler is processed.

```<code>myApp.directive("displayArticleDivDirective", function($parse,$rootScope) {
    return {
        scope: {
          id: "=",
          status: "@",
          callbackFn: "&?"
        },
        link: function($scope, $element, $attrs) {

            var clickHandler = function() {
                var id = $scope.id;
                var status = $scope.status;
                if(callbackFn){
                    callbackFn({ id: id , article_status: status});
                }

                console.log(id); /* id is displayed */
          };

          $element.bind('click', clickHandler);
        }
    };
});

$scope.someFunction = function(status)
    //status is passed from inside the directive and this function is run
    //from the parent scope, not the directive scope.
    console.log('test');
});

<display-article-div-directive id={{article.id}} status={{article.status}} callback-fn={{someFunction}}></display-article-div-directive>
</code>```

This would allow an optional callback to be passed to the directive to be triggered when handling a click. Also, you may want to use "<" when binding the id, as the "=" means that you could potentially change the id registered to the directive from the parent controller. I don't know if that was your intention, but I would think an id would be unchanging throughout the lifecycle of the directive instance.

Body:
I'm new to AngularJs, I would like to know how can I use broadcast inside my Directive Link, Please take a look, Thank You,

Here is my directive,

myApp.directive("displayArticleDivDirective", function($parse,$rootScope) {
        return {
            scope: {
              id: "=",
              status: "@"
            },
            link: function($scope, $element, $attrs) {

                var clickingCallback = function() {
                var id = $scope.id;
                var status = $scope.status;

                    console.log(id); /* id is displayed */

                    $scope.$broadcast("ScopeDisplayArticleDiv",{ id: id , article_status: status}); /* this does not execute, nothing happens here */

              };
              $element.bind('click', clickingCallback);
            }
        };
    });

Here is my listener .$on

$scope.$on("ScopeDisplayArticleDiv", function(event,target){
            /* Nothing Happens Here */
                console.log('test');
});

The ScopeDisplayArticleDiv wont broadcast, it wont fire and there's no error on my console. I dont know why its not firing,
A working sample would be highly appreciated, Thank You!

Body:
Try changing $broadcast to $emit.

They both function very similarly, but $broadcast sends a message down the scope hierarchy, whereas $emit sends it upwards. Assuming your listener is on your controller, or at least above the scope of the directive, that should do the trick.

here's more info on it:
http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx

and a photo from that link depicting what I was describing:
http://www.dotnettricks.com/img/angularjs/emit-broadcast.png

EDIT: alternatively, you could pass a callback function into the directive that would be called each time the click handler is processed.

myApp.directive("displayArticleDivDirective", function($parse,$rootScope) {
    return {
        scope: {
          id: "=",
          status: "@",
          callbackFn: "&?"
        },
        link: function($scope, $element, $attrs) {

            var clickHandler = function() {
                var id = $scope.id;
                var status = $scope.status;
                if(callbackFn){
                    callbackFn({ id: id , article_status: status});
                }

                console.log(id); /* id is displayed */
          };

          $element.bind('click', clickHandler);
        }
    };
});

$scope.someFunction = function(status)
    //status is passed from inside the directive and this function is run
    //from the parent scope, not the directive scope.
    console.log('test');
});

<display-article-div-directive id={{article.id}} status={{article.status}} callback-fn={{someFunction}}></display-article-div-directive>

This would allow an optional callback to be passed to the directive to be triggered when handling a click. Also, you may want to use "<" when binding the id, as the "=" means that you could potentially change the id registered to the directive from the parent controller. I don't know if that was your intention, but I would think an id would be unchanging throughout the lifecycle of the directive instance.


问:
when I minimize the app, the app is not showing in task manager
I have developed android app its working fine but when I minimize the app, the app is not showing in task manager

after opening the app press on home button app need to be displayed in taskmanger running apps to resume app

答:
Check carefully if you accidently added below line in your manifest and remove it if it is there:</p>

```<code><activity android:name=".MainActivity"
    android:excludeFromRecents="true" //<----
</code>```

Body:
Check carefully if you accidently added below line in your manifest and remove it if it is there:

<activity android:name=".MainActivity"
    android:excludeFromRecents="true" //<----


问:
How to check button is pressed or not in while loop in java?
I've a native function called get, I'm checking the returned value in while loop by this function. If this returned value is 1, I continue to get different returned value. However, as you predict it cause infinite loop in this way. So that, I also want to check the stop button is pressed to break infinite while loop. How can I do that?

My Native Function

```<code>int rValue = get();  // I get returned value here from native get() function

while(rValue == 1)
{
   rValue = get();  // I'm trying to get different returned value here
   if(stopButton.getModel().isPressed() == true) // I tried something like this but didn't work
        break;
}

if(rValue == -1)
{
  // do something
}
</code>```

答:
You have to use Action Listener to achieve this

Something like this,

```<code>stopButton.addActionListener( new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("Stop Button Clicked");
    }
});
</code>```

Body:
I've a native function called get, I'm checking the returned value in while loop by this function. If this returned value is 1, I continue to get different returned value. However, as you predict it cause infinite loop in this way. So that, I also want to check the stop button is pressed to break infinite while loop. How can I do that?

My Native Function

int rValue = get();  // I get returned value here from native get() function

while(rValue == 1)
{
   rValue = get();  // I'm trying to get different returned value here
   if(stopButton.getModel().isPressed() == true) // I tried something like this but didn't work
        break;
}

if(rValue == -1)
{
  // do something
}

Body:
You have to use Action Listener to achieve this

Something like this,

stopButton.addActionListener( new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("Stop Button Clicked");
    }
});


问:
Add an image in background and a text zone
Well I'm a newbie in latex and I want to make a latex Curriculum Vitae.
I want to create a page with two parts

First part: an image from TOP to Bottom, and from left to the middle of the page

Second part: a text zone from from TOP to Bottom, and from middle of the page to the right

I have tried to create two columns but every time one of the columnes are put on the next pages :(

Do you have any advice or tips or answer to give me?

Thank you very much for your help.

答:
For a single-page split-view display, you can set the content in a tabularx structure. The left-hand side contains an image with no height/depth. This allows you put anything in the right-hand side.

```<code>\documentclass{article}

\usepackage[margin=1in]{geometry}
\usepackage{graphicx,tabularx}
\usepackage{lipsum}

\setlength{\parindent}{0pt}
\pagestyle{empty}

\begin{document}

\begin{tabularx}{\textwidth}{@{} X X @{}}
  \raisebox{\dimexpr-\height+.7\normalbaselineskip}[0pt][0pt]{%
    \includegraphics[width=\linewidth,height=\textheight]{example-image}} &
    \lipsum[1-3]
\end{tabularx}

\end{document}
</code>```

There are multiple ways of doing this. It all depends on whether you're stuck with a single page, or want to move to a bigger canvas.

Body:
For a single-page split-view display, you can set the content in a tabularx structure. The left-hand side contains an image with no height/depth. This allows you put anything in the right-hand side.

\documentclass{article}

\usepackage[margin=1in]{geometry}
\usepackage{graphicx,tabularx}
\usepackage{lipsum}

\setlength{\parindent}{0pt}
\pagestyle{empty}

\begin{document}

\begin{tabularx}{\textwidth}{@{} X X @{}}
  \raisebox{\dimexpr-\height+.7\normalbaselineskip}[0pt][0pt]{%
    \includegraphics[width=\linewidth,height=\textheight]{example-image}} &
    \lipsum[1-3]
\end{tabularx}

\end{document}

There are multiple ways of doing this. It all depends on whether you're stuck with a single page, or want to move to a bigger canvas.


问:
driver.wait() throws IllegalMonitorStateException
All the variations of wait(...) are throwing the below exception from the following code. What am I doing wrong?</p>

```<code>java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at LoginPage.main(LoginPage.java:29)

try
        {
            driver.get("http://domain:port/coco/webapp/login/login.faces");

            driver.findElement(By.id("clientCode")).sendKeys("coco");
            driver.findElement(By.id("systemCode")).sendKeys("consumer");
            driver.findElement(By.id("userId")).sendKeys("ffadmin");
            driver.findElement(By.id("password")).sendKeys("password");

            driver.findElement(By.className("af_commandButton")).click();
            driver.wait();
            Assert.assertTrue(driver.getPageSource().contains("Administration"));

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
</code>```

答:
Use the below code, this will work.</p>

```<code>synchronized (driver)
{
　　driver.wait(2000);
}
driver.context(NATIVE_APP);
driver.findElementByXPath("//android.widget.Button[@resourceid=‘android:id/button1’]").click();
</code>```

Body:
All the variations of wait(...) are throwing the below exception from the following code. What am I doing wrong?

java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:485)
    at LoginPage.main(LoginPage.java:29)

try
        {
            driver.get("http://domain:port/coco/webapp/login/login.faces");

            driver.findElement(By.id("clientCode")).sendKeys("coco");
            driver.findElement(By.id("systemCode")).sendKeys("consumer");
            driver.findElement(By.id("userId")).sendKeys("ffadmin");
            driver.findElement(By.id("password")).sendKeys("password");

            driver.findElement(By.className("af_commandButton")).click();
            driver.wait();
            Assert.assertTrue(driver.getPageSource().contains("Administration"));

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

Body:
Use the below code, this will work.

synchronized (driver)
{
　　driver.wait(2000);
}
driver.context(NATIVE_APP);
driver.findElementByXPath("//android.widget.Button[@resourceid=‘android:id/button1’]").click();


问:
Understanding the following piece of code in smalltalk
I am trying to understand the following piece of code in smalltalk

```<code>Character extend [
   isGraph [
      ^ (Character space < self) & (self <= $~)
   ]
   visible [
      self isGraph ifTrue: [^ '$', self asString]
                   ifFalse: [^ self asInteger printStringRadix: 16]
   ]
]
</code>```

So basically what that code is doing is to extend the functionality of character by adding two new functions to it. IsGraph returns a boolean value, but I don't understand its purpose. How do you interpret (Character space < self) & (self <= $~)?. Somehow the message space is sent to character and that returns something which is compared to self and then self is compared to $~. Can also someone explain the meaning of the symbol ',' in the iftrue block?

答:
welcome to StackOverflow.

First of all the code is adding two new methods and not functions as this is object-oriented programming.

When you send the space message to the Character class it will return you an instance if that class which represents the space character. isGraph probably means "is graphical" because the characters that precede space in the ASCII table do not have a graphical representation (they are NULL, CR, ESC, etc.) as well as the DEL character that follows ~. Thus with isGraph, you check whether a character is between space and ~ on ASCII table.

visible returns a visible representation of a character and relies on isGraph to decide whether to return the actual character or its integer ASCII representation. The actual character is returned in the Smalltalk's character literal format e.g. $a is used for character a, $3 is used for character 3. Strings are concatenated with the , message.

Actually, one of the main points of Smalltalk is understandability. Thus you should be always able to debug a small piece of code or look at the implementations of a message (like , in your case). But I suspect that you use something like GNU Smalltalk that lacks many of these features.

Body:
I am trying to understand the following piece of code in smalltalk

Character extend [
   isGraph [
      ^ (Character space < self) & (self <= $~)
   ]
   visible [
      self isGraph ifTrue: [^ '$', self asString]
                   ifFalse: [^ self asInteger printStringRadix: 16]
   ]
]

So basically what that code is doing is to extend the functionality of character by adding two new functions to it. IsGraph returns a boolean value, but I don't understand its purpose. How do you interpret (Character space < self) & (self <= $~)?. Somehow the message space is sent to character and that returns something which is compared to self and then self is compared to $~. Can also someone explain the meaning of the symbol ',' in the iftrue block?


问:
Using firebase admin node.js SDK via edge.js (c#)
I have web service that writing in C# , and host in azure .
As part of my processing I want to use the fire-base admin via my C# code.
After I looking in the web I found the edge.js package that let you to run node.js scripts under C# , I install the package and success to run different node.js scripts via C# .
The problem start when I try to use the firebase admin SDK .
I install the firebase lib via npm (npm install firebase-admin -g) as global package.
Then I try to use it for calling the firebase lib , I try only to load the lib and I received error.

```<code> var func = Edge.Func(@"

return function(data,callback)
{
var admin = require('firebase - admin');
callback(null, 'test fcm ' + data);
}

");
</code>```

The error I received in c# is :

An unhandled exception of type 'System.AggregateException' occurred in
  mscorlib.dll

So I have several question :
1. May someone success to work with the fire-base lib via edge.js  ?

How I can debug the error ?

May someone have different method for calling the firebase admin nodejs sdk via C# ?

May someone have any method for calling the firebase admin via C# code ?

Thanks ,
MAK

答:
To avoid this error, you'd need to run the command npm install firebase-admin in the root of your c# project, it will install the dependencies in the node_modules folder for your project.

You also need to remove spaces from the package name as below:

```<code>var admin = require('firebase-admin');
</code>```

Body:
I have web service that writing in C# , and host in azure .
As part of my processing I want to use the fire-base admin via my C# code.
After I looking in the web I found the edge.js package that let you to run node.js scripts under C# , I install the package and success to run different node.js scripts via C# .
The problem start when I try to use the firebase admin SDK .
I install the firebase lib via npm (npm install firebase-admin -g) as global package.
Then I try to use it for calling the firebase lib , I try only to load the lib and I received error.

 var func = Edge.Func(@"

return function(data,callback)
{
var admin = require('firebase - admin');
callback(null, 'test fcm ' + data);
}

");

The error I received in c# is :

An unhandled exception of type 'System.AggregateException' occurred in
  mscorlib.dll

So I have several question :
1. May someone success to work with the fire-base lib via edge.js  ?

How I can debug the error ?

May someone have different method for calling the firebase admin nodejs sdk via C# ?

May someone have any method for calling the firebase admin via C# code ?

Thanks ,
MAK

Body:
To avoid this error, you'd need to run the command npm install firebase-admin in the root of your c# project, it will install the dependencies in the node_modules folder for your project.

You also need to remove spaces from the package name as below:

var admin = require('firebase-admin');


问:
How to reference subquery in the WHERE clause
I have a SQL query (T-SQL) in which I have a subquery in the SELECT statement.

Here is a reduced version:

```<code>SELECT
    p.id AS id,
    (SELECT
        jobs_without_price.id
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
FROM
    st_person p
WHERE
    JobsWithoutPrice IS NOT NULL
GROUP BY
    p.id
</code>```

The problem is that SSMS tells me

Invalid column name 'JobsWithoutPrice'.

This is almost certainly because SQL doesn't allow aliases in WHERE clauses, but how else can I use the result of this subquery to filter the results?

[The full query has more table joins and much more in the SELECT statement, all of which pertains to a single person record, whereas the subquery reports back multiple records, which is why it's in a subquery.]

答:
try this:</p>

```<code>SELECT
    p.id AS id,
    -- sum(a), max(b), min(c) <--- what you want from JobsWithoutPrice table
FROM st_person p inner join (
    (SELECT jobs_without_price.id, -- jobs_without_price.a, jobs_without_price.b, jobs_without_price.c
    FROM st_job jobs_without_price
    WHERE jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
) on (jobs_without_price.person_id = p.id)
GROUP BY p.id
</code>```

Body:
I have a SQL query (T-SQL) in which I have a subquery in the SELECT statement.

Here is a reduced version:

SELECT
    p.id AS id,
    (SELECT
        jobs_without_price.id
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
FROM
    st_person p
WHERE
    JobsWithoutPrice IS NOT NULL
GROUP BY
    p.id

The problem is that SSMS tells me

Invalid column name 'JobsWithoutPrice'.

This is almost certainly because SQL doesn't allow aliases in WHERE clauses, but how else can I use the result of this subquery to filter the results?

[The full query has more table joins and much more in the SELECT statement, all of which pertains to a single person record, whereas the subquery reports back multiple records, which is why it's in a subquery.]

Body:
try this:

SELECT
    p.id AS id,
    -- sum(a), max(b), min(c) <--- what you want from JobsWithoutPrice table
FROM st_person p inner join (
    (SELECT jobs_without_price.id, -- jobs_without_price.a, jobs_without_price.b, jobs_without_price.c
    FROM st_job jobs_without_price
    WHERE jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
) on (jobs_without_price.person_id = p.id)
GROUP BY p.id


问:
Given a string, how to iterate through many regexes to find a match?
Given a string, and a mapping of regexes to integers, I want to find out which integer the string maps to (assume the string will match exactly one of those regexes)

Is it inefficient to just iterate through the hash of regexes, trying each regex against the string, then outputting the value? Certainly I cannot explicitly enumerate all possible string => integer mappings, but it seems bad to try matching each regex in bunch of regexes.

答:
Just do as you suggest, loop over the hash of regex/numbers and return the first that matches a string:

```<code>def find_match(regex_mapping, str)
  regex_mapping.each do |regex, n|
    return n if str =~ regex
  end
  return nil
end
</code>```

The only thing to say about efficiency is this: it probably doesn't matter anyway. Just write your code as clearly and simply as you can, and then, in the end, if it is to slow, run it through a profiler (for example the absolutely awesome perftools.rb) and see what the hotspots are. Optimize those. Don't optimize before you've written any code.

That said, a simple optimization you can do in this case, which doesn't cost you anything, is to put the regexes into the mapping hash in an order such that the most likely to match comes first, that way fewer comparisons have to be made (but this is a probabilistic optimization, the worst case running time remains the same). This only applies to Ruby 1.9 though, since hashes don't retain their insertion order in 1.8.

Body:
Just do as you suggest, loop over the hash of regex/numbers and return the first that matches a string:

def find_match(regex_mapping, str)
  regex_mapping.each do |regex, n|
    return n if str =~ regex
  end
  return nil
end

The only thing to say about efficiency is this: it probably doesn't matter anyway. Just write your code as clearly and simply as you can, and then, in the end, if it is to slow, run it through a profiler (for example the absolutely awesome perftools.rb) and see what the hotspots are. Optimize those. Don't optimize before you've written any code.

That said, a simple optimization you can do in this case, which doesn't cost you anything, is to put the regexes into the mapping hash in an order such that the most likely to match comes first, that way fewer comparisons have to be made (but this is a probabilistic optimization, the worst case running time remains the same). This only applies to Ruby 1.9 though, since hashes don't retain their insertion order in 1.8.

ContentLicense: CC BY-SA 2.5


问:
How to create a 'Load More' feature without re-rendering entire component in React/Node?
I'm trying to create a simple poll app, where you can make new polls.

In the section 'MyPolls', I want it to render only the first 5 polls that I've made instead of rendering the entire list of polls.

At the bottom is a 'Load More' button, where upon clicking, loads another 5 polls and so on.

I've been using Mongoose/MongoDB backend and my approach has been to use skip and limit.

I've managed to implement this feature, but the problem is the entire component re-renders, which is annoying for a user as you have to scroll down again the click the 'Load More' button.

Here is my app: https://voting-app-drhectapus.herokuapp.com/

(use can you these login details for convenience:
username: riverfish@gmail.com
password: 123)

And then goto the My Polls page.

MyPoll.js:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';

class MyPolls extends Component {
  constructor(props) {
    super(props);
    this.state = {
      skip: 0
    };
  }

  componentDidMount() {
    this.props.fetchMyPolls(this.state.skip);
    this.setState({ skip: this.state.skip + 5 });
  }

  sumVotes(polls) {
    return polls.reduce((a, b) => {
      return a.votes + b.votes;
    });
  }

  loadMore(skip) {
    this.props.fetchMyPolls(skip);
    const nextSkip = this.state.skip + 5;
    this.setState({ skip: nextSkip });
  }

  renderPolls() {
    return this.props.polls.map(poll => {
      return (
        <div className='card' key={poll._id}>
          <div className='card-content'>
            <span className='card-title'>{poll.title}</span>
            <p>Votes: {this.sumVotes(poll.options)}</p>
          </div>
        </div>
      )
    })
  }

  render() {
    console.log('polls', this.props.polls);
    console.log('skip:', this.state.skip);
    return (
      <div>
        <h2>My Polls</h2>
        {this.renderPolls()}
        <a href='#' onClick={() => this.loadMore(this.state.skip)}>Load More</a>
      </div>

    );
  }
}

function mapStateToProps({ polls }) {
  return { polls }
}

export default connect(mapStateToProps, actions)(MyPolls);
</code>```

Action creator:

```<code>export const fetchMyPolls = (skip) => async dispatch => {
  const res = await axios.get(`/api/mypolls/${skip}`);

  dispatch({ type: FETCH_MY_POLLS, payload: res.data });
}
</code>```

Poll route:

```<code>app.get('/api/mypolls/:skip', requireLogin, (req, res) => {

    console.log(req.params.skip);

    Poll.find({ _user: req.user.id })
      .sort({ dateCreated: -1 })
      .skip(parseInt(req.params.skip))
      .limit(5)
      .then(polls => {
        res.send(polls);
      });
  });
</code>```

Entire github repo: https://github.com/drhectapus/voting-app

I understand that might method of implementing this feature might be the best possible solution so I'm open to any suggestions.

答:
It looks like the re-render is triggered by the fact that clicking the "Load More" link actually causes react router to navigate to a new route, causing the entire MyPolls component to re-render.

Just replace the href='#' onClick={...}> with <button onClick={...}>.

If you don't want to use a button, you could also change the onClick function to

```<code>const onLoadMoreClick = e => {
    e.preventDefault(); // this prevents the navigation normally occuring with an <a> element
    this.loadMore(this.state.skip);
}
</code>```

Body:
I'm trying to create a simple poll app, where you can make new polls.

In the section 'MyPolls', I want it to render only the first 5 polls that I've made instead of rendering the entire list of polls.

At the bottom is a 'Load More' button, where upon clicking, loads another 5 polls and so on.

I've been using Mongoose/MongoDB backend and my approach has been to use skip and limit.

I've managed to implement this feature, but the problem is the entire component re-renders, which is annoying for a user as you have to scroll down again the click the 'Load More' button.

Here is my app: https://voting-app-drhectapus.herokuapp.com/

(use can you these login details for convenience:
username: riverfish@gmail.com
password: 123)

And then goto the My Polls page.

MyPoll.js:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';

class MyPolls extends Component {
  constructor(props) {
    super(props);
    this.state = {
      skip: 0
    };
  }

  componentDidMount() {
    this.props.fetchMyPolls(this.state.skip);
    this.setState({ skip: this.state.skip + 5 });
  }

  sumVotes(polls) {
    return polls.reduce((a, b) => {
      return a.votes + b.votes;
    });
  }

  loadMore(skip) {
    this.props.fetchMyPolls(skip);
    const nextSkip = this.state.skip + 5;
    this.setState({ skip: nextSkip });
  }

  renderPolls() {
    return this.props.polls.map(poll => {
      return (

            {poll.title}

Votes: {this.sumVotes(poll.options)}

      )
    })
  }

  render() {
    console.log('polls', this.props.polls);
    console.log('skip:', this.state.skip);
    return (

My Polls

        {this.renderPolls()}
         this.loadMore(this.state.skip)}>Load More

    );
  }
}

function mapStateToProps({ polls }) {
  return { polls }
}

export default connect(mapStateToProps, actions)(MyPolls);

Action creator:

export const fetchMyPolls = (skip) => async dispatch => {
  const res = await axios.get(`/api/mypolls/${skip}`);

  dispatch({ type: FETCH_MY_POLLS, payload: res.data });
}

Poll route:

app.get('/api/mypolls/:skip', requireLogin, (req, res) => {

    console.log(req.params.skip);

    Poll.find({ _user: req.user.id })
      .sort({ dateCreated: -1 })
      .skip(parseInt(req.params.skip))
      .limit(5)
      .then(polls => {
        res.send(polls);
      });
  });

Entire github repo: https://github.com/drhectapus/voting-app

I understand that might method of implementing this feature might be the best possible solution so I'm open to any suggestions.

Body:
It looks like the re-render is triggered by the fact that clicking the "Load More" link actually causes react router to navigate to a new route, causing the entire MyPolls component to re-render.

Just replace the <a href='#' onClick={...}> with <button onClick={...}>.

If you don't want to use a button, you could also change the onClick function to

const onLoadMoreClick = e => {
    e.preventDefault(); // this prevents the navigation normally occuring with an <a> element
    this.loadMore(this.state.skip);
}