问:
Issue regarding copying data from second stored value _Ty2 second of a std::map iterator
I am using visual studio 2008 as compiler. I have a std map which contains first parameter as std::string and second parameter as struct CSVFileInfo. I tried to copy the iterator second parameter to an another object of CSVFileInfo using memcpy function as follows,

```<code>std::map<std::string, CSVFileInfo>::iterator iter;
for(iter = csv_files.begin(); iter != csv_files.end(); iter++)
{
  CSVFileInfo objCsv;
  memcpy(&objCsv, &(iter->second), sizeof(CSVFileInfo));
}
</code>```

which resulted in a crash in release mode but not in debug mode. My struct is as follows,

```<code>    struct CSVFileInfo
    {
        typedef boost::thread _csv_run_thread_;
        bool m_outofService;
        bool m_readonly;
        bool m_is_running;
        int m_start_option;
        HTREEITEM m_item;
        std::string m_fileNamePath;
        std::string m_file;
        CCSVHandler* m_csvHandler;
        _csv_run_thread_ *m_thread;

        CSVFileInfo() : m_outofService(false), m_readonly(false), m_thread(NULL),
            m_is_running(false), m_csvHandler(NULL), m_item(NULL), m_start_option(100)
        {
        }
    };
</code>```

When i found the crash i changed my code to,

```<code>    CSVFileInfo csvFileInfo;
    csvFileInfo.m_csvHandler = iter->second.m_csvHandler;
    csvFileInfo.m_file = iter->second.m_file;
    csvFileInfo.m_fileNamePath = iter->second.m_fileNamePath;
    csvFileInfo.m_is_running = iter->second.m_is_running;
    csvFileInfo.m_item = iter->second.m_item;
    csvFileInfo.m_outofService = iter->second.m_outofService;
    csvFileInfo.m_readonly = iter->second.m_readonly;
    csvFileInfo.m_start_option = iter->second.m_start_option;
    csvFileInfo.m_thread = iter->second.m_thread;
</code>```

instead of the memcpy function. I fixed the issue.

My doubt is regarding the crash, why memcpy gave a crash when i used it in this situation?

答:
One of the main problems is that you use std::memcpy to copy objects. This should be solved by doing simple copy-construction (or even assignment), if you really need a copy:

```<code>CSVFileInfo objCsv = iter->second;
</code>```

If you don't actually need a copy, use references instead:

```<code>CSVFileInfo &objCsv = iter->second;
</code>```

Using std::memcpy is troublesome because it's basically does a byte-wise copy, disregarding the C++ copy-semantics (copy-construction, copy-assignment). That will be very problematic when using other classes inside your class, like the std::string members as they will not be copied correctly.

Using C++ copy-semantics will solve this problem.

In general, unless you have a C-style POD object you should avoid C-style functions for manipulating the object (e.g. memcpy or memset and more).

Body:
I am using visual studio 2008 as compiler. I have a std map which contains first parameter as std::string and second parameter as struct CSVFileInfo. I tried to copy the iterator second parameter to an another object of CSVFileInfo using memcpy function as follows,

std::map<std::string, CSVFileInfo>::iterator iter;
for(iter = csv_files.begin(); iter != csv_files.end(); iter++)
{
  CSVFileInfo objCsv;
  memcpy(&objCsv, &(iter->second), sizeof(CSVFileInfo));
}

which resulted in a crash in release mode but not in debug mode. My struct is as follows,

    struct CSVFileInfo
    {
        typedef boost::thread _csv_run_thread_;
        bool m_outofService;
        bool m_readonly;
        bool m_is_running;
        int m_start_option;
        HTREEITEM m_item;
        std::string m_fileNamePath;
        std::string m_file;
        CCSVHandler* m_csvHandler;
        _csv_run_thread_ *m_thread;

        CSVFileInfo() : m_outofService(false), m_readonly(false), m_thread(NULL),
            m_is_running(false), m_csvHandler(NULL), m_item(NULL), m_start_option(100)
        {
        }
    };

When i found the crash i changed my code to,

    CSVFileInfo csvFileInfo;
    csvFileInfo.m_csvHandler = iter->second.m_csvHandler;
    csvFileInfo.m_file = iter->second.m_file;
    csvFileInfo.m_fileNamePath = iter->second.m_fileNamePath;
    csvFileInfo.m_is_running = iter->second.m_is_running;
    csvFileInfo.m_item = iter->second.m_item;
    csvFileInfo.m_outofService = iter->second.m_outofService;
    csvFileInfo.m_readonly = iter->second.m_readonly;
    csvFileInfo.m_start_option = iter->second.m_start_option;
    csvFileInfo.m_thread = iter->second.m_thread;

instead of the memcpy function. I fixed the issue.

My doubt is regarding the crash, why memcpy gave a crash when i used it in this situation?

Body:
One of the main problems is that you use std::memcpy to copy objects. This should be solved by doing simple copy-construction (or even assignment), if you really need a copy:

CSVFileInfo objCsv = iter->second;

If you don't actually need a copy, use references instead:

CSVFileInfo &objCsv = iter->second;

Using std::memcpy is troublesome because it's basically does a byte-wise copy, disregarding the C++ copy-semantics (copy-construction, copy-assignment). That will be very problematic when using other classes inside your class, like the std::string members as they will not be copied correctly.

Using C++ copy-semantics will solve this problem.

In general, unless you have a C-style POD object you should avoid C-style functions for manipulating the object (e.g. memcpy or memset and more).


来源: stackexchange

问:
Control StackNavigator outside of the animated scene
EDIT: I understand my problem and solution so I'm rephrasing my question, followed by an answer.

A normal StackNavigator and screen with navigation looks like this:

```<code>class ExampleScreen extends React.Component {
  render() {
    const { navigate, state } = this.props.navigation.navigate;
    const exampleTitle = state.params.title;

    return (
      <View>
        <Text>{exampleTitle}</Text>
        <Button
          title="Click"
          onPress={() => {
            navigate('Example', { exampleTitle: 'foo' })
          }}
        />
      </View>
    );
  }
}

const ExampleNavigator = StackNavigator({
  Example: { screen: ExampleScreen }
}, {
  initialRouteName: 'Example',
  initialRouteParams: { exampleTitle: 'bar' }
});

AppRegistry.registerComponent('Example', () => ExampleNavigator);
</code>```

I would like to access the navigation object outside of ExampleScreen#render so that it isn't part of the CardStack animation.

答:
I believe what I would like to do is very similar, if not identical, to this. I don't understand why this isn't so common (extracting behaviour from a component and allowing higher level components to define behaviour across a set of components, and in this case define all navigation behaviour) as to be supported without having to use refs.

An ideal solution would seem to be:

```<code>class ExampleScreen extends React.Component {
  render() {
    const { navigate, state } = this.props.navigation.navigate;
    const exampleTitle = state.params.title;

    return (
      <View>
        <Text>{exampleTitle}</Text>
        <Button
          title="Click"
          onPress=state.params.onPress
        />
      </View>
    );
  }
}

const ExampleNavigator = StackNavigator({
  Example: { screen: ExampleScreen }
}, {
  initialRouteName: 'Example',
  initialRouteParams: {
    exampleTitle: 'bar',
    onPress: () => {XXX.navigate('Example', { exampleTitle: 'foo' })}
  }
});

AppRegistry.registerComponent('Example', () => ExampleNavigator);
</code>```

with navigate being available somehow within StackNavigator initialRouteParams.

Am I also missing something here in terms of an easy solution to what seems like a commonly expected design pattern?

ContentLicense: CC BY-SA 3.0

Body:
EDIT: I understand my problem and solution so I'm rephrasing my question, followed by an answer.

A normal StackNavigator and screen with navigation looks like this:

class ExampleScreen extends React.Component {
  render() {
    const { navigate, state } = this.props.navigation.navigate;
    const exampleTitle = state.params.title;

    return (
      <View>
        <Text>{exampleTitle}</Text>
        <Button
          title="Click"
          onPress={() => {
            navigate('Example', { exampleTitle: 'foo' })
          }}
        />
      </View>
    );
  }
}

const ExampleNavigator = StackNavigator({
  Example: { screen: ExampleScreen }
}, {
  initialRouteName: 'Example',
  initialRouteParams: { exampleTitle: 'bar' }
});

AppRegistry.registerComponent('Example', () => ExampleNavigator);

I would like to access the navigation object outside of ExampleScreen#render so that it isn't part of the CardStack animation.

Body:
I believe what I would like to do is very similar, if not identical, to this. I don't understand why this isn't so common (extracting behaviour from a component and allowing higher level components to define behaviour across a set of components, and in this case define all navigation behaviour) as to be supported without having to use refs.

An ideal solution would seem to be:

class ExampleScreen extends React.Component {
  render() {
    const { navigate, state } = this.props.navigation.navigate;
    const exampleTitle = state.params.title;

    return (
      <View>
        <Text>{exampleTitle}</Text>
        <Button
          title="Click"
          onPress=state.params.onPress
        />
      </View>
    );
  }
}

const ExampleNavigator = StackNavigator({
  Example: { screen: ExampleScreen }
}, {
  initialRouteName: 'Example',
  initialRouteParams: {
    exampleTitle: 'bar',
    onPress: () => {XXX.navigate('Example', { exampleTitle: 'foo' })}
  }
});

AppRegistry.registerComponent('Example', () => ExampleNavigator);

with navigate being available somehow within StackNavigator initialRouteParams.

