问:
split display legend in highcharts
I have combination chart with highcharts, there are spline, pie and stacked. Is it possible to split legend or use vertical and horizontal layout together?

current layout legend is horizontal

*series 1 *series 2 *series 3 *series 4 *series 5 *series 6 *series 7 *series 8

I want the legend display to be

*series 1 *series 2

*series 3 *series 4 *series 5

*series 6 *series 7 *series 8

is it possible?

thanx

答:
It cannot be done just by using Highcharts constructor options. You can achieve that kind of look and behavior by wrapping some core functions:

```<code>(function(H) {
  var merge = H.merge;

  H.wrap(H.Legend.prototype, 'getAllItems', function() {
    var allItems = [],
      chart = this.chart,
      options = this.options,
      legendID = options.legendID;

    H.each(chart.series, function(series) {
      if (series) {
        var seriesOptions = series.options;

        // use points or series for the legend item depending on legendType
        if (!isNaN(legendID) && (seriesOptions.legendID === legendID)) {
          allItems = allItems.concat(
            series.legendItems ||
            (seriesOptions.legendType === 'point' ?
              series.data :
              series)
          );
        }
      }
    });

    return allItems;
  });

  H.wrap(H.Chart.prototype, 'render', function(p) {
    var chart = this,
      chartOptions = chart.options;

    chart.firstLegend = new H.Legend(chart, merge(chartOptions.legend, chartOptions.firstLegend, {
      legendID: 0
    }));

    chart.secondLegend = new H.Legend(chart, merge(chartOptions.legend, chartOptions.secondLegend, {
      legendID: 1
    }));

    p.call(this);
  });

  H.wrap(H.Chart.prototype, 'redraw', function(p, r, a) {
    var chart = this;

    p.call(chart, r, a);

    chart.firstLegend.render();
    chart.secondLegend.render();
  });

  H.wrap(H.Legend.prototype, 'positionItem', function(p, item) {
    p.call(this, item);
  });
})(Highcharts);
</code>```

Highcharts options:

```<code>Highcharts.chart('container', {

  chart: {
    marginRight: 350 // create some space for the legend
  },

  legend: {
    verticalAlign: 'middle',
    width: 300,
    align: 'right'
  },
  firstLegend: {
    y: -25
  },
  secondLegend: {
    y: 25
  },

  series: [{
    data: [5, 6, 7],
    legendID: 0,
  }, {
    data: [2, 3, 1],
    legendID: 0,
  },
  (...)
  {
    data: [1, 8, 2],
    legendID: 1
  }, {
    data: [3, 2],
    legendID: 1
  },
  (...)
  ]
});
</code>```

Live demo: http://jsfiddle.net/kkulig/r70fwasr/

This code can be optimized so that it works for more than 2 legends.

Title: split display legend in highcharts

Body:
It cannot be done just by using Highcharts constructor options. You can achieve that kind of look and behavior by wrapping some core functions:

(function(H) {
  var merge = H.merge;

  H.wrap(H.Legend.prototype, 'getAllItems', function() {
    var allItems = [],
      chart = this.chart,
      options = this.options,
      legendID = options.legendID;

    H.each(chart.series, function(series) {
      if (series) {
        var seriesOptions = series.options;

        // use points or series for the legend item depending on legendType
        if (!isNaN(legendID) && (seriesOptions.legendID === legendID)) {
          allItems = allItems.concat(
            series.legendItems ||
            (seriesOptions.legendType === 'point' ?
              series.data :
              series)
          );
        }
      }
    });

    return allItems;
  });

  H.wrap(H.Chart.prototype, 'render', function(p) {
    var chart = this,
      chartOptions = chart.options;

    chart.firstLegend = new H.Legend(chart, merge(chartOptions.legend, chartOptions.firstLegend, {
      legendID: 0
    }));

    chart.secondLegend = new H.Legend(chart, merge(chartOptions.legend, chartOptions.secondLegend, {
      legendID: 1
    }));

    p.call(this);
  });

  H.wrap(H.Chart.prototype, 'redraw', function(p, r, a) {
    var chart = this;

    p.call(chart, r, a);

    chart.firstLegend.render();
    chart.secondLegend.render();
  });

  H.wrap(H.Legend.prototype, 'positionItem', function(p, item) {
    p.call(this, item);
  });
})(Highcharts);

Highcharts options:

Highcharts.chart('container', {

  chart: {
    marginRight: 350 // create some space for the legend
  },

  legend: {
    verticalAlign: 'middle',
    width: 300,
    align: 'right'
  },
  firstLegend: {
    y: -25
  },
  secondLegend: {
    y: 25
  },

  series: [{
    data: [5, 6, 7],
    legendID: 0,
  }, {
    data: [2, 3, 1],
    legendID: 0,
  },
  (...)
  {
    data: [1, 8, 2],
    legendID: 1
  }, {
    data: [3, 2],
    legendID: 1
  },
  (...)
  ]
});

Live demo: http://jsfiddle.net/kkulig/r70fwasr/

This code can be optimized so that it works for more than 2 legends.


来源: stackexchange

问:
#Name error in excel sheet
I have a csv file which is filled automatically through a java programm. I have a line which have the following text when I open the text in Notepad++:

```<code>-LRB- from the PMI Practice Standard for Work Breakdown Structures , Oct 2000 -RRB- '',"no","f1_FRAG:1.0","f2_specialChar:1.0","f3:15.0","f4:7.0","f5:0.0","f6:2.0","f7:0.0","f8:3.7612001156935624","f9:7.0","f10:1.0","f11:1.0","f12:0.0","f13:0.0","f14:0.0,"f15_ROOT:1.0","f16_specialChar:1.0","f17_NOTHING:1.0","f18_IN:1.0""
</code>```

But when I open it in excel sheet, there are two problems:

1) When I click on the cell, I see #Name error and any click on the page causes an error. I even can't close the excel window normally. I also sometimes see something like =A228 or =B223 when I click on the cell. It sounds to be read as a formula, but it actually isn't.

2) The row is not shown completely. I can't see this part when I open the file using office excel:

```<code>",f15_ROOT:1.0","f16_specialChar:1.0","f17_NOTHING:1.0","f18_IN:1.0"".
</code>```

Any help is appreciated.

答:
Since the row starts with a - (minus sign), Excel is expecting a formula.

Manually, you could either:

add an ' (apostrophe) at the beginning of the line (which tells Excel that the cell contains text), or

Format the cell as text : Right-click the cell → Format Cells → Number tab → Text

Ideally, to prevent this issue in the future, the Java program which generates the .CSV file should be changed to enclose text fields with " double quotation marks.

Oddly, that is the only field in your example that isn't surrounded by double quotes.

```<code>"-LRB- from the PMI Practice Standard for Work Breakdown Structures , Oct 2000 -RRB- ''","no","f1_FRAG:1.0","f2_specialChar:1.0","f3:15.0","f4:7.0","f5:0.0","f6:2.0","f7:0.0","f8:3.7612001156935624","f9:7.0","f10:1.0","f11:1.0","f12:0.0","f13:0.0","f14:0.0,"f15_ROOT:1.0","f16_specialChar:1.0","f17_NOTHING:1.0","f18_IN:1.0""
</code>```

At the minimum, double-quotes should the used around any fields that begin with a symbol or contain a comma (like above).

```<code>1997,Ford,E350,"Super, luxurious truck"
</code>```

The double-quotes will be recognized and removed by most apps that open CSV's.

Any field may be quoted (that is, enclosed within double-quote characters). Some fields must be quoted, as specified in following
rules.

"1997","Ford","E350"

Fields with embedded commas or double-quote characters must be quoted.

1997,Ford,E350,"Super, luxurious truck"

Each of the embedded double-quote characters must be represented by a pair of double-quote characters.

1997,Ford,E350,"Super, ""luxurious"" truck"

.

More about Comma Separated Value files:

Wikipedia: CSV Files - Basic Rules

RFC 2046 Standard

RFC4180 Standard

.

Surprisingly, I can't find any reference document from Microsoft that mentions starting text cells with an apostrophe. (I guess it's a secret, so if anyone asks, you didn't hear it from me.)  :-)

The reason you are getting the #NAME error specifically is because Excel figures you're trying to enter a formula (because of the minus sign) but it doesn't recognize the Name of the function ("LRB")

ContentLicense: CC BY-SA 3.0

Title: #Name error in excel sheet

Body:
I have a csv file which is filled automatically through a java programm. I have a line which have the following text when I open the text in Notepad++:

-LRB- from the PMI Practice Standard for Work Breakdown Structures , Oct 2000 -RRB- '',"no","f1_FRAG:1.0","f2_specialChar:1.0","f3:15.0","f4:7.0","f5:0.0","f6:2.0","f7:0.0","f8:3.7612001156935624","f9:7.0","f10:1.0","f11:1.0","f12:0.0","f13:0.0","f14:0.0,"f15_ROOT:1.0","f16_specialChar:1.0","f17_NOTHING:1.0","f18_IN:1.0""

But when I open it in excel sheet, there are two problems:

1) When I click on the cell, I see #Name error and any click on the page causes an error. I even can't close the excel window normally. I also sometimes see something like =A228 or =B223 when I click on the cell. It sounds to be read as a formula, but it actually isn't.

2) The row is not shown completely. I can't see this part when I open the file using office excel:

",f15_ROOT:1.0","f16_specialChar:1.0","f17_NOTHING:1.0","f18_IN:1.0"".

Any help is appreciated.

Body:
Since the row starts with a - (minus sign), Excel is expecting a formula.

Manually, you could either:

add an ' (apostrophe) at the beginning of the line (which tells Excel that the cell contains text), or

Format the cell as text : Right-click the cell → Format Cells → Number tab → Text

Ideally, to prevent this issue in the future, the Java program which generates the .CSV file should be changed to enclose text fields with " double quotation marks.

Oddly, that is the only field in your example that isn't surrounded by double quotes.

"-LRB- from the PMI Practice Standard for Work Breakdown Structures , Oct 2000 -RRB- ''","no","f1_FRAG:1.0","f2_specialChar:1.0","f3:15.0","f4:7.0","f5:0.0","f6:2.0","f7:0.0","f8:3.7612001156935624","f9:7.0","f10:1.0","f11:1.0","f12:0.0","f13:0.0","f14:0.0,"f15_ROOT:1.0","f16_specialChar:1.0","f17_NOTHING:1.0","f18_IN:1.0""

At the minimum, double-quotes should the used around any fields that begin with a symbol or contain a comma (like above).

1997,Ford,E350,"Super, luxurious truck"

The double-quotes will be recognized and removed by most apps that open CSV's.

Any field may be quoted (that is, enclosed within double-quote characters). Some fields must be quoted, as specified in following
rules.

"1997","Ford","E350"

Fields with embedded commas or double-quote characters must be quoted.

1997,Ford,E350,"Super, luxurious truck"

Each of the embedded double-quote characters must be represented by a pair of double-quote characters.

1997,Ford,E350,"Super, ""luxurious"" truck"

.

More about Comma Separated Value files:

Wikipedia: CSV Files - Basic Rules

RFC 2046 Standard

RFC4180 Standard

.

Surprisingly, I can't find any reference document from Microsoft that mentions starting text cells with an apostrophe. (I guess it's a secret, so if anyone asks, you didn't hear it from me.)  :-)

The reason you are getting the #NAME error specifically is because Excel figures you're trying to enter a formula (because of the minus sign) but it doesn't recognize the Name of the function ("LRB")


问:
Issue with jackson deserializing, sets all variables to null
I'm trying, and failing to deserialize in jackson 2.9.2, i am trying to make a game, for a uni project, where i am working on a save function, where i can save my Player class, and serialize it, but when i try to deserialize it, and make a new player from it, it sets all the variables to null, this is my method:

```<code>public void LoadSaveString() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    //module.addDeserializer(SaveFile.class, new SaveDeserializer());
    mapper.registerModule(module);

    String filePath = "files/SaveFile.json";
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    testfile = reader.readLine();

    System.out.println("Stringen testfilen bliver printet: " + testfile);
    Player player1 = (Player) mapper.readValue(testfile, Player.class);
    System.out.println("Test 2: " + player1.toString());

}
</code>```

and the output i get is:

Stringen testfilen bliver printet: {"player":{"hp":100,"air":97,"inventory":[],"hasCalledHelp":false,"wonGame":false,"playerName":"Mads","awesomePoints":0,"totalTimePlayed":3,"terminateThreads":false,"stopThreadOxygen":false,"stopThreadHP":false,"name":"Mads"}}

Test 2: Player{hp=0, air=0, inventory=null, hasCalledHelp=false, wonGame=false, awesomePoints=0, totalTimePlayed=0, terminateThreads=false, stopThreadOxygen=false, stopThreadHP=false}