Am I also missing something here in terms of an easy solution to what seems like a commonly expected design pattern?


问:
What is 'forward declaration' and the difference between 'typedef struct X' and 'struct X'?
I am a beginner in C programming and I know the difference between struct type declaration and typedef struct declaration. I came across to know an answer saying that if we define a struct like:

```<code>typedef struct {
    some members;
} struct_name;
</code>```

Then it will be like providing an alias to an anonymous struct (as it is not having a tag name). So it can't be used for forward declaration. I don't know what the forward declaration means.

Also, I wanted to know that for the following code:

```<code>typedef struct NAME {
    some members;
} struct_alias;
</code>```

Is there any difference between NAME and struct_alias? Or are both equal as
struct_alias is an alias of  struct NAME ?

Furthermore, can we declare a variable of type struct NAME like these:

```<code>struct_alias variable1;
</code>```

and/or like:

```<code>struct NAME variable2;
</code>```

or like:

```<code>NAME variable3;
</code>```

答:
As others stated before, a forward declaration in C/C++ is the declaration of something with the actual definition unavailable. Its a declaration telling the compiler "there is a data type ABC".

Lets pretend this is a header for some key/value store my_dict.h :

```<code>...
struct my_dict_t;
struct my_dict_t* create();

char* get_value(const struct my_dict_t* dict, const char* name);
char* insert(struct my_dict_t* dict, const char* name, char* value);
void destroy(struct my_dict_t* dict);
...
</code>```

You dont know anything about my_dict_t, but actually, for using the store
you dont need to know:

```<code>#include "my_dict.h"
...
struct my_dict_t* dict = create();
if(0 != insert(dict, "AnEntry", strdup("AValue"))) {
    ...
}
...
</code>```

The reason for this is: You are only using POINTERS to the data structure.

POINTERS are just numbers, and for dealing with them you dont need to know what they are pointing at.

This will only matter if you try to actually access them, like

```<code>struct my_dict_t* dict = create();
printf("%s\n", dict->value);  /* Impossible if only a forward decl is available */
</code>```

So, for implementing the functions, you require an actual definition of my_struct_t.
You might do this in the source file my_dict.c like so:

```<code>#include "my_dict.h"

struct my_dict_t {
    char* value;
    const char* name;
    struct my_dict_t* next;
}

struct my_dict_t* create() {
    return calloc(1, sizeof(struct my_dict_t));
}
</code>```

This is handy for several situations, like

For resolving circular type dependencies, like Sergei L. explained.

For encapsulation, like in the example above.

So the question that remains is: Why cant we just omit the forward declaration at all when using the functions above? In the end, it would suffice for the compiler to know that all dict are pointers.

However, the compiler does perform type checks:
It needs to verify that you don't do something like

```<code>...
int i = 12;
char* value = get_value(&i, "MyName");
...
</code>```

It does not need to know how my_dict_t looks like, but it needs to know that &i is not the type of pointer get_value() expects.

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner in C programming and I know the difference between struct type declaration and typedef struct declaration. I came across to know an answer saying that if we define a struct like:

typedef struct {
    some members;
} struct_name;

Then it will be like providing an alias to an anonymous struct (as it is not having a tag name). So it can't be used for forward declaration. I don't know what the forward declaration means.

Also, I wanted to know that for the following code:

typedef struct NAME {
    some members;
} struct_alias;

Is there any difference between NAME and struct_alias? Or are both equal as
struct_alias is an alias of  struct NAME ?

Furthermore, can we declare a variable of type struct NAME like these:

struct_alias variable1;

and/or like:

struct NAME variable2;

or like:

NAME variable3;

Body:
As others stated before, a forward declaration in C/C++ is the declaration of something with the actual definition unavailable. Its a declaration telling the compiler "there is a data type ABC".

Lets pretend this is a header for some key/value store my_dict.h :

...
struct my_dict_t;
struct my_dict_t* create();

char* get_value(const struct my_dict_t* dict, const char* name);
char* insert(struct my_dict_t* dict, const char* name, char* value);
void destroy(struct my_dict_t* dict);
...

You dont know anything about my_dict_t, but actually, for using the store
you dont need to know:

#include "my_dict.h"
...
struct my_dict_t* dict = create();
if(0 != insert(dict, "AnEntry", strdup("AValue"))) {
    ...
}
...

The reason for this is: You are only using POINTERS to the data structure.

POINTERS are just numbers, and for dealing with them you dont need to know what they are pointing at.

This will only matter if you try to actually access them, like

struct my_dict_t* dict = create();
printf("%s\n", dict->value);  /* Impossible if only a forward decl is available */

So, for implementing the functions, you require an actual definition of my_struct_t.
You might do this in the source file my_dict.c like so:

#include "my_dict.h"

struct my_dict_t {
    char* value;
    const char* name;
    struct my_dict_t* next;
}

struct my_dict_t* create() {
    return calloc(1, sizeof(struct my_dict_t));
}

This is handy for several situations, like

For resolving circular type dependencies, like Sergei L. explained.

For encapsulation, like in the example above.

So the question that remains is: Why cant we just omit the forward declaration at all when using the functions above? In the end, it would suffice for the compiler to know that all dict are pointers.

However, the compiler does perform type checks:
It needs to verify that you don't do something like

...
int i = 12;
char* value = get_value(&i, "MyName");
...

It does not need to know how my_dict_t looks like, but it needs to know that &i is not the type of pointer get_value() expects.


问:
How do connect to a SQL Server Visible in remote Desktop
I am an employee of an organisation which uses Remote Desktop Computers. We log in from personal devices with Windows Remote Desktop to an IP/port combo, say 12.23.1.234:5431.

Once in I have servers accessible on the root path e.g. SVR1

Our main software uses a SQL Server instance on SVR1 e.g. Database_01. I can see this on the software loading screen and switch between SVR1\Database_01 and SVR1\Database_02 etc.

How can I identify the server name/address to connect MS Powerpivot to this server directly from my personal machine?

答:
For this you have static ip address provided by your isp provider or your machine should have connected to your VPN and if you have  one of them then you can access database by enabling tcp/ip in sql server in host machine
for this open SQL Server management configuration
in configuration tab go to
SQL Native Client *.0 Configuration =>Client Protocol
then Right Click on TCP/IP in right panel and make it enable

after that you can able to access sql server remotely by using ip address in server name


问:
Why returned data from web service is not displayed in table?
I use anguraljs 1.6 in my project.

I read data from web service and I need to display returned data in table.

Here is my http ajax call:

```<code>$http.get("../../Services/ReportDepartmentService.asmx/GetRecords").then(function (response) {
          $scope.report = response.data;
    });
</code>```

And here is example of data returned from web service:

```<code>    "<?xml version="1.0" encoding="utf-8"?>
    <ArrayOfDepartmentReport xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://localhost/services">
      <DepartmentReport>
        <IncidentId>140609</IncidentId>
        <JunctionId>1</JunctionId>
        <PropType>Data1</PropType>
        <Damage>Data2</Damage>
        <UserName>John1</UserName>
        <ContractNO>10040/10</ContractNO>
        <FixName>Data3</FixName>
        <TimeStart>14:31</TimeStart>
        <TimeDue>17:31</TimeDue>
        <TimeEnd>14:38</TimeEnd>
        <StatusID>1</StatusID>
        <StatusText>End</StatusText>
        <Priority>High</Priority>
        <Notes />
        <IncidentFactor />
        <Description />
        <DtStartPlus>2017-01-18T14:31:00</DtStartPlus>
        <DtDuePlus>2017-01-18T17:31:00</DtDuePlus>
        <DtEnd>2017-01-18T14:38:00</DtEnd>
      </DepartmentReport>
      <DepartmentReport>
        <IncidentId>140609</IncidentId>
        <JunctionId>1</JunctionId>
        <PropType>Data10</PropType>
        <Damage>Data20</Damage>
        <UserName>Max1</UserName>
        <ContractNO>10040/10</ContractNO>
        <FixName>Data30</FixName>
        <TimeStart>14:31</TimeStart>
        <TimeDue>17:31</TimeDue>
        <TimeEnd>14:38</TimeEnd>
        <StatusID>1</StatusID>
        <StatusText>End</StatusText>
        <Priority>High</Priority>
        <Notes />
        <IncidentFactor />
        <Description>Description1</Description>
        <DtStartPlus>2017-01-30T17:39:00</DtStartPlus>
        <DtDuePlus>2017-01-30T20:39:00</DtDuePlus>
        <DtEnd>2017-01-30T18:34:00</DtEnd>
      </DepartmentReport>
    </ArrayOfDepartmentReport>"
</code>```

as you can see it returned in XML format.

And here is table:

```<code>    <table class="table table-striped table-hover table-condensed">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Credit</th>
                <th>Semester</th>

            </tr>
        </thead>

         <tbody><tr ng-repeat="record in report track by $index">
            <td>{{record.IncidentId}}</td>
            <td>{{record.JunctionId}}</td>
            <td>{{record.PropType}}</td>
            <td>{{record.Damage}}</td>
        </tr>
      </tbody>
    </table>
</code>```

But when I try to display data in the table it's not displayed.

I gess that the records is not displayed because the returned data from the web service is XML format and not JSON format.

Any idea how can I display data in table above?

答:
You have to convert the XML data you are getting to a JSON format using some js library (X2JS for example).

And in your controller try this :