And i have set my player class to ignore unknown properties, so i only, get and set, the things that are important for the playerclass

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
</code>```

and the properties in my Player class:

```<code>public class Player {
private int hp;
private int air;
private ArrayList<Item> inventory;
private boolean hasCalledHelp = false;
private boolean wonGame = false;
public String playerName = "Mads"; // Non-negotiable
public int awesomePoints = 0;
public int totalTimePlayed = 0;
</code>```

Edit:

The content in the file SaveFile.json:

```<code>{
    "player": {
        "hp": 100,
        "air": 97,
        "inventory": [],
        "hasCalledHelp": false,
        "wonGame": false,
        "playerName": "Mads",
        "awesomePoints": 0,
        "totalTimePlayed": 3,
        "terminateThreads": false,
        "stopThreadOxygen": false,
        "stopThreadHP": false,
        "name": "Mads"
    }
}
</code>```

答:
The JSON of your file is an Object that has an attribute player. It's not a Player

```<code>{
    "player": { "hp":100, ... }
}
</code>```

Something like:

```<code>public class PlayerWrapper {
    public player Player;
}
</code>```

The JSON should be

```<code>{
    "hp":100,
    "air":97,
    "inventory":[],
    "hasCalledHelp":false,
    "wonGame":false,
    "playerName":"Mads",
    "awesomePoints":0,
    "totalTimePlayed":3,
    "terminateThreads":false,
    "stopThreadOxygen":false,
    "stopThreadHP":false,
    "name":"Mads"
}
</code>```

or if you can not change the file use the PlayerWrapper:

```<code>mapper.readValue(testfile, PlayerWrapper.class)
</code>```

Body:
I'm trying, and failing to deserialize in jackson 2.9.2, i am trying to make a game, for a uni project, where i am working on a save function, where i can save my Player class, and serialize it, but when i try to deserialize it, and make a new player from it, it sets all the variables to null, this is my method:

public void LoadSaveString() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    //module.addDeserializer(SaveFile.class, new SaveDeserializer());
    mapper.registerModule(module);

    String filePath = "files/SaveFile.json";
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    testfile = reader.readLine();

    System.out.println("Stringen testfilen bliver printet: " + testfile);
    Player player1 = (Player) mapper.readValue(testfile, Player.class);
    System.out.println("Test 2: " + player1.toString());

}

and the output i get is:

Stringen testfilen bliver printet: {"player":{"hp":100,"air":97,"inventory":[],"hasCalledHelp":false,"wonGame":false,"playerName":"Mads","awesomePoints":0,"totalTimePlayed":3,"terminateThreads":false,"stopThreadOxygen":false,"stopThreadHP":false,"name":"Mads"}}

Test 2: Player{hp=0, air=0, inventory=null, hasCalledHelp=false, wonGame=false, awesomePoints=0, totalTimePlayed=0, terminateThreads=false, stopThreadOxygen=false, stopThreadHP=false}

And i have set my player class to ignore unknown properties, so i only, get and set, the things that are important for the playerclass

@JsonIgnoreProperties(ignoreUnknown = true)

and the properties in my Player class:

public class Player {
private int hp;
private int air;
private ArrayList<Item> inventory;
private boolean hasCalledHelp = false;
private boolean wonGame = false;
public String playerName = "Mads"; // Non-negotiable
public int awesomePoints = 0;
public int totalTimePlayed = 0;

Edit:

The content in the file SaveFile.json:

{
    "player": {
        "hp": 100,
        "air": 97,
        "inventory": [],
        "hasCalledHelp": false,
        "wonGame": false,
        "playerName": "Mads",
        "awesomePoints": 0,
        "totalTimePlayed": 3,
        "terminateThreads": false,
        "stopThreadOxygen": false,
        "stopThreadHP": false,
        "name": "Mads"
    }
}

Body:
The JSON of your file is an Object that has an attribute player. It's not a Player

{
    "player": { "hp":100, ... }
}

Something like:

public class PlayerWrapper {
    public player Player;
}

The JSON should be

{
    "hp":100,
    "air":97,
    "inventory":[],
    "hasCalledHelp":false,
    "wonGame":false,
    "playerName":"Mads",
    "awesomePoints":0,
    "totalTimePlayed":3,
    "terminateThreads":false,
    "stopThreadOxygen":false,
    "stopThreadHP":false,
    "name":"Mads"
}

or if you can not change the file use the PlayerWrapper:

mapper.readValue(testfile, PlayerWrapper.class)


问:
Xib file as a Custom TableView Cell crashes
I am using Xib file as a custom Tableview Cell. But everytime i run my application, it crashes. I get this crash logs which i posted below

* Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:6730
  2017-12-04 17:23:16.070 iCommander[2489:135476] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
  *** First throw call stack:
  (
      0   CoreFoundation                      0x00000001035f6b0b exceptionPreprocess + 171
      1   libobjc.A.dylib                     0x000000010305b141 objc_exception_throw + 48
      2   CoreFoundation                      0x00000001035facf2 +[NSException raise:format:arguments:] + 98
      3   Foundation                          0x0000000102bf5536 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
      4   UIKit                               0x00000001042eae45 -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] + 241
      5   iCommander                          0x0000000101e6b43f _TFC10iCommander25CommentsHistoryController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 303
      6   iCommander                          0x0000000101e6ba07 _TToFC10iCommander25CommentsHistoryController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 87
      7   UIKit                               0x00000001042fdab2 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 750
      8   UIKit                               0x00000001042fdcf8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
      9   UIKit                               0x00000001042d2639 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2845
      10  UIKit                               0x0000000104306ccc -[UITableView _performWithCachedTraitCollection:] + 111
      11  UIKit                               0x00000001042ede7a -[UITableView layoutSubviews] + 233
      12  UIKit                               0x000000010425455b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
      13  QuartzCore                          0x0000000102429904 -[CALayer layoutSublayers] + 146
      14  QuartzCore                          0x000000010241d526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
      15  QuartzCore                          0x000000010241d3a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
      16  QuartzCore                          0x00000001023ace92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
      17  QuartzCore                          0x00000001023d9130 _ZN2CA11Transaction6commitEv + 468
      18  QuartzCore                          0x00000001023d9b37 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 115
      19  CoreFoundation                      0x000000010359c717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23
      20  CoreFoundation                      0x000000010359c687 __CFRunLoopDoObservers + 391
      21  CoreFoundation                      0x0000000103581720 __CFRunLoopRun + 1200
      22  CoreFoundation                      0x0000000103581016 CFRunLoopRunSpecific + 406
      23  GraphicsServices                    0x00000001091e1a24 GSEventRunModal + 62
      24  UIKit                               0x0000000104191134 UIApplicationMain + 159
      25  iCommander                          0x0000000101e13ea7 main + 55
      26  libdyld.dylib                       0x000000010743e65d start + 1
      27  ???                                 0x0000000000000001 0x0 + 1
  )
  libc++abi.dylib: terminating with uncaught exception of type NSException

Please help. Thanks in advance.

答:
You forgot to register the XIB file. You have to register the xib file for getting rid of the crash.

In Swift 3

```<code> let xib = UINib(nibName: "YourCustomCell", bundle: nil)
 tableView.register(xib, forCellReuseIdentifier: "Cell")
</code>```

You should register the custom cell like that.

Hope it helps.

Body:
You forgot to register the XIB file. You have to register the xib file for getting rid of the crash.

In Swift 3

 let xib = UINib(nibName: "YourCustomCell", bundle: nil)
 tableView.register(xib, forCellReuseIdentifier: "Cell")

You should register the custom cell like that.

Hope it helps.


问:
Function to check if parameter is still the same
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

```<code>for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}
</code>```

my problem here is to return checkifcurrent(value) if it still the same like this

```<code>function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}
</code>```

I hope you understand tysm for understanding

答:
You can do it like this, no need for a function call.</p>

```<code>var data = ['test1','test1','test1','test2'];
lastValue = data[0];
for (var i = 1; i < data.length; i++) {
    var currentValue = data[i];
    if(lastValue==currentValue){
      console.log("Value is same")
    }
    else
    {
      console.log("Value is not same")
    }
    lastValue = currentValue;
}
</code>```

Body:
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}

my problem here is to return checkifcurrent(value) if it still the same like this

function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}

I hope you understand tysm for understanding

Body:
You can do it like this, no need for a function call.

var data = ['test1','test1','test1','test2'];
lastValue = data[0];
for (var i = 1; i < data.length; i++) {
    var currentValue = data[i];
    if(lastValue==currentValue){
      console.log("Value is same")
    }
    else
    {
      console.log("Value is not same")
    }
    lastValue = currentValue;
}


问:
When is a function too long?
35 lines, 55 lines, 100 lines, 300 lines? When you should start to break it apart? I'm asking because I have a function with 60 lines (including comments) and was thinking about breaking it apart.

```<code>long_function(){ ... }
</code>```

into:

```<code>small_function_1(){...}
small_function_2(){...}
small_function_3(){...}
</code>```

The functions are not going to be used outside of the long_function, making smaller functions means more function calls, etc.

When would you break apart a function into smaller ones? Why?

Methods should do only one logical thing (think about functionality)

You should be able to explain the method in a single sentence

It should fit into the height of your display

Avoid unnecessary overhead (comments that point out the obvious...)

Unit testing is easier for small logical functions

Check if part of the function can be reused by other classes or methods

Avoid excessive inter-class coupling

Avoid deeply nested control structures

Thanks everyone for the answers, edit the list and vote for the correct answer I'll choose that one ;)

I am refactoring now with those ideas in mind :)

答:
I have written 500 line functions before, however these were just big switch statements for decoding and responding to messages. When the code for a single message got more complex than a single if-then-else, I extracted it out.

In essence, although the function was 500 lines, the independently maintained regions averaged 5 lines.

LastEditorDisplayName: Movaxes

ContentLicense: CC BY-SA 2.5

Title: When is a function too long?

Body:
35 lines, 55 lines, 100 lines, 300 lines? When you should start to break it apart? I'm asking because I have a function with 60 lines (including comments) and was thinking about breaking it apart.

long_function(){ ... }

into:

small_function_1(){...}
small_function_2(){...}
small_function_3(){...}

The functions are not going to be used outside of the long_function, making smaller functions means more function calls, etc.

When would you break apart a function into smaller ones? Why?

Methods should do only one logical thing (think about functionality)

You should be able to explain the method in a single sentence

It should fit into the height of your display

Avoid unnecessary overhead (comments that point out the obvious...)

Unit testing is easier for small logical functions

Check if part of the function can be reused by other classes or methods

Avoid excessive inter-class coupling

Avoid deeply nested control structures

Thanks everyone for the answers, edit the list and vote for the correct answer I'll choose that one ;)

I am refactoring now with those ideas in mind :)

OwnerDisplayName: Joshua


问:
How to make TinyMCE work inside an UpdatePanel?
I'm trying to do something that many people seem to have been able to do but which I am unable to implement any solution. The TinyMCE control works pretty well in an asp.net form until you enclose it with an UpdatePanel, which then breaks after postback. I have tried some fixes like the RegisterClientScriptBlock method, but am still unsuccessful, I still lose the tinyMCE control after postback.

Below is a full test project (VS 2008) provided with a Control outside UpdatePanel and one inside, with a button on each to generate postback. Also in the project I have a EditorTest control which include commented code of some calls I tried, in case it gives anyone any ideas.

CODE SAMPLE

Here are some sources for some solutions on the MCE forum :

AJAX

UpdatePanel

答:
This is an old question, but after hours searching and messing around looking for the answer, I feel obligated to post the solution I came up with.

It appears that, at least in the implementation I'm using (multiple editors inside an UpdatePanel) that tinyMCE must be informed the control is going away when the UpdatePanel submits, or else it will refuse to load it again.

So, in addition to the code to Init TinyMCE (which only needs to run when the whole page loads) you need to do this for each of your MCE textboxes:

```<code>ScriptManager.RegisterStartupScript(this, this.GetType(), elm1.UniqueID+"Add",
    "tinyMCE.execCommand('mceAddControl', true,'" + elm1.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), elm1.UniqueID + "Remove",
    "tinyMCE.execCommand('mceRemoveControl', true,'" + elm1.ClientID + "');");
</code>```

elm1 is whatever the tinyMCE element is.  Mine is a textarea residing in a UserControl, but you can apply it to any item you want to bind/unbind your textarea.

LastEditorDisplayName: Nick Fortescue

Body:
This is an old question, but after hours searching and messing around looking for the answer, I feel obligated to post the solution I came up with.

It appears that, at least in the implementation I'm using (multiple editors inside an UpdatePanel) that tinyMCE must be informed the control is going away when the UpdatePanel submits, or else it will refuse to load it again.

So, in addition to the code to Init TinyMCE (which only needs to run when the whole page loads) you need to do this for each of your MCE textboxes:

ScriptManager.RegisterStartupScript(this, this.GetType(), elm1.UniqueID+"Add",
    "tinyMCE.execCommand('mceAddControl', true,'" + elm1.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), elm1.UniqueID + "Remove",
    "tinyMCE.execCommand('mceRemoveControl', true,'" + elm1.ClientID + "');");

elm1 is whatever the tinyMCE element is.  Mine is a textarea residing in a UserControl, but you can apply it to any item you want to bind/unbind your textarea.


答:
you can iterate over the data array and compare with all the array elements except the one at the current position.

If it is equals to the current and the index is not the same of the current then it is a duplicate

var data = ['test1','test1','test1','test2'];

for (var i = 0; i < data.length; i++) {
    var value = data[i];
    for(var j = 0; j < data.length; j++){
       //skip the index at position i, because it is the one we are currently comparing
     if(i !== j && data[j] === value) {
 console.log('another value like: ' + value + ' at position: ' + i + ' has been found at index: ' + j)
      }
    }
}```

Title: Function to check if parameter is still the same


问:
How can I search data from firebase in android
I'm doing my project.
My project is App for finding room in my campus.
In my database there are room name, floor, building room and location.

I want to find all records that have a keyword that the user want to find.
And show data about that room.

My firebase

答:
Refer this link for complete code
http://www.amalhichri.net/android-firebase-realtime-database-basic-cruds/

private void findperson(String name){
     Query deleteQuery = myDatabaseReference.orderByChild("fullName").equalTo(name);

```<code>    deleteQuery.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Iterable snapshotIterator = dataSnapshot.getChildren();
            Iterator iterator = snapshotIterator.iterator();
            while((iterator.hasNext())){
                Log.d("Item found: ",iterator.next().getValue().toString()+"---");
            }
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }`enter code here`

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d("Item not found: ","this item is not in the list");
        }
    });
}
</code>```

Body:
Refer this link for complete code
http://www.amalhichri.net/android-firebase-realtime-database-basic-cruds/

private void findperson(String name){
     Query deleteQuery = myDatabaseReference.orderByChild("fullName").equalTo(name);

    deleteQuery.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Iterable snapshotIterator = dataSnapshot.getChildren();
            Iterator iterator = snapshotIterator.iterator();
            while((iterator.hasNext())){
                Log.d("Item found: ",iterator.next().getValue().toString()+"---");
            }
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }`enter code here`

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d("Item not found: ","this item is not in the list");
        }
    });
}


问:
Remove Row from DataTable using a custom button
I'm trying to remove the selected row using a custom button in dataTable (datatables.net). I tried to follow the documentation but there is something that I don't understand. What I did is After I click Approve on confirmation pop-up I execute the code given on documentation rows().remove() but nothing happens.

Here is my code:

```<code><script>
    $(function () {
        var dataSet = [
                        [
                            "<div class='pull-right'>" +
                            "<br />" +
                            "<button type='button' class='btn btn-success' id='Approve' onclick='Approve(1)'> APPROVE </button>  " +
                            "<button type='button' class='btn btn-danger' id='Decline' onclick='Decline(1)' > DECLINE </button>" +
                            "</div>"
                        ]
                      ]

        $('#AccomplishmentTable').dataTable({
            data: dataSet,
            columns: [
                { title: "Employee" }
            ]
        });
    });
</script>
</code>```

The event I'm trying to execute:

```<code><script>
    $('#AccomplishmentTable tbody').on('click', '#Approve', function () {
        swal({
        title: "Approve this Accomplishment?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#5cb85c",
        confirmButtonText: "Approve",
        closeOnConfirm: true,
        closeOnCancel: true
        },
        function (isConfirm) {
            if (isConfirm) {
                var url = "@Url.Action("Approve", "Utilities")";
                // $.get(url, { id: id }, function (e) {
                //     swal(e.MTitle, e.MBody, e.MType);
                // });
                console.log("Check");
                var table = $('#AccomplishmentTable').DataTable();
                    table
                    .row($(this).parents('tr'))
                    .remove()
                    .draw();
            }
        });
    });
</script>
</code>```

EDIT:
I'm using ASP.NET MVC and here is the UI of my code to avoid confusion

答:
You have a simple scope problem, this refers to the embedded confirm function (or what it is), not the outer event handler. Do this instead :

```<code>$('#AccomplishmentTable tbody').on('click', '#Approve', function () {
  var row = $(this).closest('tr');
  var api = $('#AccomplishmentTable').DataTable();

    swal({
    title: "Approve this Accomplishment?",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#5cb85c",
    confirmButtonText: "Approve",
    closeOnConfirm: true,
    closeOnCancel: true
    },
    function (isConfirm) {
        if (isConfirm) {
            var url = "@Url.Action("Approve", "Utilities")";
            // $.get(url, { id: id }, function (e) {
            //     swal(e.MTitle, e.MBody, e.MType);
            // });
            console.log("Check");
            api.row(row).remove().draw();
        }
    });
});
</code>```

Body:
I'm trying to remove the selected row using a custom button in dataTable (datatables.net). I tried to follow the documentation but there is something that I don't understand. What I did is After I click Approve on confirmation pop-up I execute the code given on documentation rows().remove() but nothing happens.

Here is my code:

The event I'm trying to execute:

EDIT:
I'm using ASP.NET MVC and here is the UI of my code to avoid confusion

Body:
You have a simple scope problem, this refers to the embedded confirm function (or what it is), not the outer event handler. Do this instead :

$('#AccomplishmentTable tbody').on('click', '#Approve', function () {
  var row = $(this).closest('tr');
  var api = $('#AccomplishmentTable').DataTable();

    swal({
    title: "Approve this Accomplishment?",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#5cb85c",
    confirmButtonText: "Approve",
    closeOnConfirm: true,
    closeOnCancel: true
    },
    function (isConfirm) {
        if (isConfirm) {
            var url = "@Url.Action("Approve", "Utilities")";
            // $.get(url, { id: id }, function (e) {
            //     swal(e.MTitle, e.MBody, e.MType);
            // });
            console.log("Check");
            api.row(row).remove().draw();
        }
    });
});


问:
Exception thrown at 0x00007FF93E507A7A (ntdll.dll) .Access violation reading location 0xFFFFFFFFFFFFFFFF
I'm using POCO lib to working network.
i use JSON data of POCO/JSON . my code:

```<code>User user(context.marshal_as<std::string>(tbUserName->Text),
        context.marshal_as<std::string>(tbFullName->Text),
        context.marshal_as<std::string>(tbDisplayName->Text),
        context.marshal_as<std::string>(tbEmail->Text),
        context.marshal_as<std::string>(tbPhoneNumber->Text),
        context.marshal_as<std::string>(tbNamSinh->Text),
        context.marshal_as<std::string>(tbPassword->Text),
        context.marshal_as<std::string>(tbConfirm->Text)
    );
    string jsonString = user.serialize();
</code>```

I have an error Exception thrown at 0x00007FF93E507A7A (ntdll.dll) in Client_Winform.exe:

0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.

If there is a handler for this exception, the program may be safely continued.

答:
Use Visual Studio's Code Analysis to track the exact place in your code where the bug is.
https://msdn.microsoft.com/en-us/library/ms182028.aspx
The problem with these kinds of error messages is not to understand the reason (bad handle) but to find the place. Since your code passed compilation with no errors, and in many cases, will run smoothly on several machines and crash only on one of them, you need to focus on the place of the crash. </p>

Body:
I'm using POCO lib to working network.
i use JSON data of POCO/JSON . my code:

User user(context.marshal_as<std::string>(tbUserName->Text),
        context.marshal_as<std::string>(tbFullName->Text),
        context.marshal_as<std::string>(tbDisplayName->Text),
        context.marshal_as<std::string>(tbEmail->Text),
        context.marshal_as<std::string>(tbPhoneNumber->Text),
        context.marshal_as<std::string>(tbNamSinh->Text),
        context.marshal_as<std::string>(tbPassword->Text),
        context.marshal_as<std::string>(tbConfirm->Text)
    );
    string jsonString = user.serialize();

I have an error Exception thrown at 0x00007FF93E507A7A (ntdll.dll) in Client_Winform.exe:

0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.

If there is a handler for this exception, the program may be safely continued.


问:
where to find specific version of aws-java-sdk?
I want to download aws-java-sdk-1.9.5, could not find any archive for this jar.
Whatever I am finding is the latest jar from AWS site https://aws.amazon.com/sdk-for-java/

I also checked maven repository but there the available jar is of 2 KBs only that didn't contain any source in the jar.
http://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk/1.9.5

Any suggestion would be appreciated.

答:
The aws-sdk-java JAR contains a list of dependencies on all other JARs in the AWS SDK. If you depend on it, then by Maven's transitive dependency mechanism you will add all of the other SDK JARs to your dependency tree.

Which you do not want to do

I've lost count of the number of individual AWS JARs, but there are a lot -- certainly dozens, possibly as many as a hundred. There's one JAR (at least) per AWS service, most of which you will never use.

A better approach is to download that JAR so that you know the names of the dependencies, then import them individually.


问:
How to use iOS 11.1 device with Xcode 8 or earlier?
I want to install my app on iOS 11 device using xcode8. I don't wan't to update xcode.</p>

答:
Just found device support files for iOS 11.1 and 11.2 (15C5097c) devices. Copy these files to DeviceSupport Folder using following method:

Open Finder window -> Select GO from Finder Menu -> Select Go to folder and paste following path...
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

you can find 11.1 device support file from https://drive.google.com/open?id=1vZHgF0-8yqet2581oioupGz-J6l4Lp97

and 11.2 from https://drive.google.com/open?id=1Jfj2nqWK0Aktvnrd5wlMK-zBVaXjDml5


问:
Trying to Create Bot with AWS Java SDK using Intents
I want to programmatically create a Bot with a simple Intent, sadly i got an error message that the resource(the intent) wasn't found, although I can see the created Intent in the Console.

Thats my simple Code:

```<code>package building;

import java.util.ArrayList;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuilding;
import com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClientBuilder;
import com.amazonaws.services.lexmodelbuilding.model.ContentType;
import com.amazonaws.services.lexmodelbuilding.model.FulfillmentActivity;
import com.amazonaws.services.lexmodelbuilding.model.FulfillmentActivityType;
import com.amazonaws.services.lexmodelbuilding.model.Intent;
import com.amazonaws.services.lexmodelbuilding.model.Message;
import com.amazonaws.services.lexmodelbuilding.model.Prompt;
import com.amazonaws.services.lexmodelbuilding.model.PutBotRequest;
import com.amazonaws.services.lexmodelbuilding.model.PutBotResult;
import com.amazonaws.services.lexmodelbuilding.model.PutIntentRequest;
import com.amazonaws.services.lexmodelbuilding.model.PutIntentResult;

public class ChatBotBuilder {

    public static void main(String [] args) {

        AmazonLexModelBuilding botBuilder = AmazonLexModelBuildingClientBuilder.standard().withRegion(Regions.EU_WEST_1).build();
        ArrayList<Intent> intents = new ArrayList<Intent>();
        Intent test = new Intent().withIntentName("Testintent").withIntentVersion("1");

        intents.add(test);

        PutIntentRequest putIntentRequest = new PutIntentRequest()
                .withDescription("das ist ein intenttest")
                .withFulfillmentActivity(new FulfillmentActivity().withType(FulfillmentActivityType.ReturnIntent))
                .withName("Testintent")
                .withSampleUtterances(new String[] {"Ich möchte den Test starten","Gib mir was"});

        PutIntentResult intentResult = botBuilder.putIntent(putIntentRequest);

        System.out.println(intentResult.getName());

        PutBotRequest putBotRequest = new PutBotRequest().withChildDirected(false)
                .withClarificationPrompt(new Prompt()
                                            .withMaxAttempts(5)
                                            .withMessages(new Message[] {new Message().withContent("Was genau willst du?").withContentType(ContentType.PlainText), new Message().withContent("Was genau du wollen?").withContentType(ContentType.PlainText)}))
                .withDescription("Programmbot")
                .withIntents(intents)
                .withName("TestBot")
                .withLocale("en-US");

        PutBotResult result = botBuilder.putBot(putBotRequest);
        System.out.println(result.getName());
        System.out.println(result.getFailureReason());

    }
}
</code>```