```<code>var vm = this;
var x2js = new X2JS();
var dataAsJson = x2js.xml_str2json(xmlData);
vm.report = dataAsJson.ArrayOfDepartmentReport.DepartmentReport;
</code>```

Here is a working fiddle :

https://jsfiddle.net/gtrwzsn1/398/

Hope this works for you :-)

Body:
I use anguraljs 1.6 in my project.

I read data from web service and I need to display returned data in table.

Here is my http ajax call:

$http.get("../../Services/ReportDepartmentService.asmx/GetRecords").then(function (response) {
          $scope.report = response.data;
    });

And here is example of data returned from web service:

    "<?xml version="1.0" encoding="utf-8"?>
    <ArrayOfDepartmentReport xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://localhost/services">
      <DepartmentReport>
        <IncidentId>140609</IncidentId>
        <JunctionId>1</JunctionId>
        <PropType>Data1</PropType>
        <Damage>Data2</Damage>
        <UserName>John1</UserName>
        <ContractNO>10040/10</ContractNO>
        <FixName>Data3</FixName>
        <TimeStart>14:31</TimeStart>
        <TimeDue>17:31</TimeDue>
        <TimeEnd>14:38</TimeEnd>
        <StatusID>1</StatusID>
        <StatusText>End</StatusText>
        <Priority>High</Priority>
        <Notes />
        <IncidentFactor />
        <Description />
        <DtStartPlus>2017-01-18T14:31:00</DtStartPlus>
        <DtDuePlus>2017-01-18T17:31:00</DtDuePlus>
        <DtEnd>2017-01-18T14:38:00</DtEnd>
      </DepartmentReport>
      <DepartmentReport>
        <IncidentId>140609</IncidentId>
        <JunctionId>1</JunctionId>
        <PropType>Data10</PropType>
        <Damage>Data20</Damage>
        <UserName>Max1</UserName>
        <ContractNO>10040/10</ContractNO>
        <FixName>Data30</FixName>
        <TimeStart>14:31</TimeStart>
        <TimeDue>17:31</TimeDue>
        <TimeEnd>14:38</TimeEnd>
        <StatusID>1</StatusID>
        <StatusText>End</StatusText>
        <Priority>High</Priority>
        <Notes />
        <IncidentFactor />
        <Description>Description1</Description>
        <DtStartPlus>2017-01-30T17:39:00</DtStartPlus>
        <DtDuePlus>2017-01-30T20:39:00</DtDuePlus>
        <DtEnd>2017-01-30T18:34:00</DtEnd>
      </DepartmentReport>
    </ArrayOfDepartmentReport>"

as you can see it returned in XML format.

And here is table:

                Id
                Name
                Credit
                Semester

            {{record.IncidentId}}
            {{record.JunctionId}}
            {{record.PropType}}
            {{record.Damage}}

But when I try to display data in the table it's not displayed.

I gess that the records is not displayed because the returned data from the web service is XML format and not JSON format.

Any idea how can I display data in table above?

Body:
You have to convert the XML data you are getting to a JSON format using some js library (X2JS for example).

And in your controller try this :

var vm = this;
var x2js = new X2JS();
var dataAsJson = x2js.xml_str2json(xmlData);
vm.report = dataAsJson.ArrayOfDepartmentReport.DepartmentReport;

Here is a working fiddle :

https://jsfiddle.net/gtrwzsn1/398/

Hope this works for you :-)


问:
WCF Restful and query string with special characters
I am using WCF with Restful API.

From client, I make a GET request with query string "http://example.com/6500/%2fSIZ7".

With "6500" and "%2fSIZ7" are parameters.

But on server, I only receives value of "6500" and "SIZ17" and doesn't have special character "%2f".

I also try with another character, for example: "#"(encode before sending). It is working.

How do we send a query string with character "/"(%2f)?

答:
Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

Url encoded characters are listed at HTML URL Encoding Reference.

From above list %2F is the encoded value of forward slash(/).


问:
How to make a Hello World application without HTML tags?
I'm used to PHP and I wanted to make a totally empty asp.net page "Hello World" (in the source code) I.E. not "
Hello World
" I want to totally strip it all out (and possibly manipulate the headers) so the view source is Hello World.

This is because I am writing an asp.net throughput environment (basically a triangulation server, to facilitate network security) that effectively redirects so I want to have no outputs that I don't accurately control.

Incidentally this also includes response headers as well. Full Control basically.

This is what I have so far

答:
Dynamically, the browser do create "html", "body" etc... basic tags. It's the DOM, created by the browser from what it received.

To explore what you actually received from the server, you can inspect the source. Or better, use developer tools in your browser to look at the network part (to allow you to explore headers as well).

To manipulate what you send, you have to manipulate the context.Response object.

You can add all the headers you want from there.

from more info, see for example :

https://msdn.microsoft.com/en-us/library/system.web.httpresponse(v=vs.110).aspx

To add headers, see for example this question :

How to add Headers in HTTPContext Response in ASP.NET MVC 3?

example:

```<code>HttpContext.Current.Response.AppendHeader("Content-Length", contentLength);
</code>```

Body:
Dynamically, the browser do create "html", "body" etc... basic tags. It's the DOM, created by the browser from what it received.

To explore what you actually received from the server, you can inspect the source. Or better, use developer tools in your browser to look at the network part (to allow you to explore headers as well).

To manipulate what you send, you have to manipulate the context.Response object.

You can add all the headers you want from there.

from more info, see for example :

https://msdn.microsoft.com/en-us/library/system.web.httpresponse(v=vs.110).aspx

To add headers, see for example this question :

How to add Headers in HTTPContext Response in ASP.NET MVC 3?

example:

HttpContext.Current.Response.AppendHeader("Content-Length", contentLength);


问:
Laravel monthly count record
I want to create monthly statistics using Chartjs by Laravel.

```<code>$monthly_uploaded_product = DB::table('author_product')
         ->select(DB::raw('count(id) as total'), DB::raw('MONTH(created_at) as month'))
         ->groupBy('month')
         ->get();
</code>```

the result of query is:

```<code>[{"total":1,"month":10},{"total":17,"month":11}]
</code>```

the output of code should be like this to be represented in Javascript (Chartjs):

```<code>[0,0,0,0,0,0,0,0,0,1,17,0]
</code>```

I have wrote code to generate the array, but error Undefined offset: 1 :

```<code>$statistics_monthly_product = array();
foreach (range(1, 12) as $month) {
    foreach ($monthly_uploaded_product as $key) {
        if ($statistics_monthly_product[$month] == $key->month){
            $statistics_monthly_product[$month] = $key->total;
        }else{
            $statistics_monthly_product[$month] = 0;
        }
    }
}
</code>```

答:
You can try something like this:</p>

```<code>$year = [0,0,0,0,0,0,0,0,0,0,0,0];//initialize all months to 0

foreach($monthly_uploaded_product as $key)
   $year[$key->month-1] = $key->total;//update each month with the total value
}
</code>```

Title: Laravel monthly count record

Body:
I want to create monthly statistics using Chartjs by Laravel.

$monthly_uploaded_product = DB::table('author_product')
         ->select(DB::raw('count(id) as total'), DB::raw('MONTH(created_at) as month'))
         ->groupBy('month')
         ->get();

the result of query is:

[{"total":1,"month":10},{"total":17,"month":11}]

the output of code should be like this to be represented in Javascript (Chartjs):

[0,0,0,0,0,0,0,0,0,1,17,0]

I have wrote code to generate the array, but error Undefined offset: 1 :

$statistics_monthly_product = array();
foreach (range(1, 12) as $month) {
    foreach ($monthly_uploaded_product as $key) {
        if ($statistics_monthly_product[$month] == $key->month){
            $statistics_monthly_product[$month] = $key->total;
        }else{
            $statistics_monthly_product[$month] = 0;
        }
    }
}

Body:
You can try something like this:

$year = [0,0,0,0,0,0,0,0,0,0,0,0];//initialize all months to 0

foreach($monthly_uploaded_product as $key)
   $year[$key->month-1] = $key->total;//update each month with the total value
}


问:
Return matched value in any() list in string
I've the following script

```<code>#Tails every new line created in this file
for line in tailer.follow(open("my/path/chatlog.html")):
    #If the new line has the word "TURN" on it, continue
    if("TURN" in line):
        #IF any of the names in the list characterNames is in the new line, execute the function parseCharacter passing the matched "name"
        if any(name in line.lower() for name in characterNames):
            parseCharacter(charactersPath + name + ".xml")
</code>```

That "name" in the last line is what I need to match the matched name in the line. I tried to check the any() documentation but couldn't find a solution.

Thanks in advance.

答:
In

```<code>if any(name in line.lower() for name in characterNames):
    parseCharacter(charactersPath + name + ".xml")
</code>```

name is only valid in the brackets. Afterwards name is no longer defined.

You must go through the list manually:

```<code>for name in characterNames:
    if name in line.lower():
        parseCharacter(charactersPath + name + ".xml")
</code>```

Body:
I've the following script

#Tails every new line created in this file
for line in tailer.follow(open("my/path/chatlog.html")):
    #If the new line has the word "TURN" on it, continue
    if("TURN" in line):
        #IF any of the names in the list characterNames is in the new line, execute the function parseCharacter passing the matched "name"
        if any(name in line.lower() for name in characterNames):
            parseCharacter(charactersPath + name + ".xml")

That "name" in the last line is what I need to match the matched name in the line. I tried to check the any() documentation but couldn't find a solution.