I expect the Code to create a Intent, and then a Bot with the created Intent.

What I actually get is:

```<code>Exception in thread "main" com.amazonaws.services.lexmodelbuilding.model.BadRequestException: The resource 'Testintent' referenced in resource 'TestBot' was not found. Choose another resource. (Service: AmazonLexModelBuilding; Status Code: 400; Error Code: BadRequestException; Request ID: b42d37ee-d8d7-11e7-ac95-f9876d663323)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1639)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1304)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.doInvoke(AmazonLexModelBuildingClient.java:2626)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.invoke(AmazonLexModelBuildingClient.java:2602)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.executePutBot(AmazonLexModelBuildingClient.java:2302)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.putBot(AmazonLexModelBuildingClient.java:2278)
    at building.ChatBotBuilder.main(ChatBotBuilder.java:51)
</code>```

答:
I specified the Version of the Intent wrong.

```<code>Intent test = new Intent().withIntentName("Testintent").withIntentVersion("1");
</code>```

This Intent can't be found because the Version of the created Intent is "$LATEST" not "1".

This is correct:

```<code>Intent test = new Intent().withIntentName("Testintent").withIntentVersion("$LATEST");
</code>```

Body:
I want to programmatically create a Bot with a simple Intent, sadly i got an error message that the resource(the intent) wasn't found, although I can see the created Intent in the Console.

Thats my simple Code:

package building;

import java.util.ArrayList;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuilding;
import com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClientBuilder;
import com.amazonaws.services.lexmodelbuilding.model.ContentType;
import com.amazonaws.services.lexmodelbuilding.model.FulfillmentActivity;
import com.amazonaws.services.lexmodelbuilding.model.FulfillmentActivityType;
import com.amazonaws.services.lexmodelbuilding.model.Intent;
import com.amazonaws.services.lexmodelbuilding.model.Message;
import com.amazonaws.services.lexmodelbuilding.model.Prompt;
import com.amazonaws.services.lexmodelbuilding.model.PutBotRequest;
import com.amazonaws.services.lexmodelbuilding.model.PutBotResult;
import com.amazonaws.services.lexmodelbuilding.model.PutIntentRequest;
import com.amazonaws.services.lexmodelbuilding.model.PutIntentResult;

public class ChatBotBuilder {

    public static void main(String [] args) {

        AmazonLexModelBuilding botBuilder = AmazonLexModelBuildingClientBuilder.standard().withRegion(Regions.EU_WEST_1).build();
        ArrayList<Intent> intents = new ArrayList<Intent>();
        Intent test = new Intent().withIntentName("Testintent").withIntentVersion("1");

        intents.add(test);

        PutIntentRequest putIntentRequest = new PutIntentRequest()
                .withDescription("das ist ein intenttest")
                .withFulfillmentActivity(new FulfillmentActivity().withType(FulfillmentActivityType.ReturnIntent))
                .withName("Testintent")
                .withSampleUtterances(new String[] {"Ich möchte den Test starten","Gib mir was"});

        PutIntentResult intentResult = botBuilder.putIntent(putIntentRequest);

        System.out.println(intentResult.getName());

        PutBotRequest putBotRequest = new PutBotRequest().withChildDirected(false)
                .withClarificationPrompt(new Prompt()
                                            .withMaxAttempts(5)
                                            .withMessages(new Message[] {new Message().withContent("Was genau willst du?").withContentType(ContentType.PlainText), new Message().withContent("Was genau du wollen?").withContentType(ContentType.PlainText)}))
                .withDescription("Programmbot")
                .withIntents(intents)
                .withName("TestBot")
                .withLocale("en-US");

        PutBotResult result = botBuilder.putBot(putBotRequest);
        System.out.println(result.getName());
        System.out.println(result.getFailureReason());

    }
}

I expect the Code to create a Intent, and then a Bot with the created Intent.

What I actually get is:

Exception in thread "main" com.amazonaws.services.lexmodelbuilding.model.BadRequestException: The resource 'Testintent' referenced in resource 'TestBot' was not found. Choose another resource. (Service: AmazonLexModelBuilding; Status Code: 400; Error Code: BadRequestException; Request ID: b42d37ee-d8d7-11e7-ac95-f9876d663323)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1639)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1304)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.doInvoke(AmazonLexModelBuildingClient.java:2626)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.invoke(AmazonLexModelBuildingClient.java:2602)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.executePutBot(AmazonLexModelBuildingClient.java:2302)
    at com.amazonaws.services.lexmodelbuilding.AmazonLexModelBuildingClient.putBot(AmazonLexModelBuildingClient.java:2278)
    at building.ChatBotBuilder.main(ChatBotBuilder.java:51)

Body:
I specified the Version of the Intent wrong.

Intent test = new Intent().withIntentName("Testintent").withIntentVersion("1");

This Intent can't be found because the Version of the created Intent is "$LATEST" not "1".

This is correct:

Intent test = new Intent().withIntentName("Testintent").withIntentVersion("$LATEST");


问:
Most useful Rails plugins, Ruby libraries and Ruby gems?
I have seen many sites which provide the whole list of Rails plugins, Ruby libraries and Ruby gems, but we hardly use few of them and some may not suit our requirement and we spend a whole lot of time searching for useful Plugins which suits our requirement.

I have created this poll, people can post useful libraries, gems and plugins which they have come across.  It would be great help for newbies like me and to the entire Ruby on Rails community.

Note: to keep this poll as useful as possible, please remember:

Post only one library, gem, or plugin per answer

Mention the name of the library, gem, or plugin which you find it useful.

URL of the location of the resource

We don't want duplicate answers, so before posting check if the library has been mentioned already.

Edit:  Any new plugins/Gems for Rails 3 ?

Thanks!

答:
Webrat - testing

is a Ruby integration test library. It has two main purposes:

Implement a browser simulator to allow fast, reliable integration testing (sans JavaScript) without requiring Selenium or Watir and their associated issues.

Define a ubiquitous DSL for describing interacting with a web application from the perspective of an end user.

ContentLicense: CC BY-SA 4.0