Thanks in advance.

Body:
In

if any(name in line.lower() for name in characterNames):
    parseCharacter(charactersPath + name + ".xml")

name is only valid in the brackets. Afterwards name is no longer defined.

You must go through the list manually:

for name in characterNames:
    if name in line.lower():
        parseCharacter(charactersPath + name + ".xml")


问:
Combine two collections with predicate using Stream API
I have two collections of type Entity.

```<code>class Entity {
    long id;
    // other fields
}

Collection<Entity> first = ...
Collection<Entity> second = ...
</code>```

I need to combine them in a such way that all elements in first should be replaced by elements from second if their ids are equal.

So, e.g if first contains [{"id": 1}, {"id": 2}, {"id": 3}] and second contains [{"id": 3}, {"id": 4}, {"id": 5}]

the result should be like this: [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}] where {"id": 3} from second replaced {"id": 3} from first.

Is there a way how to implement it in a Java 8 way, using Stream API.

答:
You can use Map.merge(..) to chose the newer record. In the example bellow it is functionally equivalent to Map.put(..), but allows you to compare other Entity attributes, such as a creation timestamp or other.

```<code>// Extract Entity::getId as a Map key, and keep the Entity object as value
Map<Long, Entity> result = first.stream()
               .collect(Collectors.toMap(Entity::getId, Function.identity()));

// Merge second collection into the result map, overwriting existing records
second.forEach(entity -> result.merge(entity.getId(), entity, (oldVal, newVal) -> newVal));

// Print result
result.values().forEach(System.out::println);
</code>```

If you want to use Stream API only, then you can concat the two Collections into a single Stream using Stream.concat(...) and then write a custom Collector

```<code>Map<Long, Entity> result2 = Stream.concat(first.stream(), second.stream())
        .collect(LinkedHashMap::new, // the placeholder type
                (map, entity) -> map.merge(entity.getId(), entity, (oldVal, newVal) -> newVal),
                (map1, map2) -> {}); // parallel processing will reorder the concat stream so ignore
</code>```

Body:
I have two collections of type Entity.

class Entity {
    long id;
    // other fields
}

Collection<Entity> first = ...
Collection<Entity> second = ...

I need to combine them in a such way that all elements in first should be replaced by elements from second if their ids are equal.

So, e.g if first contains [{"id": 1}, {"id": 2}, {"id": 3}] and second contains [{"id": 3}, {"id": 4}, {"id": 5}]

the result should be like this: [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}] where {"id": 3} from second replaced {"id": 3} from first.

Is there a way how to implement it in a Java 8 way, using Stream API.

Body:
You can use Map.merge(..) to chose the newer record. In the example bellow it is functionally equivalent to Map.put(..), but allows you to compare other Entity attributes, such as a creation timestamp or other.

// Extract Entity::getId as a Map key, and keep the Entity object as value
Map<Long, Entity> result = first.stream()
               .collect(Collectors.toMap(Entity::getId, Function.identity()));

// Merge second collection into the result map, overwriting existing records
second.forEach(entity -> result.merge(entity.getId(), entity, (oldVal, newVal) -> newVal));

// Print result
result.values().forEach(System.out::println);

If you want to use Stream API only, then you can concat the two Collections into a single Stream using Stream.concat(...) and then write a custom Collector

Map<Long, Entity> result2 = Stream.concat(first.stream(), second.stream())
        .collect(LinkedHashMap::new, // the placeholder type
                (map, entity) -> map.merge(entity.getId(), entity, (oldVal, newVal) -> newVal),
                (map1, map2) -> {}); // parallel processing will reorder the concat stream so ignore


问:
Severity: 8192 Message: Methods with the same name as their class will not be constructors in a future version of PHP;
Severity: 8192

Message: Methods with the same name as their class will not be constructors in a future version of PHP; CI_Pagination has a deprecated constructor

Filename: libraries/Pagination.php

Line Number: 27

```<code>class CI_Pagination {

    var $base_url           = ''; // The page we are linking to
    var $total_rows         = ''; // Total number of items (database results)
    var $per_page           = 10; // Max number of items you want shown per page
    var $num_links          =  2; // Number of "digit" links to show before/after the currently viewed page
    var $cur_page           =  0; // The current page being viewed
    var $first_link         = '‹ First';
    var $next_link          = '>';
    var $prev_link          = '<';
    var $last_link          = 'Last ›';
    var $uri_segment        = 3;
    var $full_tag_open      = '';
    var $full_tag_close     = '';
    var $first_tag_open     = '';
    var $first_tag_close    = ' ';
    var $last_tag_open      = ' ';
    var $last_tag_close     = '';
    var $cur_tag_open       = ' ';
    var $cur_tag_close      = '';
    var $next_tag_open      = ' ';
    var $next_tag_close     = ' ';
    var $prev_tag_open      = ' ';
    var $prev_tag_close     = '';
    var $num_tag_open       = ' ';
    var $num_tag_close      = '';
    var $page_query_string  = FALSE;
    var $query_string_segment = 'per_page';
</code>```

答:
Loader.php 414 line, I have removed Ampersent.

```<code>$CI->dbutil =& new $class();
</code>```

to

```<code>$CI->dbutil = new $class();
</code>```

It works fine in php5.x.

Body:
Severity: 8192

Message: Methods with the same name as their class will not be constructors in a future version of PHP; CI_Pagination has a deprecated constructor

Filename: libraries/Pagination.php

Line Number: 27

class CI_Pagination {

    var $base_url           = ''; // The page we are linking to
    var $total_rows         = ''; // Total number of items (database results)
    var $per_page           = 10; // Max number of items you want shown per page
    var $num_links          =  2; // Number of "digit" links to show before/after the currently viewed page
    var $cur_page           =  0; // The current page being viewed
    var $first_link         = '‹ First';
    var $next_link          = '>';
    var $prev_link          = '<';
    var $last_link          = 'Last ›';
    var $uri_segment        = 3;
    var $full_tag_open      = '';
    var $full_tag_close     = '';
    var $first_tag_open     = '';
    var $first_tag_close    = ' ';
    var $last_tag_open      = ' ';
    var $last_tag_close     = '';
    var $cur_tag_open       = ' ';
    var $cur_tag_close      = '';
    var $next_tag_open      = ' ';
    var $next_tag_close     = ' ';
    var $prev_tag_open      = ' ';
    var $prev_tag_close     = '';
    var $num_tag_open       = ' ';
    var $num_tag_close      = '';
    var $page_query_string  = FALSE;
    var $query_string_segment = 'per_page';

Body:
Loader.php 414 line, I have removed Ampersent.

$CI->dbutil =& new $class();

to

$CI->dbutil = new $class();

It works fine in php5.x.


问:
Importing stylesheet in a server rendered react view - TypeError: style._getCss is not a function
I am building an isomorphic react-redux app on top of NodeJS. I am rendering my homePage from the server. However, my styles are not reflected in my rendered view. I would like to import stylesheets just how I do it on the client side. I tried this article and this too, but neither of them actually got me what I want to achieve.

Here are more details on the project.

.babelrc

```<code>{
 "presets": [ "es2015", "react", "stage-0"],
 "plugins": ["transform-decorators-legacy", ["transform-assets", {
            "extensions": ["scss"],
            "name": "[name].[ext]?[sha512:hash:base64:7]",
          }]]
 }
</code>```

webpack.config.js

```<code>const path = require('path');
module.exports = [
    {
      name: 'client',
      target: 'web',
      entry: './routes/client.jsx',
      output: {
        path: path.join(__dirname, 'assets'),
        filename: 'client.js',
        publicPath: '/assets/',
      },
      resolve: {
        extensions: ['.js', '.jsx']
      },
      devtool: 'source-map',
      module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules\/)/,
                use: [{ loader: 'babel-loader'}]
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'isomorphic-style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            importLoaders: 1,
                            localIdentName: '[name]__[local]___[hash:base64:5]',
                            sourceMap: true
                        }
                    },
                    { loader: 'sass-loader'}
                ]
            }
        ],
    },
}];
</code>```

server.js

```<code>import express from 'express'
import React from 'react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import MainStore from './views/store/MainStore'
import { StaticRouter } from 'react-router-dom';
import Routes from './routes/routes';
import Template from './views/templates/template';
import { Helmet } from 'react-helmet';
import { renderToString } from 'react-dom/server'
import ReactDOMServer from 'react-dom/server';
import ContextProvider from './routes/contextProvider'

const webpackDevMiddleware = require('webpack-dev-middleware')
const config = require('./webpack/webpack.development.config.js')
const webpack = require('webpack')
const app = express()
const port = 3000
const compiler = webpack(config);

let preloadedState = { shipper: {view: "from_server"} }

app.use('/assets', express.static('./assets'))
app.use(webpackDevMiddleware(compiler, {
   publicPath: "/assets/",
}));

app.use(handleRender);

function handleRender(req, res) {
   // Create a new Redux store instance
   const store = createStore(MainStore, preloadedState)
   const css = new Set(); // CSS for all rendered React components
   const context = { insertCss: (...styles) => styles.forEach(style =>
   css.add(style._getCss())) }

   const html = renderToString(
     <Provider store={store}>
        <StaticRouter context={context}>
            <ContextProvider context={context}>
            <Routes />
        </ContextProvider>
        </StaticRouter>
     </Provider>
  )
  const finalState = store.getState()
  const helmet = Helmet.renderStatic();
  const preloadedState = store.getState()
  res.send(renderFullPage(html, preloadedState));
 }

 function renderFullPage(html, finalState) {
    return `
      <!doctype html>
      <html>
         <head>
            <title>Redux Universal Example</title>
            <style type="text/css">${[...css].join('')}</style>
         </head>
         <body>
             <div id="root">${html}</div>
             <script>
                window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
             </script>
             <script src="./assets/client.js"></script>
         </body>
    </html>
    `
  }

app.listen(port)
</code>```

contextProvider.js

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Routes from './routes.jsx';

export default class ContextProvider extends Component {
   static childContextTypes = {
   insertCss: PropTypes.func,
}

 getChildContext() {
    return { ...this.props.context }
  }

 render() {
    const { children, ...props } = this.props
    return React.cloneElement(children, props)
  }
}
</code>```

I am importing it in my homePresenter as

```<code>import homePageStyle from './home.scss';
</code>```

and using it in my div in the same component as

```<code><div className="component">
</code>```

If I change this to

```<code><div className={homePageStyle.component}>
</code>```

I get an error on the browser

```<code>TypeError: style._getCss is not a function at server.js:52:84
</code>```

On the browser, I could see that the div has class name as 'component'; it;'s just it is not inheriting the styles.

Any suggestions on what I am missing here?

答:
TypeError: style._getCss is not a function at server.js:52:84

Most likely that server-side rendering is not configured properly. If you are not using webpack for compiling server-side bundle, of course, appropriate styles will not loaded, since isomorphic-style-loader had not processed files on server-side.

Check how application is started and ensure, that webpack had been applied for server-bundle and configuration was like this: https://webpack.js.org/configuration/node/

Also you can try ready isomorphic solution with frontend+backend bundling and includes css support, like resolve-app.

Body:
I am building an isomorphic react-redux app on top of NodeJS. I am rendering my homePage from the server. However, my styles are not reflected in my rendered view. I would like to import stylesheets just how I do it on the client side. I tried this article and this too, but neither of them actually got me what I want to achieve.

Here are more details on the project.

.babelrc

{
 "presets": [ "es2015", "react", "stage-0"],
 "plugins": ["transform-decorators-legacy", ["transform-assets", {
            "extensions": ["scss"],
            "name": "[name].[ext]?[sha512:hash:base64:7]",
          }]]
 }

webpack.config.js

const path = require('path');
module.exports = [
    {
      name: 'client',
      target: 'web',
      entry: './routes/client.jsx',
      output: {
        path: path.join(__dirname, 'assets'),
        filename: 'client.js',
        publicPath: '/assets/',
      },
      resolve: {
        extensions: ['.js', '.jsx']
      },
      devtool: 'source-map',
      module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules\/)/,
                use: [{ loader: 'babel-loader'}]
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'isomorphic-style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            importLoaders: 1,
                            localIdentName: '[name]__[local]___[hash:base64:5]',
                            sourceMap: true
                        }
                    },
                    { loader: 'sass-loader'}
                ]
            }
        ],
    },
}];

server.js

import express from 'express'
import React from 'react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import MainStore from './views/store/MainStore'
import { StaticRouter } from 'react-router-dom';
import Routes from './routes/routes';
import Template from './views/templates/template';
import { Helmet } from 'react-helmet';
import { renderToString } from 'react-dom/server'
import ReactDOMServer from 'react-dom/server';
import ContextProvider from './routes/contextProvider'

const webpackDevMiddleware = require('webpack-dev-middleware')
const config = require('./webpack/webpack.development.config.js')
const webpack = require('webpack')
const app = express()
const port = 3000
const compiler = webpack(config);

let preloadedState = { shipper: {view: "from_server"} }

app.use('/assets', express.static('./assets'))
app.use(webpackDevMiddleware(compiler, {
   publicPath: "/assets/",
}));

app.use(handleRender);

function handleRender(req, res) {
   // Create a new Redux store instance
   const store = createStore(MainStore, preloadedState)
   const css = new Set(); // CSS for all rendered React components
   const context = { insertCss: (...styles) => styles.forEach(style =>
   css.add(style._getCss())) }

   const html = renderToString(
     <Provider store={store}>
        <StaticRouter context={context}>
            <ContextProvider context={context}>
            <Routes />
        </ContextProvider>
        </StaticRouter>
     </Provider>
  )
  const finalState = store.getState()
  const helmet = Helmet.renderStatic();
  const preloadedState = store.getState()
  res.send(renderFullPage(html, preloadedState));
 }

 function renderFullPage(html, finalState) {
    return `
      <!doctype html>

            <title>Redux Universal Example</title>

${html}

    `
  }

app.listen(port)

contextProvider.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Routes from './routes.jsx';

export default class ContextProvider extends Component {
   static childContextTypes = {
   insertCss: PropTypes.func,
}

 getChildContext() {
    return { ...this.props.context }
  }

 render() {
    const { children, ...props } = this.props
    return React.cloneElement(children, props)
  }
}

I am importing it in my homePresenter as

import homePageStyle from './home.scss';

and using it in my div in the same component as

If I change this to

I get an error on the browser

TypeError: style._getCss is not a function at server.js:52:84

On the browser, I could see that the div has class name as 'component'; it;'s just it is not inheriting the styles.

Any suggestions on what I am missing here?


问:
Use ARKit detect phone moving trail and distance
I want log phone moving trail and distance .

since we can use ARKit measure real world objects.

```<code>func distance(from vector: SCNVector3) -> Float {
    let distanceX = self.x - vector.x
    let distanceY = self.y - vector.y
    let distanceZ = self.z - vector.z

    return sqrtf( (distanceX * distanceX) + (distanceY * distanceY) + (distanceZ * distanceZ))
}
</code>```

i can get distance between 2 SCNVector3 .

but i don't know how to log phone's current SCNVector3 in AR Scene

is it possible use ARKit measure phone move distance and moving trail ?

答:
When you create your ARSession,  the camera is located at 0,0,0 and it moves as you move the phone.  So if you want to know how far the phone is from its original position, just look at the translation portion of the camera transform matrix for the current frame:

```<code>frame.camera.transform
</code>```

the x y and z translation components are in m41, m42 and m43 respectively.  See the apple core animation docs for more on matrices if you are not familiar with the math.

Body:
I want log phone moving trail and distance .

since we can use ARKit measure real world objects.

func distance(from vector: SCNVector3) -> Float {
    let distanceX = self.x - vector.x
    let distanceY = self.y - vector.y
    let distanceZ = self.z - vector.z

    return sqrtf( (distanceX * distanceX) + (distanceY * distanceY) + (distanceZ * distanceZ))
}

i can get distance between 2 SCNVector3 .

but i don't know how to log phone's current SCNVector3 in AR Scene

is it possible use ARKit measure phone move distance and moving trail ?

Body:
When you create your ARSession,  the camera is located at 0,0,0 and it moves as you move the phone.  So if you want to know how far the phone is from its original position, just look at the translation portion of the camera transform matrix for the current frame:

frame.camera.transform

the x y and z translation components are in m41, m42 and m43 respectively.  See the apple core animation docs for more on matrices if you are not familiar with the math.


问:
Can't start debugserver on iPhone device Xcode 7.1 error
When I run the iOS device, Xcode is giving me a error...

Could not start debug server on "iPhone" when trying to launch "Monster"

This never happened before, why is this happening now? What is this? What do I do?

答:
Xcode 9:-

Just restarting the Xcode worked for me.


问:
Not getting keycode in keyup function
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

```<code>$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");
</code>```

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

```<code>function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}
</code>```

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

答:
Using inline events is complicating this. e is acting as this in the function. It would be easier to modify the code slightly to remove the inline event, and instead write it as:

```<code>$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text'>");

var textInput = document.getElementById('testTextbox');

textInput.addEventListener('keyup', function(e){
alert(e.keyCode+" : "+e.which);
});
</code>```

Or

```<code>$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text'>");

$('#testTextbox').on('keyup', function(e){
alert(e.keyCode+" : "+e.which);
});
</code>```

Here's a working example:

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text'>");

var textInput = document.getElementById('testTextbox');

textInput.addEventListener('keyup', function(e){
alert(e.keyCode+" : "+e.which);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="testDiv"></div></code>```

Title: Not getting keycode in keyup function

Body:
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

Body:
Using inline events is complicating this. e is acting as this in the function. It would be easier to modify the code slightly to remove the inline event, and instead write it as:

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text'>");

var textInput = document.getElementById('testTextbox');

textInput.addEventListener('keyup', function(e){
alert(e.keyCode+" : "+e.which);
});

Or

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text'>");

$('#testTextbox').on('keyup', function(e){
alert(e.keyCode+" : "+e.which);
});

Here's a working example:

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text'>");

var textInput = document.getElementById('testTextbox');