问:
Wrapped, vertically scrolling alphabet in libGDX
I need a vertically scrolling alphabet in libGDX.  The user won't directly interact with it. I thought about using ScrollPane, however, it doesn't seem to wrap (I'm happy to be corrected if I have that wrong).

I plan to present five letters at a time.  The vertically scrolling alphabet needs to wrap so that when the bottom letter is 'Z' and it scrolls upwards, 'A' becomes the bottom letter.

What's the best approach for this in libGDX?  Many thanks.

答:
VerticalGroup has an option to wrap the content.</p>

```<code>VerticalGroup group = new VerticalGroup();
group.wrap();
group.addActor( ... ); // a table or the individual letters

ScrollPane scrollPane = new ScrollPane( group );
</code>```

Body:
VerticalGroup has an option to wrap the content.

VerticalGroup group = new VerticalGroup();
group.wrap();
group.addActor( ... ); // a table or the individual letters

ScrollPane scrollPane = new ScrollPane( group );


问:
what does "DependsOn": [] means in cloudformation
I am using a AWS supplied template which uses "DependsOn": [] in a nested stack call.
I know dependson can have a list dependencies but have never come across this.</p>

```<code>BucketsStack": {
        "DependsOn": [],
        "Properties": {
            "Parameters": {
                "CreateDemonstration": {
                    "Ref": "CreateDemonstration"
                },
</code>```

答:
Remove it as it is an empty array so it is useless  .

Indeed DependsOn affects the order of resources creation.

Below is from the official documentation.

With the DependsOn attribute you can specify that the creation of a
  specific resource follows another. When you add a DependsOn attribute
  to a resource, that resource is created only after the creation of the
  resource specified in the DependsOn attribute.

Body:
I am using a AWS supplied template which uses "DependsOn": [] in a nested stack call.
I know dependson can have a list dependencies but have never come across this.

BucketsStack": {
        "DependsOn": [],
        "Properties": {
            "Parameters": {
                "CreateDemonstration": {
                    "Ref": "CreateDemonstration"
                },


问:
Detecting and Comparing Shapes between two images
I'm currently working on a project that needs the shape of objects in two images to be compared.

I have to check if the shape varies above a certain threshold.

I already have the ROI(Region Of Interest) where the objects can occur in the images.I just need to compare the shape in that ROI.

Many objects may be present in the ROI(objects position may vary) and I have to check if they are also present at approximately the same spot on the second image by comparing the shapes. In short, I need to check for similarity between the shapes present in the two images.

I tried contours, but it doesn't work well in finding all contours and varies with different images.

I am now trying to use Histogram of Oriented Gradients(HOG) approach now. I have got the feature vectors for two images separately. But I don't know how to compare the HOG feature vectors of the two images to find shape similarity.

Deep learning and CNN can only be used if the object to be detected is known beforehand along with a large number of training images. My problem is that object can be anything and I don't have large training sets. So, I decided to go with shape descriptors like HOG, SIFT, SURF,... But I don't know how to work with them effectively to get desired outputs.

I can't understand the outputs(feature vectors) from the descriptors. I don't know how to use feature vectors from both the images to compare the shapes present in the two images.

Can anyone help me in understanding and working with shape descriptors(HOG, SIFT, SURF,...)? How can we compare the HOG feature vectors of two images? or is there a better way to compare if two images have similar shapes in them?  Detecting and Comparing Shapes is the goal.

答:
Detecting and Comparing Shapes between two images can be broken into two parts.

Detecting Shapes

Comparing Shapes

Detecting Shapes

Detecteting Shapes can be easy tackled using the OpenCV library available.
(https://docs.opencv.org/trunk/d4/dc6/tutorial_py_template_matching.html)

```<code>import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0)
img2 = img.copy()
template = cv2.imread('template.jpg',0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
        'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
    img = img2.copy()
    method = eval(meth)
    # Apply template Matching
    res = cv2.matchTemplate(img,template,method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv2.rectangle(img,top_left, bottom_right, 255, 2)
    plt.subplot(121),plt.imshow(res,cmap = 'gray')
    plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(img,cmap = 'gray')
    plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
    plt.suptitle(meth)
    plt.show()
</code>```

Comparing Shapes

The match template can also give scores of matching and the scale, which could be used to compare shapes.

The only caveat would be that the score is not relative and depends on the image size and the matching algorithms used. This needs to be tweaks according to the need.

Body:
Detecting and Comparing Shapes between two images can be broken into two parts.

Detecting Shapes

Comparing Shapes

Detecting Shapes

Detecteting Shapes can be easy tackled using the OpenCV library available.
(https://docs.opencv.org/trunk/d4/dc6/tutorial_py_template_matching.html)

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('messi5.jpg',0)
img2 = img.copy()
template = cv2.imread('template.jpg',0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
        'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
    img = img2.copy()
    method = eval(meth)
    # Apply template Matching
    res = cv2.matchTemplate(img,template,method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv2.rectangle(img,top_left, bottom_right, 255, 2)
    plt.subplot(121),plt.imshow(res,cmap = 'gray')
    plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(img,cmap = 'gray')
    plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
    plt.suptitle(meth)
    plt.show()

Comparing Shapes

The match template can also give scores of matching and the scale, which could be used to compare shapes.

The only caveat would be that the score is not relative and depends on the image size and the matching algorithms used. This needs to be tweaks according to the need.


问:
qemu-arm running compiled binary
Trying to run a compiled binary I've extracted from a firmware on qemu, however I encounter this error:

```<code>root@ubuntu14:~# qemu-arm -L /usr/arm-linux-gnueabi ~/x
/system/bin/linker: No such file or directory

root@ubuntu14:~# file ./x
./x: ELF 32-bit LSB  shared object, ARM, EABI5 version 1 (SYSV), dynamically linked (uses shared libs), stripped
</code>```

I'm using the "-L" flag, as suggested in:
qemu-arm can't run arm compiled binary

However, this flag doesn't seem to make a different for me, neither does setting QEMU_LD_PREFIX

Could it be some missing dependencies?

答: /system/bin/linker is the Android dynamic linker, so you need a directory with the Android dynamic linker and dynamic libraries, not one for Linux (which is what /usr/arm-linux-gnueabi will be). You should be able to pull the relevant files out of your firmware image, I expect.</p>

Title: qemu-arm running compiled binary

Body:
Trying to run a compiled binary I've extracted from a firmware on qemu, however I encounter this error:

root@ubuntu14:~# qemu-arm -L /usr/arm-linux-gnueabi ~/x
/system/bin/linker: No such file or directory

root@ubuntu14:~# file ./x
./x: ELF 32-bit LSB  shared object, ARM, EABI5 version 1 (SYSV), dynamically linked (uses shared libs), stripped

I'm using the "-L" flag, as suggested in:
qemu-arm can't run arm compiled binary

However, this flag doesn't seem to make a different for me, neither does setting QEMU_LD_PREFIX

Could it be some missing dependencies?


问:
HTMLDOC Chinese language Support
I have a page with the Chinese content written in it. I am using htmldoc to convert it to PDF. Now while converting to PDF it shows garbage characters and not the Chinese characters. I have my html pages in multiple languages. When users clicks on download as PDF I want to convert them to pdf in those languages. Its working perfectly fine for English but for languages other than English I am facing problem.
Any help would be appreciated</p>

答:
Unfortunately, as htmldoc author mentioned at http://michaelrsweet.github.io/htmldoc/:

you can’t use HTMLDOC to format Arabic, Chinese, Hebrew, Japanese, or other languages that are not based on latin-based alphabets that read left-to-right

Title: HTMLDOC Chinese language Support


问:
Integrating social network connections into website
I have a client who has a web site that requires membership.  He wants to allow his users to find other users with whom they might have a existing friendship/relationship on a social networking site (Facebook, Twitter, etc).

Does anybody have any experience with this type of problem?  If so, what to packages/APIs did you use?  Right now I'm evaluating Janrain and Gigya, but we're still in the decision-making phase so I'm open to other solutions.  This is mostly a JSP shop, but again, we're open.

Thanks in advance,
Chip

答:
I assume you mean visitors should have the ability to find existing friendships before their decision to register (ie. they'll be more inclined to register if they see [x] number of friends are already using the site).

If you're just interfacing with Facebook, try using their Facepile plugin. It's a quick way for non-registered users to see which Facebook friends are using the application (assuming a valid FB session).

If you're interested in multiple networks, Gigya is a really good solution. One feature you might find useful is their getFriendsInfo() method. If you set the siteUsersOnly parameter to true, Gigya will only return social network friends who are also registered users of the site.

Regardless of your choice, one piece of advice is to make sure visitors understand they aren't registering for the site just by signing-in with their social network account and checking for friends. For some users, this distinction isn't always clear.

Hope some of this helps.


问:
Replace class in order to replace image on click with jquery
I read a number of articles and answers here on Stack Overflow but none of them answered my question as I'm really a noob when it comes to jQuery and I'm not sure how to do this.

I have a HTML landing page on which I'm trying to show several images on which you click and they get replaced with another image and when clicked again or at another image the original one is shown.

I have this so far:

```<code><div class="santa">
  <img class="show" src="images/santa.png" alt="">
  <img class="hide" src="images/bubble.png" alt="">
</div>
</code>```

.hide { display: none; }
.show { display: block; }
```

I want to show santa.png by default and when clicked on to change it to bubble.png, meaning default class is show and when clicked on it's hide for santa and vice versa.

Thanks in advance!

答:
The simple way to do this is to call toggle() on both the displayed and hidden images when one is clicked. This will invert the display state of both elements simultaneously:

$('.hide, .show').click(function() {
  $(this).closest('div').find('.hide, .show').toggle();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide { display: none; }
.show { display: block; }</code>```

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

<p>If you actually want to change the <code>class</code> values on the elements, then you can use <code>toggleClass()</code> instead:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.hide, .show').click(function() {
  $(this).closest('div').find('.hide, .show').toggleClass('hide show');
})</code>```

.hide { display: none; }
.show { display: block; }```
<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 class="santa">
  <img class="show" src="images/santa.png" alt="Santa">
  <img class="hide" src="images/bubble.png" alt="Bubble">
</div>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa2">
  <img class="hide" src="images/bubble.png" alt="Bubble2">
</div></code>```

Body:
I read a number of articles and answers here on Stack Overflow but none of them answered my question as I'm really a noob when it comes to jQuery and I'm not sure how to do this.

I have a HTML landing page on which I'm trying to show several images on which you click and they get replaced with another image and when clicked again or at another image the original one is shown.

I have this so far:

.hide { display: none; }
.show { display: block; }

I want to show santa.png by default and when clicked on to change it to bubble.png, meaning default class is show and when clicked on it's hide for santa and vice versa.

Thanks in advance!

Body:
The simple way to do this is to call toggle() on both the displayed and hidden images when one is clicked. This will invert the display state of both elements simultaneously:

$('.hide, .show').click(function() {
  $(this).closest('div').find('.hide, .show').toggle();
})

.hide { display: none; }
.show { display: block; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa">
  <img class="hide" src="images/bubble.png" alt="Bubble">
</div>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa2">
  <img class="hide" src="images/bubble.png" alt="Bubble2">
</div>

If you actually want to change the class values on the elements, then you can use toggleClass() instead:

$('.hide, .show').click(function() {
  $(this).closest('div').find('.hide, .show').toggleClass('hide show');
})

.hide { display: none; }
.show { display: block; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa">
  <img class="hide" src="images/bubble.png" alt="Bubble">
</div>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa2">
  <img class="hide" src="images/bubble.png" alt="Bubble2">
</div>


问:
CodeTaskFactory" could not be found in the assembly"
I'm new in Dot net after I cloned some project from GitHub, I try to run then got below error.

OS: Mac 10.12.6 (16G29)
Tool version: Visual stuido 2017
SDK: 2

```<code>/Volumes/Users/Administrator/Documents/My Web Sites/nopCommerce-develop
/nopCommerce-develop/src/Build/ClearPluginAssemblies.proj(5,5): Error MSB4174:
 The task factory "CodeTaskFactory" could not be found in the assembly "/Library/Frameworks/Mono.framework/Versions/5.2.0/lib/mono/msbuild/15.0/bin/Micro
soft.Build.Tasks.v4.0.dll". (MSB4174) (Nop.Web)
</code>```

答:
As per the previous answer:

nopCommerce 4.0 has developed with .NET core, but still its targeting to .NET Framework 4.6 and not .NET Core. So you cannot run nopCommerce 4.0 to MAC or Linux.

Still if you would like to run it to cross platform, you can change the targeted framework to .NET Core and solve the errors may you face.

Body:
I'm new in Dot net after I cloned some project from GitHub, I try to run then got below error.

OS: Mac 10.12.6 (16G29)
Tool version: Visual stuido 2017
SDK: 2

/Volumes/Users/Administrator/Documents/My Web Sites/nopCommerce-develop
/nopCommerce-develop/src/Build/ClearPluginAssemblies.proj(5,5): Error MSB4174:
 The task factory "CodeTaskFactory" could not be found in the assembly "/Library/Frameworks/Mono.framework/Versions/5.2.0/lib/mono/msbuild/15.0/bin/Micro
soft.Build.Tasks.v4.0.dll". (MSB4174) (Nop.Web)


问:
Fill an Input without selecting it before. HTML / JS?
I would like to fill an input without having to select it with my mouse before. Just using javascript and not Jquery .

What I mean is that they user just have ton type his answer and it goes directly into the input. Here is my HTML.

```<code><input id="inputresponse" name="response" type="text" value="" />
</code>```

I have searched everywhere but I can't find a clue. I guess we should use either keyup or keypress, but I can't find how.

Your help is highly appreciated, thanks !

答:
Use Autofocus on HTML tag as -

<input id="inputresponse" name="response" type="text" autofocus>```
</div>
</div>
</p>

<blockquote>
  <p>Another Way, You can use js also -</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = function() {
    var input = document.getElementById("inputresponse").focus();
}</code>```

<input id="inputresponse" name="response" type="text">```

Body:
I would like to fill an input without having to select it with my mouse before. Just using javascript and not Jquery .

What I mean is that they user just have ton type his answer and it goes directly into the input. Here is my HTML.

<input id="inputresponse" name="response" type="text" value="" />

I have searched everywhere but I can't find a clue. I guess we should use either keyup or keypress, but I can't find how.

Your help is highly appreciated, thanks !

Body:
Use Autofocus on HTML tag as -

<input id="inputresponse" name="response" type="text" autofocus>

Another Way, You can use js also -

window.onload = function() {
    var input = document.getElementById("inputresponse").focus();
}

<input id="inputresponse" name="response" type="text">


问:
PHP Update Set If else
If sinkQty field in the given record is not equal to the existing value, then want current date NOW() otherwise keep existing date.
The update fails. Any words of wisdom would sure help on this project!

```<code>$tbl_name="sink";

$count=mysql_num_rows($result);

$sinkid    = $_POST['sinkID'];
$qty       = $_POST['sinkQty'];
$qtyonorder= $_POST['sinkQtyOnOrder'];
$desiredqty= $_POST['sinkDesiredQty'];
$posted    = $_POST['sinkPosted'];

for($i=0;$i<$count;$i++)
{
    $sql1=("UPDATE $tbl_name
            SET sinkPosted = IF ( sinkQty != $qty[$i] ,NOW(), $posted[$i]),
                sinkQty=$qty[$i],
                sinkDesiredQty=$desiredqty[$i],
                sinkQtyOnOrder=$qtyonorder[$i]
            WHERE sinkID=$sinkid[$i]");

    $result1=mysql_query($sql1);
}
</code>```

答:
```<code> $sql1=("UPDATE $tbl_name
        SET sinkPosted = IF ( sinkQty != $qty[$i] ,NOW(), $posted[$i]),
            sinkQty=$qty[$i],
            sinkDesiredQty=$desiredqty[$i],
            sinkQtyOnOrder=$qtyonorder[$i]
        WHERE sinkID=$sinkid[$i]");
// Try
$query = "UPDATE $tbl_name
        SET sinkPosted = IF ( sinkQty != $qty[$i] ,NOW(), $posted[$i]),
            sinkQty=$qty[$i],
            sinkDesiredQty=$desiredqty[$i],
            sinkQtyOnOrder=$qtyonorder[$i]
        WHERE sinkID=$sinkid[$i]";
echo "```$query```";
$result1 = mysql_query($query) or die(mysql_error());
// And please, remove SQL Injection from $query.
</code>```

Title: PHP Update Set If else

Body:
If sinkQty field in the given record is not equal to the existing value, then want current date NOW() otherwise keep existing date.
The update fails. Any words of wisdom would sure help on this project!

$tbl_name="sink";

$count=mysql_num_rows($result);

$sinkid    = $_POST['sinkID'];
$qty       = $_POST['sinkQty'];
$qtyonorder= $_POST['sinkQtyOnOrder'];
$desiredqty= $_POST['sinkDesiredQty'];
$posted    = $_POST['sinkPosted'];

for($i=0;$i<$count;$i++)
{
    $sql1=("UPDATE $tbl_name
            SET sinkPosted = IF ( sinkQty != $qty[$i] ,NOW(), $posted[$i]),
                sinkQty=$qty[$i],
                sinkDesiredQty=$desiredqty[$i],
                sinkQtyOnOrder=$qtyonorder[$i]
            WHERE sinkID=$sinkid[$i]");

    $result1=mysql_query($sql1);
}

Body:
 $sql1=("UPDATE $tbl_name
        SET sinkPosted = IF ( sinkQty != $qty[$i] ,NOW(), $posted[$i]),
            sinkQty=$qty[$i],
            sinkDesiredQty=$desiredqty[$i],
            sinkQtyOnOrder=$qtyonorder[$i]
        WHERE sinkID=$sinkid[$i]");
// Try
$query = "UPDATE $tbl_name
        SET sinkPosted = IF ( sinkQty != $qty[$i] ,NOW(), $posted[$i]),
            sinkQty=$qty[$i],
            sinkDesiredQty=$desiredqty[$i],
            sinkQtyOnOrder=$qtyonorder[$i]
        WHERE sinkID=$sinkid[$i]";
echo "<pre>$query</pre>";
$result1 = mysql_query($query) or die(mysql_error());
// And please, remove SQL Injection from $query.


问:
Java custom class loader issue
I'm sending a Class object from client to server side. Every time the server needs to load the Class object sent by the client instead of reusing it by parent delegation model (when it was loaded during the 1st iteration).

I'm trying to use a custom class loader on the server side whose loadClass(String) simply calls findClass() instead of checking with parent hierarchy.
To achieve this, I'm doing following:

Generate byte[] by reading the .class file on the client side as following:

```<code>Class cl = com.example.XYZ.class;
String path = cl.getName().replace('.', '/') + ".class";
InputStream is = cl.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data = -1;
while((data=is.read())!=-1)
  bos.write(data);
byte[] classBinaryData = bos.toByteArray();
</code>```

I'm sending classBinaryData to the server side.

On the server side, every time I retrieve the byte[], verify if it's the same as on client side by matching MD5 checksum, then I create a new instance of my custom class loader and pass the byte array so it could be used in calling defineClass from within findClass.

However, I'm getting either of the errors (depending on the way I create byte[] out of .class)

Incompatible magic value ..... in class file <Unknown>

OR

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

I need help in figuring out the mistake in my approach/code.

答:
Your code looks fine. Your error is somewhere else.

You are, in some way, returning bad class files from your class loader.

The first error means the byte array is totally garbled; the first 4 bytes are wrong. You can check them easily (they have to be 0xCAFEBABE), to catch this error earlier.

The other error, I think, means that you are returning the definition of a different class than was requested.

Title: Java custom class loader issue

Body:
I'm sending a Class object from client to server side. Every time the server needs to load the Class object sent by the client instead of reusing it by parent delegation model (when it was loaded during the 1st iteration).

I'm trying to use a custom class loader on the server side whose loadClass(String) simply calls findClass() instead of checking with parent hierarchy.
To achieve this, I'm doing following:

Generate byte[] by reading the .class file on the client side as following:

Class cl = com.example.XYZ.class;
String path = cl.getName().replace('.', '/') + ".class";
InputStream is = cl.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data = -1;
while((data=is.read())!=-1)
  bos.write(data);
byte[] classBinaryData = bos.toByteArray();

I'm sending classBinaryData to the server side.

On the server side, every time I retrieve the byte[], verify if it's the same as on client side by matching MD5 checksum, then I create a new instance of my custom class loader and pass the byte array so it could be used in calling defineClass from within findClass.

However, I'm getting either of the errors (depending on the way I create byte[] out of .class)

Incompatible magic value ..... in class file <Unknown>

OR

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

I need help in figuring out the mistake in my approach/code.


问:
Function to check if parameter is still the same
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

```<code>for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}
</code>```

my problem here is to return checkifcurrent(value) if it still the same like this

```<code>function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}
</code>```

I hope you understand tysm for understanding

答:
Its not very clear about your task, i hope it is checking if the a value present in arr1 is available are not in arr2. If you so,

Loop through all elements in arr1 and check the indexof it

arr1 =[1,2,3,4];
arr2 = [2,3,4,5,6,6];
arr1.forEach((x)=>{if(arr2.indexOf(x)==-1){console.log('unable to find the element'+x)}})
unable to find the element1

Body:
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}

my problem here is to return checkifcurrent(value) if it still the same like this

function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}

I hope you understand tysm for understanding


问:
Hybrid app with remote html and local cordova.js
I have a website that I want to enhance on mobiles with a hybrid app.  Ideally the app would load the remote site over http but load the platform specific code locally.  I've tried to set up a Cordova project to do this but am having lots of trouble.  Cordova 4.3.1, Cordova Android 3.7.2 on a Nexus 7 Android 4.4.4 has been my environment.  (The google maps plugin is for Cordova Android < 4.)

If I try to load file:///android_assets/www/cordova.js from an http site, chromium says Not allowed to load local resource.  I tried to set up a local URL scheme but don't know what android-specific code to put where.

Is this the right way to make a hybrid app?  Is there a cordova plugin to allow loading file: from http:?

I also tried using an iframe and passing messages to indicate cordova is enabled and which plugins are installed, but I don't want to deal with having the http server re-serve the same js files that are already available locally.

I also thought to download the website and access it over file: but I imagine I will have the same problem trying to access http resources.

答:
I am able to load local cordova.js on remote html using cordova-plugin-file (cdvfile://) plugin .

Add cordova-plugin-file plugin to your cordova project
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Confirm cdvfile URI for cordova.js using below sample code(Android example)

    checkCordovaJSPath('file:///android_asset/www/cordova.js');

    function checkCordovaJSPath(jsUri) {
            window.resolveLocalFileSystemURL(jsUri, function success(fileEntry){
                console.log("got cordova.js file: " + fileEntry.fullPath);
                console.log('cordova.js cdvfile URI: ' + fileEntry.toInternalURL());

    });
    }```
</div>
</div>
</p>

<ol start="3">
<li>Load <code>cordova.js</code> using <code>cdvfile://localhost</code> on remote html.</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><script type="text/javascript" src="cdvfile://localhost/assets/www/cordova.js"/></code>```

Body:
I am able to load local cordova.js on remote html using cordova-plugin-file (cdvfile://) plugin .

Add cordova-plugin-file plugin to your cordova project
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Confirm cdvfile URI for cordova.js using below sample code(Android example)

    checkCordovaJSPath('file:///android_asset/www/cordova.js');

    function checkCordovaJSPath(jsUri) {
            window.resolveLocalFileSystemURL(jsUri, function success(fileEntry){
                console.log("got cordova.js file: " + fileEntry.fullPath);
                console.log('cordova.js cdvfile URI: ' + fileEntry.toInternalURL());

    });
    }

Load cordova.js using cdvfile://localhost on remote html.

<script type="text/javascript" src="cdvfile://localhost/assets/www/cordova.js"/>


问:
"Unable to autoload constant" using rspec but not rails
I've this file which I would like to test.

app/workers/station/http.rb

```<code>module Worker
  module Station
    class HTTP
      # ...
    end
  end
end
</code>```

This is my spec file.

spec/workers/station/http_spec.rb

```<code>describe Worker::Station::HTTP do
  it "should do something"  do
  end
end
</code>```

The problem now is that I'm getting the following error when running the spec file using rspec.

rspec spec/workers/station/http_spec.rb

```<code>/Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:464:in `load_missing_constant': Unable to autoload constant Station::HTTP, expected app/workers/station/http.rb to define it (LoadError)
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:184:in `const_missing'
  from spec/workers/station/http_spec.rb:3:in `<top (required)>'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `block in load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:214:in `load_dependency'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `block in load_spec_files'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `each'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `load_spec_files'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/command_line.rb:22:in `run'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:80:in `run'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:17:in `block in autorun'
  from /Users/linus/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  from /Users/linus/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
</code>```

The strange thing is that everyting works in the console.

    $ rails c
    [1] pry(main)> Worker::Station::HTTP
    => Worker::Station::HTTP

Why is this happening using rspec and not in rails and how would I fix it?

I'm using

rails (4.0.4)

rspec (2.14.1)

答:
As jfornoff suggests you could add a require statement to the spec with a statement something like the following:

require "app/workers/station/http"

But if you are using the Spring Rails application preloader and the above doesn't resolve the problem, you could also check to see if Spring needs to be restarted. You can test running the spec without using Spring as follows:

bundle exec rspec spec/workers/station/http_spec.rb

... or ...

```<code>spring stop # or bin/spring stop
rspec spec/workers/station/http_spec.rb
</code>```

Body:
I've this file which I would like to test.

app/workers/station/http.rb

module Worker
  module Station
    class HTTP
      # ...
    end
  end
end

This is my spec file.

spec/workers/station/http_spec.rb

describe Worker::Station::HTTP do
  it "should do something"  do
  end
end

The problem now is that I'm getting the following error when running the spec file using rspec.

rspec spec/workers/station/http_spec.rb

/Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:464:in `load_missing_constant': Unable to autoload constant Station::HTTP, expected app/workers/station/http.rb to define it (LoadError)
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:184:in `const_missing'
  from spec/workers/station/http_spec.rb:3:in `<top (required)>'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `block in load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:214:in `load_dependency'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/activesupport-4.0.4/lib/active_support/dependencies.rb:223:in `load'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `block in load_spec_files'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `each'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `load_spec_files'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/command_line.rb:22:in `run'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:80:in `run'
  from /Users/linus/.rvm/gems/ruby-2.0.0-p247@global/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:17:in `block in autorun'
  from /Users/linus/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  from /Users/linus/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'

The strange thing is that everyting works in the console.

    $ rails c
    [1] pry(main)> Worker::Station::HTTP
    => Worker::Station::HTTP

Why is this happening using rspec and not in rails and how would I fix it?

I'm using

rails (4.0.4)

rspec (2.14.1)

Body:
As jfornoff suggests you could add a require statement to the spec with a statement something like the following:

require "app/workers/station/http"

But if you are using the Spring Rails application preloader and the above doesn't resolve the problem, you could also check to see if Spring needs to be restarted. You can test running the spec without using Spring as follows:

bundle exec rspec spec/workers/station/http_spec.rb

... or ...

spring stop # or bin/spring stop
rspec spec/workers/station/http_spec.rb


问:
Unable to use webpack alias with Jest testing - Invariant Violation: Target container is not a DOM element
I've created a new repo that replicates this problem found here: https://github.com/davidRoussov/jest-webpack-alias

It's a React app bootstrapped using create-react-app, but it has been ejected. The error I'm getting when I run npm run test is this:

```<code>FAIL  src\components\Parent.test.js
● Test suite failed to run

Invariant Violation: Target container is not a DOM element.

  at invariant (node_modules/fbjs/lib/invariant.js:42:15)
  at Object.<anonymous> (src/index.js:7:20)
  at Object.<anonymous> (src/components/Parent.js:2:14)
  at Object.<anonymous> (src/components/Parent.test.js:2:15)
  at process._tickCallback (internal/process/next_tick.js:103:7)
</code>```

The component being tested, Parent.js:

```<code>import React, { Component } from 'react';
import Child from '@/components/Child';

class Parent extends Component {
  render() {
    return (
      <div>
        <Child/>
      </div>
    );
  }
}

export default Parent;
</code>```

The test, Parent.test.js:

```<code>import React from 'react';
import Parent from './Parent';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer.create(
      <Parent/>
  ).toJSON();
  expect(tree).toMatchSnapshot();
});
</code>```

For the webpack config I've only added:

```<code>function resolve(dir) {
  return path.join(__dirname, '..', dir)
}
</code>```

And:

```<code>alias: {

  // Support React Native Web
  // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  'react-native': 'react-native-web',
  '@': resolve('src')
},
</code>```

The Jest config:

```<code>  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.js?(x)",
      "<rootDir>/src/**/?(*.)(spec|test).js?(x)"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
    ],
    "moduleDirectories": ["node_modules"],
    "modulePaths": ["src"],
    "moduleNameMapper": {
      "^@(.*)$": "<rootDir>/src",
      "^react-native$": "react-native-web"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ]
  },
</code>```

Jest does not produce errors if import Child from '@/components/Child'; is replaced with import Child from './Child';

答:
I hope it's not too late, you forgot to substitute the captured regex groups in the path , like so:

```<code>"moduleNameMapper": {
  "^@(.*)$": "<rootDir>/src/$1",
},
</code>```

Link to the documentation

Body:
I've created a new repo that replicates this problem found here: https://github.com/davidRoussov/jest-webpack-alias

It's a React app bootstrapped using create-react-app, but it has been ejected. The error I'm getting when I run npm run test is this:

FAIL  src\components\Parent.test.js
● Test suite failed to run

Invariant Violation: Target container is not a DOM element.

  at invariant (node_modules/fbjs/lib/invariant.js:42:15)
  at Object.<anonymous> (src/index.js:7:20)
  at Object.<anonymous> (src/components/Parent.js:2:14)
  at Object.<anonymous> (src/components/Parent.test.js:2:15)
  at process._tickCallback (internal/process/next_tick.js:103:7)

The component being tested, Parent.js:

import React, { Component } from 'react';
import Child from '@/components/Child';

class Parent extends Component {
  render() {
    return (

        <Child/>

    );
  }
}

export default Parent;

The test, Parent.test.js:

import React from 'react';
import Parent from './Parent';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer.create(
      <Parent/>
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

For the webpack config I've only added:

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

And:

alias: {

  // Support React Native Web
  // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  'react-native': 'react-native-web',
  '@': resolve('src')
},

The Jest config:

  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.js?(x)",
      "<rootDir>/src/**/?(*.)(spec|test).js?(x)"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
    ],
    "moduleDirectories": ["node_modules"],
    "modulePaths": ["src"],
    "moduleNameMapper": {
      "^@(.*)$": "<rootDir>/src",
      "^react-native$": "react-native-web"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ]
  },

Jest does not produce errors if import Child from '@/components/Child'; is replaced with import Child from './Child';

Body:
I hope it's not too late, you forgot to substitute the captured regex groups in the path , like so:

"moduleNameMapper": {
  "^@(.*)$": "<rootDir>/src/$1",
},

Link to the documentation