textInput.addEventListener('keyup', function(e){
alert(e.keyCode+" : "+e.which);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="testDiv"></div>


问:
CSS Different Class
I need change a color for this element

```<code><div class="box download">
    <div class="box-inner-block">
        <a href="" target="_blank" rel="noopener">Plugin Windows</a>
    </div>
</div>
</code>```

I call a from CSS with:

```<code>.download.box-inner-block a {
    color: white!important;
}
</code>```

But it does not work, why? I need this color only for the element in .box-inner-block inside .download.

答:
You are using the wrong selector, as .download.box-inner-block selects elements which has both download AND box-inner-block classes.

```<code><div class="download box-inner-block"/>
</code>```

To target nested elements, leave a space between the two class selectors. So the correct selector in your case is:

```<code>.download .box-inner-block a {
    color: white;
}
</code>```

In this case you can drop !important too.

Title: CSS Different Class

Body:
I need change a color for this element

        Plugin Windows

I call a from CSS with:

.download.box-inner-block a {
    color: white!important;
}

But it does not work, why? I need this color only for the element in .box-inner-block inside .download.

Body:
You are using the wrong selector, as .download.box-inner-block selects elements which has both download AND box-inner-block classes.

<div class="download box-inner-block"/>

To target nested elements, leave a space between the two class selectors. So the correct selector in your case is:

.download .box-inner-block a {
    color: white;
}

In this case you can drop !important too.


问:
Parameterising an import statement
I maintain a Python module that wraps and exposes the functionality of a DLL (also maintained by me).  The interfacing with the DLL uses ctypes.

This all works wonderfully thanks to the wonders of ctypes.  However, as I am by no means a Python expert, there are some parts of the Python that I feel are not idiomatic.

In particular I offer control of the DLL location to the user of the module. The DLL is loaded during the import of the module. I do this because I want to switch behaviour based on the capability of the DLL, and I need to load the DLL in order to query its behaviour.

By default, the DLL load relies of the DLL search path to locate the DLL. I would like to be able to allow the user to specify a full path to the DLL, should they wish to pick out a particular version.

At the moment I do this by using an environment variable but I recognise that this is a rather grotesque way to do it. What I'm looking for is a canonical or idiomatic Python way for the module importer to pass some information to the module which can be accessed at module import time.

答:
This code is taken from this page http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
It adds some paths to explores :</p>

```<code>ALLDIRS = ['usr/local/pythonenv/PYLONS-1/lib/python2.5/site-packages']

import sys
import site

# Remember original sys.path.
prev_sys_path = list(sys.path)

# Add each new site-packages directory.
for directory in ALLDIRS:
  site.addsitedir(directory)

# Reorder sys.path so new directories at the front.
new_sys_path = []
for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path
</code>```

ContentLicense: CC BY-SA 2.5

Title: Parameterising an import statement

Body:
This code is taken from this page http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
It adds some paths to explores :

ALLDIRS = ['usr/local/pythonenv/PYLONS-1/lib/python2.5/site-packages']

import sys
import site

# Remember original sys.path.
prev_sys_path = list(sys.path)

# Add each new site-packages directory.
for directory in ALLDIRS:
  site.addsitedir(directory)

# Reorder sys.path so new directories at the front.
new_sys_path = []
for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path


问:
React Dynamic Html Tags
Lets say i have this react component refering to a TextInput.
I want this component to be a

<input type="text"> and a <textarea> as well, but with no ifs on it, as being passed throw props, however my renderer got extra stuff on the element as follows:

```<code>   render() {
      return (
            <label>
            <strong>{this.props.name}</strong>
               <input type="text" ref={ component => { this.input = component; } } name={this.props.name} onChange={this.handleChange} value={this.state.value} />
            </label>
      )
   }
</code>```

My original idea was doing something like this

```<code>myInputProps = { type: (<input type="text"/>) }
</code>```

So in my element i woul render this simply as

```<code>  {this.props.type}
</code>```

However how could i pass all those extra stuff to the element such as the ref, name, onchange etc ? What would be a good aproach on this problem ? I could do some ifs and check what should i render depending on the component state etc, but i`m not sure that would be the best.

答:
I'd advocate using separate <TextInput> and <TextArea> components, but if you really need the flexiblity, use render props:

Using a render prop:

```<code>render() {
      const props = {
          ref: component => this.input = component,
          name: this.props.name,
          onChange: this.handleChange
      };
      return (
            <label>
            <strong>{this.props.name}</strong>
               { this.props.render(props) }
            </label>
      )
   }
</code>```

Then use it like:

```<code><TextInput name="foo" render={ props => <input ...props /> } />
</code>```

Title: React Dynamic Html Tags

Body:
Lets say i have this react component refering to a TextInput.
I want this component to be a

<input type="text"> and a <textarea> as well, but with no ifs on it, as being passed throw props, however my renderer got extra stuff on the element as follows:

   render() {
      return (

            {this.props.name}
               <input type="text" ref={ component => { this.input = component; } } name={this.props.name} onChange={this.handleChange} value={this.state.value} />

      )
   }

My original idea was doing something like this

myInputProps = { type: (<input type="text"/>) }

So in my element i woul render this simply as

  {this.props.type}

However how could i pass all those extra stuff to the element such as the ref, name, onchange etc ? What would be a good aproach on this problem ? I could do some ifs and check what should i render depending on the component state etc, but i`m not sure that would be the best.

Body:
I'd advocate using separate <TextInput> and <TextArea> components, but if you really need the flexiblity, use render props:

Using a render prop:

render() {
      const props = {
          ref: component => this.input = component,
          name: this.props.name,
          onChange: this.handleChange
      };
      return (
            <label>
            <strong>{this.props.name}</strong>
               { this.props.render(props) }
            </label>
      )
   }

Then use it like:

<TextInput name="foo" render={ props => <input ...props /> } />


问:
Which Unicode space has the same width as 1ch?
This are the Unicode spaces:

U+0020 SPACE

U+00A0 NO-BREAK SPACE

U+1680 OGHAM SPACE MARK

U+2000 EN QUAD

U+2001 EM QUAD

U+2002 EN SPACE

U+2003 EM SPACE

U+2004 THREE-PER-EM SPACE

U+2005 FOUR-PER-EM SPACE

U+2006 SIX-PER-EM SPACE

U+2007 FIGURE SPACE

U+2008 PUNCTUATION SPACE

U+2009 THIN SPACE

U+200A HAIR SPACE

U+202F NARROW NO-BREAK SPACE

U+205F MEDIUM MATHEMATICAL SPACE

U+3000 IDEOGRAPHIC SPACE

Which of them has the same width as 1ch in CSS?

答:
Unicode does not guarantee any space character to have the same advance width as U+0030 ZERO, which the ch unit is based on. It is entirely dependent on the typeface, and can be arbitrary.

The closest is U+2007 FIGURE SPACE, which is suggested to have the same width as a digit (not necessarily the digit zero), but again this depends entirely on the typeface having equal-width digits, which not all of them do.


答:
Just change the any to a loop over a list from a list comprehension:</p>

```<code>for name in [name for name in characterNames if name in line.lower()]:
    parseCharacter(charactersPath + name + ".xml")
</code>```

Title: Return matched value in any() list in string

Body:
Just change the any to a loop over a list from a list comprehension:

for name in [name for name in characterNames if name in line.lower()]:
    parseCharacter(charactersPath + name + ".xml")


问:
C# Need to access Microsoft Management Infrastructure namespace
All,
I am writing a Powershell cmdlet.  Got everything working for the cmdlet on my local machine.  Looked at what is needed to access remote machines and it seems I need a reference to Microsoft.Management.Infrastructure.dll in my project.  I have search my system to no avail.

So I hit Google.  I verified I am running Windows 7 SP1.  Downloaded and installed the Windows Management Framework (WMF) 4.0.  No luck.  Still no DLL.  I verified I met the minimum requirements.

I then found a Microsoft page that said version 5 required WMF 4.0 as a prerequisite to the install.  So I upgraded my .Net Framework to 4.6.2.  Then installed WMF 5.0.  Still no .DLL anywhere on my system.

Has anyone experienced this before?  Can anyone shed some light as to what I may be doing wrong?  I am using Visual Studio 2010.  Is this the cause of the problem?

I have continued to search the web and found articles that stated the Microsoft.Management.Infrastructure dll was part of the Windows 7 SDK.  Tried installing the SDK with no effect.  Still cannot get the dll load on my system.

Continuing to look for a fix.

答:
The easiest way I found to get this dll - and reference it automatically within my VS 2017 Project was via packet Manager console:

```<code>Install-Package Microsoft.Management.Infrastructure -Version 4.0.0
</code>```

As stated here on this Microsoft page: Nuget Gallery

No Need to install any SDK or so only to get this dll.

Body:
The easiest way I found to get this dll - and reference it automatically within my VS 2017 Project was via packet Manager console:

Install-Package Microsoft.Management.Infrastructure -Version 4.0.0

As stated here on this Microsoft page: Nuget Gallery

No Need to install any SDK or so only to get this dll.


问:
Neo4j Cypher return most consecutive "passes"

I am trying to return from a graph database the students with the most consecutive passes to a series of exams.

Below is my current code but not sure where I can take it from its current state to solve my issue.

```<code>MATCH (s:Student)-[r:TAKEN]->(e:Exam)
RETURN s.name, e.date,
  CASE
    WHEN r.score >= e.pass_mark THEN 1
  END as pass
ORDER BY e.date
</code>```

I would like a basic table which would show the student along with there most consecutive passes in a row.

For example:

```<code>| student   | pass/fail |
| joe       | pass      |
| matt      | pass      |
| joe       | fail      |
| matt      | pass      |
| joe       | pass      |
| matt      | pass      |
| joe       | pass      |
| matt      | fail      |
</code>```

And I would like the result from my query to display each student and their highest pass streak in a row.

```<code>| student  | passes in a row |
| joe      | 2               |
| matt     | 3               |
</code>```

I have been playing around with CASE but haven't been able to come up with a good solution, currently, it will just list all the students for each exam and have a 1 if they have passed it.

答:
This is a tricky one, and as far as I know can't be done with just Cypher, but there is a procedure in APOC Procedures that can help.

apoc.coll.split() takes a collection and a value to split around, and will yield records for each resulting sub-collection. Basically, we collect the ordered results per student, split around failures to get collections of consecutive passes, then get the max consecutive passes from the sizes of those collections:

```<code>MATCH (s:Student)-[r:TAKEN]->(e:Exam)
WITH s, r.score >= e.pass_mark as passed
ORDER BY e.date
WITH s, collect(passed) as resultsColl
CALL apoc.coll.split(resultsColl, false) YIELD value
WITH s, max(size(value)) as consecutivePasses
RETURN s.name as student, consecutivePasses
</code>```

Body:
I am trying to return from a graph database the students with the most consecutive passes to a series of exams.

Below is my current code but not sure where I can take it from its current state to solve my issue.

MATCH (s:Student)-[r:TAKEN]->(e:Exam)
RETURN s.name, e.date,
  CASE
    WHEN r.score >= e.pass_mark THEN 1
  END as pass
ORDER BY e.date

I would like a basic table which would show the student along with there most consecutive passes in a row.

For example:

| student   | pass/fail |
| joe       | pass      |
| matt      | pass      |
| joe       | fail      |
| matt      | pass      |
| joe       | pass      |
| matt      | pass      |
| joe       | pass      |
| matt      | fail      |

And I would like the result from my query to display each student and their highest pass streak in a row.

| student  | passes in a row |
| joe      | 2               |
| matt     | 3               |

I have been playing around with CASE but haven't been able to come up with a good solution, currently, it will just list all the students for each exam and have a 1 if they have passed it.

Body:
This is a tricky one, and as far as I know can't be done with just Cypher, but there is a procedure in APOC Procedures that can help.

apoc.coll.split() takes a collection and a value to split around, and will yield records for each resulting sub-collection. Basically, we collect the ordered results per student, split around failures to get collections of consecutive passes, then get the max consecutive passes from the sizes of those collections:

MATCH (s:Student)-[r:TAKEN]->(e:Exam)
WITH s, r.score >= e.pass_mark as passed
ORDER BY e.date
WITH s, collect(passed) as resultsColl
CALL apoc.coll.split(resultsColl, false) YIELD value
WITH s, max(size(value)) as consecutivePasses
RETURN s.name as student, consecutivePasses


问:
Reading data from _transaction_state topic in Kafka 0.11.0.1
I want to read meta data for transaction (which is supported in Kafka 0.11.0.1) so that I can figure out that whether the transaction for a particular transactional ID has been committed or not. Currently I am getting the key and value from _transactional_state topic but it is in some encoded format.
Below are some same key/value I received when I polled __transaction_state topic:
key =    10000000mmm, value =         �   �����+'���������)

答: You can look to source code of TransactionLogMessageParser class inside kafka/tools/DumpLogSegments.scala file as an example.  It uses readTxnRecordValue function from TransactionLog class.  The first argument for this function could be retrieved via readTxnRecordKey function of the same class.


问:
Multiple size/versions of an image in SVG
Is it possible to embed multiple images in SVG file to achieve similar effect like with ICO file?

In case of ICO, the file contains several versions/sizes of an image, so
the smaller ones can omit some details or have use ratios which may render the scaled down image more readable.

Edit

I am not interested in any particular application, and I intentionally do not take into account for what ICO format was intended (used only as an example).

For further discussion lets use Applications-database.svg, witch contains four different images, as an example:

 (original size/ration).

 (scaled).

The picture on the right contains less details, and has different proportions, but is much more readable when scaled down:

However the Applications-database.svg does not switch between individual pictures automatically and only the biggest and the most detail image is normally visible.

So the question is: Can I with CSS/SVG hide/show different image (maybe <symbol>) when the whole image is resized (i.e. show symbol-1 if width > 50 else show symbol-2)?

答:
You seem to misunderstand what the whole point of an SVG is.

SVG defines the image in terms of shape definitions.  That means it should be able to be drawn at any size and give the best result*.

It is not limited to certain sizes like an ICO file or a PNG, which are pixel based.

* As long as the SVG doesn't specify a fixed size in its header.

Update based on question edit

You can use @media queries in your SVG to style your SVG differently based on the final size.

ellipse {
  fill: lightsteelblue;
  stroke: black;
  stroke-width: 5;
}

@media all and (max-width: 400px)
{
  ellipse {
    stroke-width: 10;
  }
}

@media all and (max-width: 100px)
{
  ellipse {
    fill: white;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 100 100">
  <ellipse cx="50" cy="75" rx="45" ry="20"/>
  <ellipse cx="50" cy="50" rx="45" ry="20"/>
  <ellipse cx="50" cy="25" rx="45" ry="20"/>
</svg></code>```

Open this CodePen and try resizing the browser window:

https://codepen.io/PaulLeBeau/pen/WdEqye

Be aware that media queries should be supported by all/most browsers, but they may not be supported by other SVG renderers or editors.

Body:
You seem to misunderstand what the whole point of an SVG is.

SVG defines the image in terms of shape definitions.  That means it should be able to be drawn at any size and give the best result*.

It is not limited to certain sizes like an ICO file or a PNG, which are pixel based.

* As long as the SVG doesn't specify a fixed size in its header.

Update based on question edit

You can use @media queries in your SVG to style your SVG differently based on the final size.

ellipse {
  fill: lightsteelblue;
  stroke: black;
  stroke-width: 5;
}

@media all and (max-width: 400px)
{
  ellipse {
    stroke-width: 10;
  }
}

@media all and (max-width: 100px)
{
  ellipse {
    fill: white;
  }
}

<svg viewBox="0 0 100 100">
  <ellipse cx="50" cy="75" rx="45" ry="20"/>
  <ellipse cx="50" cy="50" rx="45" ry="20"/>
  <ellipse cx="50" cy="25" rx="45" ry="20"/>
</svg>

Open this CodePen and try resizing the browser window:

https://codepen.io/PaulLeBeau/pen/WdEqye

Be aware that media queries should be supported by all/most browsers, but they may not be supported by other SVG renderers or editors.


问:
Flash cs5 - how to change frame rate of only movie clip?
I am building a small flash application.
In my application I've inserted an fla video.
the flv video's length when I open it in vlc player is 16 seconds (after I edit the speed of the video in an external program and then converted it back to fla).
When I open it in flash cs 5, the video's length is back to 90 seconds.

I guess it's got something to do with the frame rate of my flash project.
I'd like to be able to change the frame rate of only the movie clip containing that video, and not of the entire stage. How is that possible?

Thank you,

答: FLV videos should not be affected by the frame rate you set for your movie.  Perhaps your library still contains the old version of the FLV? Just open the properties panel for your FLV and update the asset.</p>


问:
Visual Studio 2013 .aspx intellisense not working
In my .aspx page I am trying to write some code but it seems my intellisense is not working. (Visual Studio 2013)

I tried deleting my v12.suo file but that did not resolve anything. I also tried web essentials and looking around my options but I couldn't get it to work.

So I tried:

Deleting v12.suo file

Cleaning/Rebuilding solution

Web Essentials

Different options in Tools -> options

Anyone have an idea of how to fix this?

答: Make sure Tools -> Options -> Text Editor -> C# -> IntelliSense -> "Show completion list after a character is typed" is checked.</p>


问:
Convert Python date to Unix timestamp
I would like to convert a Python date object to a Unix timestamp.

I already added a time object, so it would be that specific date at midnight, but I don't know how to continue from there.

```<code>d = date(2014, 10, 27)
t = time(0, 0, 0)
dt = datetime.combine(d, t)

#How to convert this to Unix timestamp?
</code>```

I am using Python 2.7

答:
```<code>>>> import datetime
>>> d = datetime.date(2014, 10, 27)
>>> int("{:%s}".format(d))
1414364400
>>> datetime.datetime.fromtimestamp(1414364400)
datetime.datetime(2014, 10, 27, 0, 0)
</code>```

Please note that %s formatting of times is not supported on Windows.

Title: Convert Python date to Unix timestamp

Body:
I would like to convert a Python date object to a Unix timestamp.

I already added a time object, so it would be that specific date at midnight, but I don't know how to continue from there.

d = date(2014, 10, 27)
t = time(0, 0, 0)
dt = datetime.combine(d, t)

#How to convert this to Unix timestamp?

I am using Python 2.7

Body:
>>> import datetime
>>> d = datetime.date(2014, 10, 27)
>>> int("{:%s}".format(d))
1414364400
>>> datetime.datetime.fromtimestamp(1414364400)
datetime.datetime(2014, 10, 27, 0, 0)

Please note that %s formatting of times is not supported on Windows.


问:
How to determine if a specific class in html exists, with Html Agilty Pack in c#
I want to know if a specific product by numbers exists in a web page. That page has a search bar, I determined that html class "product-thumb" appears only when search result is TRUE. So i wanna use that class as an example of TRUE and FALSE in IF statement. I'm using html agilty pack to do this task, here is a code what I already have but it doesn't work, always returns FALSE. I googled a lot, can't find proper solution yet, and that's why I left not working code here. I have string "url" like this because I will list many numbers like this to check for each product, preperations for a big loop, but still can't make this test code work. Thanks in advance.</p>

```<code>        string url = "90551";
        HtmlWeb web = new HtmlWeb();
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        string s = "http://examplewebpage" + url;
        doc = web.Load(s);
        System.Threading.Thread.Sleep(5000);

        if (doc.DocumentNode.HasClass("//*[@class=\"product-thumb") == true)
        {
            webBrowser1.DocumentText = url + " Yes";
        }
        else
            webBrowser1.DocumentText = url + " No";
</code>```

答:
You can just search for any item containing 'product-thumb' class</p>

```<code>var containsProductThumb = doc.DocumentNode
    .Descendants()
    .Any( d =>
        d.Attributes.Contains("class")
        &&
        d.Attributes["class"].Value.Contains("product-thumb")
    );
if (containsProductThumb)
    webBrowser1.DocumentText = url + " Yes";
else
    webBrowser1.DocumentText = url + " No";
</code>```

Body:
I want to know if a specific product by numbers exists in a web page. That page has a search bar, I determined that html class "product-thumb" appears only when search result is TRUE. So i wanna use that class as an example of TRUE and FALSE in IF statement. I'm using html agilty pack to do this task, here is a code what I already have but it doesn't work, always returns FALSE. I googled a lot, can't find proper solution yet, and that's why I left not working code here. I have string "url" like this because I will list many numbers like this to check for each product, preperations for a big loop, but still can't make this test code work. Thanks in advance.

        string url = "90551";
        HtmlWeb web = new HtmlWeb();
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        string s = "http://examplewebpage" + url;
        doc = web.Load(s);
        System.Threading.Thread.Sleep(5000);

        if (doc.DocumentNode.HasClass("//*[@class=\"product-thumb") == true)
        {
            webBrowser1.DocumentText = url + " Yes";
        }
        else
            webBrowser1.DocumentText = url + " No";

Body:
You can just search for any item containing 'product-thumb' class

var containsProductThumb = doc.DocumentNode
    .Descendants()
    .Any( d =>
        d.Attributes.Contains("class")
        &&
        d.Attributes["class"].Value.Contains("product-thumb")
    );
if (containsProductThumb)
    webBrowser1.DocumentText = url + " Yes";
else
    webBrowser1.DocumentText = url + " No";


问:
badge_label_helper.rb is failing to load in resque jobs
We are trying to upgrade rails from 4.2 to 5.1.4 along with resque gem.
But we got below results on the same.

File : /lib/tasks/resque.rake
    require 'resque/tasks'
    require 'resque-scheduler'
    require 'resque/scheduler/server'
    require 'resque/scheduler/tasks'
    task "resque:setup" => :environment do
        ENV['QUEUE'] = '*'
        ENV['COUNT'] = '5'
        require 'resque'
        require 'resque-scheduler'
    end

```<code>*Error: rake aborted!
LoadError: No such file to load -- badge_label_helper.rb*
</code>```

_Trace : QUEUE= rake environment resque:work --trace
** Invoke environment (first_time)
** Execute environment
** Invoke resque:work (first_time)
** Invoke resque:preload (first_time)
** Invoke resque:setup (first_time)
** Invoke environment
** Execute resque:setup
** Execute resque:preload
rake aborted!
LoadError: No such file to load -- badge_label_helper.rb
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:in load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:inblock in load_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:661:in new_constants_in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:475:inload_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:374:in block in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inblock in load_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:12:in block in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/concurrency/share_lock.rb:149:inexclusive'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:11:in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inload_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:357:in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:335:independ_on'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:251:in require_dependency'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:476:inblock (2 levels) in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:inblock in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:ineager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:354:in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:ineach'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:in block (2 levels) in <top (required)>'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:251:inblock in execute'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:251:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:251:inexecute'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:195:in block in invoke_with_call_chain'
/Users/dinilv/.rvm/rubies/ruby-2.4.2/lib/ruby/2.4.0/monitor.rb:214:inmon_synchronize'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:188:in invoke_with_call_chain'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:217:inblock in invoke_prerequisites'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:215:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:215:ininvoke_prerequisites'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:194:in block in invoke_with_call_chain'
/Users/dinilv/.rvm/rubies/ruby-2.4.2/lib/ruby/2.4.0/monitor.rb:214:inmon_synchronize'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:188:in invoke_with_call_chain'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:181:ininvoke'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:153:in invoke_task'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:109:inblock (2 levels) in top_level'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:109:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:109:inblock in top_level'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:118:in run_with_threads'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:103:intop_level'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:81:in block in run'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:179:instandard_exception_handling'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:78:in run'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/exe/rake:27:in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/rake:23:in load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/rake:23:in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in eval'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in'
Tasks: TOP => resque:work => resque:preload_
Command :QUEUE=* rake environment resque:work
"
_rake aborted!
LoadError: No such file to load -- badge_label_helper.rb
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:in load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:inblock in load_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:661:in new_constants_in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:475:inload_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:374:in block in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inblock in load_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:12:in block in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/concurrency/share_lock.rb:149:inexclusive'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:11:in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inload_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:357:in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:335:independ_on'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:251:in require_dependency'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:476:inblock (2 levels) in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:inblock in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:ineager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:354:in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:ineach'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:in block (2 levels) in <top (required)>'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/exe/rake:27:in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in eval'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in'
Tasks: TOP => resque:work => resque:preload
(See full trace by running task with --trace)_
"*

答:
I encountered exactly the same strange issue. It was working before, but when I reorganised my Gemfile it broke. After a lot of trying I found the solution:
The resque-web may not be put into a group.
Before:

```<code>group :production do
  gem 'resque-web', require: 'resque_web' # This will break
  gem 'resque-pool'
end
</code>```

After:

```<code>gem 'resque-web', require: 'resque_web' # Now it works
group :production do
  gem 'resque-pool'
end
</code>```

Hope i could help.

Body:
We are trying to upgrade rails from 4.2 to 5.1.4 along with resque gem.
But we got below results on the same.

File : /lib/tasks/resque.rake
    require 'resque/tasks'
    require 'resque-scheduler'
    require 'resque/scheduler/server'
    require 'resque/scheduler/tasks'
    task "resque:setup" => :environment do
        ENV['QUEUE'] = '*'
        ENV['COUNT'] = '5'
        require 'resque'
        require 'resque-scheduler'
    end

*Error: rake aborted!
LoadError: No such file to load -- badge_label_helper.rb*

_Trace : QUEUE= rake environment resque:work --trace
** Invoke environment (first_time)
** Execute environment
** Invoke resque:work (first_time)
** Invoke resque:preload (first_time)
** Invoke resque:setup (first_time)
** Invoke environment
** Execute resque:setup
** Execute resque:preload
rake aborted!
LoadError: No such file to load -- badge_label_helper.rb
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:in load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:inblock in load_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:661:in new_constants_in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:475:inload_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:374:in block in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inblock in load_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:12:in block in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/concurrency/share_lock.rb:149:inexclusive'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:11:in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inload_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:357:in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:335:independ_on'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:251:in require_dependency'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:476:inblock (2 levels) in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:inblock in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:ineager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:354:in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:ineach'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:in block (2 levels) in <top (required)>'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:251:inblock in execute'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:251:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:251:inexecute'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:195:in block in invoke_with_call_chain'
/Users/dinilv/.rvm/rubies/ruby-2.4.2/lib/ruby/2.4.0/monitor.rb:214:inmon_synchronize'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:188:in invoke_with_call_chain'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:217:inblock in invoke_prerequisites'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:215:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:215:ininvoke_prerequisites'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:194:in block in invoke_with_call_chain'
/Users/dinilv/.rvm/rubies/ruby-2.4.2/lib/ruby/2.4.0/monitor.rb:214:inmon_synchronize'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:188:in invoke_with_call_chain'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/task.rb:181:ininvoke'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:153:in invoke_task'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:109:inblock (2 levels) in top_level'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:109:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:109:inblock in top_level'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:118:in run_with_threads'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:103:intop_level'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:81:in block in run'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:179:instandard_exception_handling'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/lib/rake/application.rb:78:in run'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/exe/rake:27:in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/rake:23:in load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/rake:23:in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in eval'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in'
Tasks: TOP => resque:work => resque:preload_
Command :QUEUE=* rake environment resque:work
"
_rake aborted!
LoadError: No such file to load -- badge_label_helper.rb
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:in load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:476:inblock in load_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:661:in new_constants_in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:475:inload_file'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:374:in block in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inblock in load_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:12:in block in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/concurrency/share_lock.rb:149:inexclusive'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:11:in loading'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:36:inload_interlock'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:357:in require_or_load'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:335:independ_on'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:251:in require_dependency'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:476:inblock (2 levels) in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:475:inblock in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:in each'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:473:ineager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/railties-5.1.4/lib/rails/engine.rb:354:in eager_load!'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:ineach'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/resque-1.27.4/lib/resque/tasks.rb:45:in block (2 levels) in <top (required)>'
/Users/dinilv/.rvm/gems/ruby-2.4.2/gems/rake-12.1.0/exe/rake:27:in'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in eval'
/Users/dinilv/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in'
Tasks: TOP => resque:work => resque:preload
(See full trace by running task with --trace)_
"*

Body:
I encountered exactly the same strange issue. It was working before, but when I reorganised my Gemfile it broke. After a lot of trying I found the solution:
The resque-web may not be put into a group.
Before:

group :production do
  gem 'resque-web', require: 'resque_web' # This will break
  gem 'resque-pool'
end

After:

gem 'resque-web', require: 'resque_web' # Now it works
group :production do
  gem 'resque-pool'
end

Hope i could help.