问:
creating an image with multiple elements in PHP
I have an array of objects ( image, text or rectangle) and I'm trying to create an image out of them. But it seems to me that whenever I insert one of the elements, the previous elements get wiped out. here is my code :

```<code>if(isset($_GET['elements'])){
    $elements = json_decode(stripslashes($_GET['elements']));
    $gfx = imagecreate(160,120);
    $width = 160;
    $height = 120;
    $white = imagecolorallocate($gfx, 255, 255, 255);
    $id = $_GET['id'];
    $username=$_GET['username'];
    $name=$_GET['name'];
    foreach ($elements as $element){
        $type = $element->type;
        switch($type){
            case 'textBox':
                text_thumb( $element,$gfx);
                break;
            case 'image':
            image_thumb( $element,$gfx,$name,$username);
            break;
            case 'rectangle':
                box_thumb( $element,$gfx);
                break;
        }
    }
    header('Content-type: image/png');
    imagepng($gfx,'../thumbnail/'.$username.'_'.$name.'_'.$id.'.png');

}

function text_thumb ($element,$gfx){
    function wrap($fontSize, $angle, $fontFace, $string, $width){
        $ret = "";
        $arr = explode(' ', $string);
        foreach ( $arr as $word ){
            $teststring = $ret.' '.$word;
            $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
            if ( $testbox[4]-$testbox[0] > $width ){
                $ret.=($ret==""?"":"\n").$word;
            } else {
                $ret.=($ret==""?"":' ').$word;
            }
        }
        return $ret;
    }
    $width = $element->width/5;
    $left =$element->left/5;
    $top =$element->top/5;
    $string = $element->text;
    $fontsize = 2.4;
    $font = "../fonts/arial.TTF";
    $fonth = imagefontheight($fontsize);
    $text = wrap($fontsize, 0, $font, $string, $width);
    imagettftext($gfx,$fontsize,0,$left,$top,$black,$font,$text);
}

function box_thumb ($element,$gfx){
    $width = $element->width/5;
    $height = $element->height/5;
    $left =$element->left/5;
    $top =$element->top/5;
    $x2=$left+$width;
    $y2=$top+$height;
    $black = imagecolorallocate($gfx, 0, 0, 0);
    imagefilledrectangle($gfx,$left, $top,$x2,$y2,$black);
}

function image_thumb ($element,$gfx,$name,$username){
    $height = $element->height;
    $width = $element->width;
    $left =$element->left/5;
    $top =$element->top/5;
    $src =$element->src;
    $extype = explode(".", $src);
    $type=$extype[1];
    if($type=="jpg"||$type=="JPG")$type="jpeg";
    $creat="imagecreatefrom".$type;
    $insert=$creat("../user_pics/view/{$username}_{$name}_{$src}");
    imagecopyresampled($gfx, $insert, $left, $top, 0, 0, $width/5, $height/5, $width, $height);
}
</code>```

The code is used as a webservice, here is an example of the $elements array:

```<code>Array
(
    [0] =>
    [1] =>
    [2] =>
    [3] =>
    [4] =>
    [5] =>
    [6] =>
    [7] => stdClass Object
        (
            [src] => 019.png
            [id] => 7
            [type] => image
            [width] => 635
            [height] => 205
            [top] => 395
            [left] => 84
            [page] => 2
        )

    [8] => stdClass Object
        (
            [type] => rectangle
            [top] => 33
            [left] => 90
            [page] => 2
            [width] => 602
            [height] => 128
            [id] => 8
        )

    [9] => stdClass Object
        (
            [type] => textBox
            [top] => 182
            [left] => 171
            [page] => 2
            [width] => 539
            [height] => 154
            [id] => 9
            [text] => SINA
        )

)
</code>```

do I have to use imagecopymerge or is there any easier way, considering that I have a variable number of elements in the image ?

***UPDATE :

I figured that if I remove the "case 'image': ..." part , i.e. just creating it from box and text it works fine, and also if I have multiple images in my array, it includes all of them correctly, so could it be because of "imagecopyresampled" ?

答:
Alright I figured it, it was working as Frode said, but the problem was that it didn't pass the colors to the functions for some reason, so it would draw the box, but in white, and because the background was white as well, you could see the box, so I changed the code to this :

```<code>if(isset($_GET['elements'])){
    $elements = json_decode(stripslashes($_GET['elements']));
    $gfx = imagecreate(160,120);
    $width = 160;
    $height = 120;
    $white = imagecolorallocate($gfx, 255, 255, 255);
    $black = imagecolorallocate($gfx, 0, 0, 0);
    $id = $_GET['id'];
    $username=$_GET['username'];
    $name=$_GET['name'];
    foreach ($elements as $element){
        $type = $element->type;
        switch($type){
            case 'textBox':
                text_thumb( $element,$gfx,$white);
                break;
            case 'image':
                image_thumb( $element,$gfx,$name,$username);
                break;
            case 'rectangle':
                box_thumb( $element,$gfx,$black);
                break;
        }
    }
    header('Content-type: image/png');
    imagepng($gfx,'../thumbnail/'.$username.'_'.$name.'_'.$id.'.png');
}
</code>```

and the rest pretty is much the same ...

Body:
I have an array of objects ( image, text or rectangle) and I'm trying to create an image out of them. But it seems to me that whenever I insert one of the elements, the previous elements get wiped out. here is my code :

if(isset($_GET['elements'])){
    $elements = json_decode(stripslashes($_GET['elements']));
    $gfx = imagecreate(160,120);
    $width = 160;
    $height = 120;
    $white = imagecolorallocate($gfx, 255, 255, 255);
    $id = $_GET['id'];
    $username=$_GET['username'];
    $name=$_GET['name'];
    foreach ($elements as $element){
        $type = $element->type;
        switch($type){
            case 'textBox':
                text_thumb( $element,$gfx);
                break;
            case 'image':
            image_thumb( $element,$gfx,$name,$username);
            break;
            case 'rectangle':
                box_thumb( $element,$gfx);
                break;
        }
    }
    header('Content-type: image/png');
    imagepng($gfx,'../thumbnail/'.$username.'_'.$name.'_'.$id.'.png');

}

function text_thumb ($element,$gfx){
    function wrap($fontSize, $angle, $fontFace, $string, $width){
        $ret = "";
        $arr = explode(' ', $string);
        foreach ( $arr as $word ){
            $teststring = $ret.' '.$word;
            $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
            if ( $testbox[4]-$testbox[0] > $width ){
                $ret.=($ret==""?"":"\n").$word;
            } else {
                $ret.=($ret==""?"":' ').$word;
            }
        }
        return $ret;
    }
    $width = $element->width/5;
    $left =$element->left/5;
    $top =$element->top/5;
    $string = $element->text;
    $fontsize = 2.4;
    $font = "../fonts/arial.TTF";
    $fonth = imagefontheight($fontsize);
    $text = wrap($fontsize, 0, $font, $string, $width);
    imagettftext($gfx,$fontsize,0,$left,$top,$black,$font,$text);
}

function box_thumb ($element,$gfx){
    $width = $element->width/5;
    $height = $element->height/5;
    $left =$element->left/5;
    $top =$element->top/5;
    $x2=$left+$width;
    $y2=$top+$height;
    $black = imagecolorallocate($gfx, 0, 0, 0);
    imagefilledrectangle($gfx,$left, $top,$x2,$y2,$black);
}

function image_thumb ($element,$gfx,$name,$username){
    $height = $element->height;
    $width = $element->width;
    $left =$element->left/5;
    $top =$element->top/5;
    $src =$element->src;
    $extype = explode(".", $src);
    $type=$extype[1];
    if($type=="jpg"||$type=="JPG")$type="jpeg";
    $creat="imagecreatefrom".$type;
    $insert=$creat("../user_pics/view/{$username}_{$name}_{$src}");
    imagecopyresampled($gfx, $insert, $left, $top, 0, 0, $width/5, $height/5, $width, $height);
}

The code is used as a webservice, here is an example of the $elements array:

Array
(
    [0] =>
    [1] =>
    [2] =>
    [3] =>
    [4] =>
    [5] =>
    [6] =>
    [7] => stdClass Object
        (
            [src] => 019.png
            [id] => 7
            [type] => image
            [width] => 635
            [height] => 205
            [top] => 395
            [left] => 84
            [page] => 2
        )

    [8] => stdClass Object
        (
            [type] => rectangle
            [top] => 33
            [left] => 90
            [page] => 2
            [width] => 602
            [height] => 128
            [id] => 8
        )

    [9] => stdClass Object
        (
            [type] => textBox
            [top] => 182
            [left] => 171
            [page] => 2
            [width] => 539
            [height] => 154
            [id] => 9
            [text] => SINA
        )

)

do I have to use imagecopymerge or is there any easier way, considering that I have a variable number of elements in the image ?

***UPDATE :

I figured that if I remove the "case 'image': ..." part , i.e. just creating it from box and text it works fine, and also if I have multiple images in my array, it includes all of them correctly, so could it be because of "imagecopyresampled" ?

Body:
Alright I figured it, it was working as Frode said, but the problem was that it didn't pass the colors to the functions for some reason, so it would draw the box, but in white, and because the background was white as well, you could see the box, so I changed the code to this :

if(isset($_GET['elements'])){
    $elements = json_decode(stripslashes($_GET['elements']));
    $gfx = imagecreate(160,120);
    $width = 160;
    $height = 120;
    $white = imagecolorallocate($gfx, 255, 255, 255);
    $black = imagecolorallocate($gfx, 0, 0, 0);
    $id = $_GET['id'];
    $username=$_GET['username'];
    $name=$_GET['name'];
    foreach ($elements as $element){
        $type = $element->type;
        switch($type){
            case 'textBox':
                text_thumb( $element,$gfx,$white);
                break;
            case 'image':
                image_thumb( $element,$gfx,$name,$username);
                break;
            case 'rectangle':
                box_thumb( $element,$gfx,$black);
                break;
        }
    }
    header('Content-type: image/png');
    imagepng($gfx,'../thumbnail/'.$username.'_'.$name.'_'.$id.'.png');
}

and the rest pretty is much the same ...


来源: stackexchange

问:
Why is the extension of my ini files nothing?
I have a procedure to save a file, which is an ini file. The procedure below is just where the user chooses the directory and name of the file:

```<code>procedure TForm1.SaveFile(Sender: TObject);
var
  Dialog : TSaveDialog;
begin
  Dialog := TSaveDialog.Create(self);
  try
    //dialog properties go here
    Dialog.Filter := 'Title (*.ini)|*.ini';
    Dialog.Options := Dialog.Options + [ofOverwritePrompt];
    if Dialog.Execute then
    begin
      //any saving procedures go here if required

      ShowMessage('File saved: ' + Dialog.FileName);
    end
  else
      ShowMessage('Save file was cancelled');
  finally
    Dialog.Free;
  end;
end;
</code>```

As you can see I set the filter to ini but no files show at all (it still saves)
The procedure below is where the user can select a previously saved file

```<code>procedure TForm1.LoadFileBtnClick(Sender: TObject);
Var
FileName, FileExtension : String;
SelectedFile : TOpenDialog;
begin
SelectedFile := TOpenDialog.Create(nil);
Try
  if SelectedFile.Execute() then
   FileName := SelectedFile.FileName
   else
   //Do whatever here if user doesn't select file
Finally
  SelectedFile.Free;  //Free dialog from memory

End;
  FileExtension := ExtractFileExt(FileName);

  if not (FileExtension = 'ini') then
    exit
    else
//Do whatever here if file extension matches specified type
end;
</code>```

I get the extension of the filename and check if its ini. The ShowMessage is there to see what value is returned for testing purposes. When i click an ini file nothing is returned but when i click a text file '.txt' is returned. Why do my ini files save with the type as 'File' when they are ini files.

How could i change my load file procedure to detect if its an ini file and if not then exit?

答:
I think you are assuming that the fact that you are specifying the SaveDialog's Filter as you do forces the SaveDialog's FileName to have an extension of 'Ini'.  It does not.  The dialog's Filter property determines what files are listed in it, not the extension that the saved file has.

Try the following code:

```<code>if SaveDialog.Execute then
begin
  SaveSeatingPlan(SaveDialog.FileName);
  Assert(SameText(ExtractFileExt(SaveDialog.FileName), '.Ini'));
  ShowMessage('File saved: ' + SaveDialog.FileName);
end else
  ShowMessage('Save file was cancelled');
</code>```

Instead of the Assert, you can of course append the '.Ini' extension in your code or, better, do what the other answer suggests.

ContentLicense: CC BY-SA 3.0

Body:
I have a procedure to save a file, which is an ini file. The procedure below is just where the user chooses the directory and name of the file:

procedure TForm1.SaveFile(Sender: TObject);
var
  Dialog : TSaveDialog;
begin
  Dialog := TSaveDialog.Create(self);
  try
    //dialog properties go here
    Dialog.Filter := 'Title (*.ini)|*.ini';
    Dialog.Options := Dialog.Options + [ofOverwritePrompt];
    if Dialog.Execute then
    begin
      //any saving procedures go here if required

      ShowMessage('File saved: ' + Dialog.FileName);
    end
  else
      ShowMessage('Save file was cancelled');
  finally
    Dialog.Free;
  end;
end;

As you can see I set the filter to ini but no files show at all (it still saves)
The procedure below is where the user can select a previously saved file

procedure TForm1.LoadFileBtnClick(Sender: TObject);
Var
FileName, FileExtension : String;
SelectedFile : TOpenDialog;
begin
SelectedFile := TOpenDialog.Create(nil);
Try
  if SelectedFile.Execute() then
   FileName := SelectedFile.FileName
   else
   //Do whatever here if user doesn't select file
Finally
  SelectedFile.Free;  //Free dialog from memory

End;
  FileExtension := ExtractFileExt(FileName);

  if not (FileExtension = 'ini') then
    exit
    else
//Do whatever here if file extension matches specified type
end;

I get the extension of the filename and check if its ini. The ShowMessage is there to see what value is returned for testing purposes. When i click an ini file nothing is returned but when i click a text file '.txt' is returned. Why do my ini files save with the type as 'File' when they are ini files.

How could i change my load file procedure to detect if its an ini file and if not then exit?

Body:
I think you are assuming that the fact that you are specifying the SaveDialog's Filter as you do forces the SaveDialog's FileName to have an extension of 'Ini'.  It does not.  The dialog's Filter property determines what files are listed in it, not the extension that the saved file has.

Try the following code:

if SaveDialog.Execute then
begin
  SaveSeatingPlan(SaveDialog.FileName);
  Assert(SameText(ExtractFileExt(SaveDialog.FileName), '.Ini'));
  ShowMessage('File saved: ' + SaveDialog.FileName);
end else
  ShowMessage('Save file was cancelled');

Instead of the Assert, you can of course append the '.Ini' extension in your code or, better, do what the other answer suggests.


问:
Bootstrap grid items get aligned wrongly on next line
I'm using the Bootstrap grid to display a page of products which are dinamically added to it. Each product has a col-md-3 class and there are 4 products per row. The problem is that when the row is full and a new product is added (hence having to start a new row), the product does not get placed at the beginning of the new row, but somewhere else (either second or third position). You can [see here a screenshot][1] showing the problem.

答:
```<code><div class= "row">
    <div class="col-xs-6 col-md-3">

   <a href="/collections/summer-collection/products/another-skirt" class="grid__image">
  <div class="my-reveal">
  <img src="//cdn.shopify.com/s/files/1/1698/6183/products/DSC_0345_123483_large.jpg?v=1486835408" alt="Another Skirt">
  <img class="hidden" src="//cdn.shopify.com/s/files/1/1698/6183/products/DSC_0353_123483_large.jpg?v=1486835408" alt="Another Skirt">
  </div>
  </a>

   <p class="h4 front-title">
     <a href="/collections/summer-collection/products/another-skirt">Another Skirt</a>
    </p>
    <p>
    <span class="visually-hidden">Regular price</span>
    <br><s>440,00 lei</s>
    </p>

   </div>
</div>
</code>```


问:
angular2 with restful service

I am trying RESTful service with my Angular2 application.
It is working when I give local json url (/app/config.json). But it is not working when I try with below url.

URL : http://localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/get

The above url will return json value as below,

{
  "title": "SingerName",
  "singer": "Singer123",
  "id": "1",
  "name": "Hero123"
}
```

<p><strong>app.module</strong></p>

<pre class="lang-ts prettyprint-override"><code>@NgModule({
  declarations: [  AppComponent,HeroListComponent,HeroDetailComponent],
  imports: [BrowserModule,HttpModule,routing],  bootstrap: [AppComponent]
})
</code>```

HeroService.ts

getHeroes(){
  var headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  return this._http.request("localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/…) .map((res:Response) => res.json());
}
```

<p><strong>HeroListComponent</strong></p>

<pre class="lang-ts prettyprint-override"><code>@Component({
   selector: 'my-hero-detail',
   template: `
      <h2>Hero List Component</h2>
      <ul *ngFor="let hero of heroes">
         {{hero}}
        <li>{{hero.id}}</li>
        <li>{{hero.name}}</li>
     </ul>`
})
export class HeroListComponent implements  OnInit {
  heroes = [];

  constructor(private _heroService:HeroService) {}

  ngOnInit(){
    this._heroService.getHeroes().
       .subscribe(response =>this.heroes = response);
      }
  }
</code>```

答:
If what is returned is:

```<code>{ "title": "SingerName", "singer": "Singer123", "id": "1", "name": "Hero123" }
</code>```

This means this is an Object, and not an array you can iterate through in your template.

So maybe change the variable name to just hero, since it's an object and not an array, but this is just a detail ;) Here I'll use heroes though:

```<code>ngOnInit(){
  this._heroService.getHeroes().
     subscribe(response => this.heroes = response);
}
</code>```

Then you do not need to iterate the response, just display it like so:

```<code><div>
  {{heroes?.id}}
  {{heroes?.name}}
</div>
</code>```

And it's useful to use the safe navigation operator :)

Hope this helps!

Title: angular2 with restful service

Body:
I am trying RESTful service with my Angular2 application.
It is working when I give local json url (/app/config.json). But it is not working when I try with below url.

URL : http://localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/get

The above url will return json value as below,

{
  "title": "SingerName",
  "singer": "Singer123",
  "id": "1",
  "name": "Hero123"
}

app.module

@NgModule({
  declarations: [  AppComponent,HeroListComponent,HeroDetailComponent],
  imports: [BrowserModule,HttpModule,routing],  bootstrap: [AppComponent]
})

HeroService.ts

getHeroes(){
  var headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });
  return this._http.request("localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/…) .map((res:Response) => res.json());
}

HeroListComponent

@Component({
   selector: 'my-hero-detail',
   template: `

Hero List Component

         {{hero}}

{{hero.id}}

{{hero.name}}

`
})
export class HeroListComponent implements  OnInit {
  heroes = [];

  constructor(private _heroService:HeroService) {}

  ngOnInit(){
    this._heroService.getHeroes().
       .subscribe(response =>this.heroes = response);
      }
  }

Body:
If what is returned is:

{ "title": "SingerName", "singer": "Singer123", "id": "1", "name": "Hero123" }

This means this is an Object, and not an array you can iterate through in your template.

So maybe change the variable name to just hero, since it's an object and not an array, but this is just a detail ;) Here I'll use heroes though:

ngOnInit(){
  this._heroService.getHeroes().
     subscribe(response => this.heroes = response);
}

Then you do not need to iterate the response, just display it like so:

<div>
  {{heroes?.id}}
  {{heroes?.name}}
</div>

And it's useful to use the safe navigation operator :)

Hope this helps!


问:
NSLayoutConstraint re-activates by itself
I created a strong constraint for a UILabel in a .xib file and an outlet for it.

In my code, I set self.constraint.active = NO, but after the application loads, when I open the Debug View Hierarchy, the same constraint is active.

I tried setting it in viewDidLoad, updateViewConstraints and viewDidLayoutSubviews to no avail.

I also created a NSLayoutConstraint subclass, overwrote the setActive: method and put a breakpoint in it, but only my code triggered it.

答:
When playing with constraints I advise to do it as late as possible. Depending on your case, it might be as early as viewDidLoad.

Whatever you end up doing, you can force a refresh with a layoutIfNeeded call.

You could, if I'm not mistaken, disable your constraint and then force an update of constraints / layout ( updateConstraints setNeedsLayout) and then call layoutIfNeeded. But I think you only need to modify your constraint and doing so will automatically set your view to relayout itself whenever it has the time OR when you call layoutIfNeeded.

Either way, try with just these two lines, otherwise, add the ones I put between parenthesis.

I'm not gonna lie, sometimes constraints are part iOS, part skill, part black magic.


问:
ui-grid ng-style dynamic height
I got a simple grid used like this :

```<code> <div id="planningGridDiv"
    class="gridPatientContent"

    style="height: 450px;min-height: 300px;"

    ng-style="{height: showScores ? '150px': '450px'}"

    ui-grid-resize-columns
    ui-grid-selection
    ui-grid-cellNav
    ui-grid-pinning

    ui-grid="myData"
    class="grid">

  </div>
</code>```

But when showScores is true and height pass from 450 to 150 px, the grid itself doesn't shrink.

The first container see its height changed, but this part no :

```<code><div role="grid" ui-grid-one-bind-id-grid="'grid-container'" class="ui-grid-render-container ng-isolate-scope ui-grid-render-container-body" ng-style="{ 'margin-left': colContainer.getMargin('left') + 'px', 'margin-right': colContainer.getMargin('right') + 'px' }" ui-grid-render-container="" container-id="'body'" col-container-name="'body'" row-container-name="'body'" bind-scroll-horizontal="true" bind-scroll-vertical="true" enable-horizontal-scrollbar="grid.options.enableHorizontalScrollbar" enable-vertical-scrollbar="grid.options.enableVerticalScrollbar" aria-multiselectable="true" id="1490734763451-grid-container" style="margin-left: 180px; margin-right: 80px;">
</code>```

I can't find any solution on doc nor stack overflow, but it seems to me that it should. I can use some help for some pointers.

答:
FYI, I found a solution on another stackoverflow question, but I changed it a bit to fit my needs :

```<code> $scope.showScoreDiv = function()
{
    $scope.showScores = !$scope.showScores;

    $timeout(function(){
         $scope.gridApi.grid.handleWindowResize();
    }, 1);
};
</code>```

So the main idea is to change the height via ng-style on the grid div, and when you fire your event, here showScores = true called by showScoreDiv(), you have to call  gridApi.grid.handleWindowResize().
The timeout is just here to give some time to the div to be set to the good height before calling handleWindowResize().

Title: ui-grid ng-style dynamic height

Body:
I got a simple grid used like this :

But when showScores is true and height pass from 450 to 150 px, the grid itself doesn't shrink.

The first container see its height changed, but this part no :

<div role="grid" ui-grid-one-bind-id-grid="'grid-container'" class="ui-grid-render-container ng-isolate-scope ui-grid-render-container-body" ng-style="{ 'margin-left': colContainer.getMargin('left') + 'px', 'margin-right': colContainer.getMargin('right') + 'px' }" ui-grid-render-container="" container-id="'body'" col-container-name="'body'" row-container-name="'body'" bind-scroll-horizontal="true" bind-scroll-vertical="true" enable-horizontal-scrollbar="grid.options.enableHorizontalScrollbar" enable-vertical-scrollbar="grid.options.enableVerticalScrollbar" aria-multiselectable="true" id="1490734763451-grid-container" style="margin-left: 180px; margin-right: 80px;">

I can't find any solution on doc nor stack overflow, but it seems to me that it should. I can use some help for some pointers.

Body:
FYI, I found a solution on another stackoverflow question, but I changed it a bit to fit my needs :

 $scope.showScoreDiv = function()
{
    $scope.showScores = !$scope.showScores;

    $timeout(function(){
         $scope.gridApi.grid.handleWindowResize();
    }, 1);
};

So the main idea is to change the height via ng-style on the grid div, and when you fire your event, here showScores = true called by showScoreDiv(), you have to call  gridApi.grid.handleWindowResize().
The timeout is just here to give some time to the div to be set to the good height before calling handleWindowResize().


问:
Why isn't autotest working?
I'm trying to use autotest for Rails development. It's supposed to run my tests automatically.

Here's my setup:

```<code>$ which ruby
/usr/bin/ruby

$ ruby -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

$ rails -v
Rails 2.3.9

autotest-rails (4.1.0)
ZenTest (4.4.0)

$ echo $PATH
/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/mysql/bin:/Users/ethan/bin:/opt/local/bin:/usr/local/pgsql/bin:/usr/local/git/bin:/usr/local/oracle/instantclient_10_2
</code>```

Here's the gem environment:

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.7
  - RUBY VERSION: 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
  - INSTALLATION DIRECTORY: /Library/Ruby/Gems/1.8
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-10
  - GEM PATHS:
     - /Library/Ruby/Gems/1.8
     - /Users/ethan/.gem/ruby/1.8
     - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - :sources => ["http://gemcutter.org"]
  - REMOTE SOURCES:
     - http://gemcutter.org
</code>```

Here's the error. It looks like autotest is trying to use some other version of Ruby.

```<code>$ autotest
loading autotest/rails
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -I.:lib:test -rubygems -e "%w[test/unit test/functional/procurements_controller_test.rb].each { |f| require f }" | unit_diff -u
sh: /usr/local/bin/unit_diff: /usr/local/bin/ruby: bad interpreter: No such file or directory
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `flush': Broken pipe (Errno::EPIPE)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `output'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:51:in `setup_mediator'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:39:in `start'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278
    from -e:1
</code>```

答:
I see two things:

Your which ruby says the default is /usr/bin/ruby, but your Autotest is calling /usr/local/bin/ruby.

sh: /usr/local/bin/unit_diff: /usr/local/bin/ruby: bad interpreter: No such file or directory

Also, your path is not organized well because you have duplicated entries. I split it on ':' then sorted it to look for duplicates:

```<code>/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/opt/local/bin # <--
/opt/local/bin # <--
/opt/local/sbin
/sbin
/Users/ethan/bin
/usr/bin
/usr/local/bin # <--
/usr/local/bin # <--
/usr/local/git/bin
/usr/local/mysql/bin
/usr/local/oracle/instantclient_10_2
/usr/local/pgsql/bin
/usr/sbin
</code>```

Notice that you have duplicated /opt/local/bin and /usr/local/bin directories. Those should appear ahead of the default /usr/bin directory in order for your "personally" installed apps to be located first, so you should do some housekeeping. Once you have done that close your terminal session(s). Open a new session and try rerunning your test and see if anything has changed/improved.

The path organization is part of the problem and explains why which ruby points to the system Ruby. I suspect another part of this puzzle is that you are using #!/usr/local/bin/ruby as the "bang slash" in your scripts, or explicitly pointing to that Ruby when you call things on the command-line. That will confuse tests no end. In my scripts I use this to invoke Ruby:

```<code>#!/usr/bin/env ruby
</code>```

which works nicely because it uses whatever Ruby is defined first in my path, and with this next part...

I'm a big proponent for using RVM to manage Ruby installations on Mac OS and Linux. It makes it so you don't have to install anything in your default /usr/bin ruby or even bother with adding one in /usr/local/bin. RVM puts everything in ~/.rvm and makes it really easy to install/manage/remove Ruby versions along with their associated gems, or even blow it all away by deleting that directory. Installing RVM and Gemsets are good starting places if you want to give it a try.

ContentLicense: CC BY-SA 2.5

Title: Why isn't autotest working?

Body:
I'm trying to use autotest for Rails development. It's supposed to run my tests automatically.

Here's my setup:

$ which ruby
/usr/bin/ruby

$ ruby -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

$ rails -v
Rails 2.3.9

autotest-rails (4.1.0)
ZenTest (4.4.0)

$ echo $PATH
/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/local/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/mysql/bin:/Users/ethan/bin:/opt/local/bin:/usr/local/pgsql/bin:/usr/local/git/bin:/usr/local/oracle/instantclient_10_2

Here's the gem environment:

RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.7
  - RUBY VERSION: 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
  - INSTALLATION DIRECTORY: /Library/Ruby/Gems/1.8
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-10
  - GEM PATHS:
     - /Library/Ruby/Gems/1.8
     - /Users/ethan/.gem/ruby/1.8
     - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - :sources => ["http://gemcutter.org"]
  - REMOTE SOURCES:
     - http://gemcutter.org

Here's the error. It looks like autotest is trying to use some other version of Ruby.

$ autotest
loading autotest/rails
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -I.:lib:test -rubygems -e "%w[test/unit test/functional/procurements_controller_test.rb].each { |f| require f }" | unit_diff -u
sh: /usr/local/bin/unit_diff: /usr/local/bin/ruby: bad interpreter: No such file or directory
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `flush': Broken pipe (Errno::EPIPE)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:108:in `output'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:51:in `setup_mediator'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:39:in `start'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278
    from -e:1

Body:
I see two things:

Your which ruby says the default is /usr/bin/ruby, but your Autotest is calling /usr/local/bin/ruby.

sh: /usr/local/bin/unit_diff: /usr/local/bin/ruby: bad interpreter: No such file or directory

Also, your path is not organized well because you have duplicated entries. I split it on ':' then sorted it to look for duplicates:

/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/opt/local/bin # <--
/opt/local/bin # <--
/opt/local/sbin
/sbin
/Users/ethan/bin
/usr/bin
/usr/local/bin # <--
/usr/local/bin # <--
/usr/local/git/bin
/usr/local/mysql/bin
/usr/local/oracle/instantclient_10_2
/usr/local/pgsql/bin
/usr/sbin

Notice that you have duplicated /opt/local/bin and /usr/local/bin directories. Those should appear ahead of the default /usr/bin directory in order for your "personally" installed apps to be located first, so you should do some housekeeping. Once you have done that close your terminal session(s). Open a new session and try rerunning your test and see if anything has changed/improved.

The path organization is part of the problem and explains why which ruby points to the system Ruby. I suspect another part of this puzzle is that you are using #!/usr/local/bin/ruby as the "bang slash" in your scripts, or explicitly pointing to that Ruby when you call things on the command-line. That will confuse tests no end. In my scripts I use this to invoke Ruby:

#!/usr/bin/env ruby

which works nicely because it uses whatever Ruby is defined first in my path, and with this next part...

I'm a big proponent for using RVM to manage Ruby installations on Mac OS and Linux. It makes it so you don't have to install anything in your default /usr/bin ruby or even bother with adding one in /usr/local/bin. RVM puts everything in ~/.rvm and makes it really easy to install/manage/remove Ruby versions along with their associated gems, or even blow it all away by deleting that directory. Installing RVM and Gemsets are good starting places if you want to give it a try.


问:
PHPExcel: Read Excel File Line by Line
I need some help. What I am trying to achieve is to read Excel file line by line using PHPExcel. I am able to read the file and also get the data, but can't figure it out how to read it line by line. Here is my code.

```<code>require_once ('../src/Classes/PHPExcel.php');

    $excel_path = '../' . $_SESSION['excel_path'];

    try {
        $inputFileType = PHPExcel_IOFactory::identify($excel_path);
        $excelReader = PHPExcel_IOFactory::createReaderForFile($excel_path);
        $excelObject = $excelReader->load($excel_path);
    } catch (Exception $ex) {
        die('Error loading file"' . pathinfo($excel_path, PATHINFO_BASENAME) . '": ' . $ex->getMessage());
    }

    $sheet = $excelObject->getSheet(0);
    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();

    for ($row = 1; $row <= $highestRow; $row++) {
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn .
                $row, NULL, TRUE, FALSE);
        foreach ($rowData as $k) {
            echo $k[0].'<br />';
        }
    }
    ?
</code>```

I was that someone could help me.

答:
Try this code in place of your for loop

```<code>$rows = $sheet->rangetoArray('A1:'.$highestColumn . $highestRow, NULL, True, True, False);
foreach ($rows as $row => $cols) {
    $line = '';
    foreach($cols as $col => $cell){
        $line .= $cell." ... "; // ... or some other separator
    }
    echo rtrim($line,'. ').'<br />';
 }
</code>```

Edited To add {} around inner foreach loop

Edited: Adding 2nd option - for creating tabular data

This works for me and creates a table, using the excel sheet name as the table caption

```<code>$sheetname = $sheet->getTitle();
$start=1;
$table = "<table><caption>$sheetname</caption>";
$rows = $sheet->rangetoArray('A'.$start.':'.$highestColumn . $highestRow, NULL, True, True, False);
foreach ($rows as $row => $cols) {
    $line = '<tr class="'.$row.'">';
    foreach($cols as $col => $cell){
        $line .= "<td>".$cell."</td>"; // ... or some other separator
    }
    if($row == 0) $line = str_replace("td>","th>", $line);
    $table .= $line.'</tr>';
 }
$table .= "</table>";.

echo $table;
</code>```

Title: PHPExcel: Read Excel File Line by Line

Body:
I need some help. What I am trying to achieve is to read Excel file line by line using PHPExcel. I am able to read the file and also get the data, but can't figure it out how to read it line by line. Here is my code.

require_once ('../src/Classes/PHPExcel.php');

    $excel_path = '../' . $_SESSION['excel_path'];

    try {
        $inputFileType = PHPExcel_IOFactory::identify($excel_path);
        $excelReader = PHPExcel_IOFactory::createReaderForFile($excel_path);
        $excelObject = $excelReader->load($excel_path);
    } catch (Exception $ex) {
        die('Error loading file"' . pathinfo($excel_path, PATHINFO_BASENAME) . '": ' . $ex->getMessage());
    }

    $sheet = $excelObject->getSheet(0);
    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();

    for ($row = 1; $row <= $highestRow; $row++) {
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn .
                $row, NULL, TRUE, FALSE);
        foreach ($rowData as $k) {
            echo $k[0].'
';
        }
    }
    ?

I was that someone could help me.

Body:
Try this code in place of your for loop

$rows = $sheet->rangetoArray('A1:'.$highestColumn . $highestRow, NULL, True, True, False);
foreach ($rows as $row => $cols) {
    $line = '';
    foreach($cols as $col => $cell){
        $line .= $cell." ... "; // ... or some other separator
    }
    echo rtrim($line,'. ').'<br />';
 }

Edited To add {} around inner foreach loop

Edited: Adding 2nd option - for creating tabular data

This works for me and creates a table, using the excel sheet name as the table caption

$sheetname = $sheet->getTitle();
$start=1;
$table = "<table><caption>$sheetname</caption>";
$rows = $sheet->rangetoArray('A'.$start.':'.$highestColumn . $highestRow, NULL, True, True, False);
foreach ($rows as $row => $cols) {
    $line = '<tr class="'.$row.'">';
    foreach($cols as $col => $cell){
        $line .= "<td>".$cell."</td>"; // ... or some other separator
    }
    if($row == 0) $line = str_replace("td>","th>", $line);
    $table .= $line.'</tr>';
 }
$table .= "</table>";.

echo $table;


问:
TFS - Link to Workitem "Duplicate" versus "Duplicate Of"
In what scenario makes it sense to distinguish "Duplicate" and "Duplicate Of" as "Link type" when linking two WorkItems (WIs) in Team Foundation Server (TFS)?

How to deal with "Duplicate" relationship of more than two WIs?

I'm aware of definition:

All two-way link types are characterized by a Forward and Reverse name, such as Parent/Child and Duplicate/Duplicate Of.
  Link work items to support traceability...

and technical detail that if WI#1 is linked to WI#2 as "Duplicate" then WI#2 is linked to WI#1 as "Duplicate Of". And also that changing link from "Duplicate" to "Duplicate Of" in WI#1 automatically updates link in WI#2 to "Duplicate".

I connect from VS 2015 or 2017 to TFS 2017

答:
The most common usage is to track duplicate bugs, where the newest is a Duplicate Of an older.
This may result in a chain of duplicate bugs that ends on the oldest work item.


问:
Align fields correctly
I really need your help to correctly format/position my form fields and its labels with proper indention and margins. The labels "CATEGORY A" and "CATEGORY B" are just sample text, but actually they will be dynamically changed its content and length, so it is important to auto-wrap it before it overlaps on "Button1" and "Button2" elements.  I am using bootstrap here to make my fields responsive.

This is the actual design format that I want to achieve:

And this is the current code that I have so far.

JSFIDDLE

<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>

 Field 1

        <input class="form-control " id="main-label-1" name="main-field-1" placeholder="Number" title="Enter Value" type="text">

 Field 2

        <input class="form-control " id="main-label-2" name="main-field-2" placeholder="Number" title="Enter Value" type="text">

Other Fields

CATEGORY A <button class="btn btn-primary" style="min-width:55px;margin-right:3px;margin-bottom:3px;padding:3px" title="">Button 1</button><button class="btn btn-primary" style="min-width:55px;margin-right:3px;margin-bottom:3px;padding:3px" title="">Button 2</button>

 Field 1

        <input class="form-control " id="main-label-1" name="main-field-1" placeholder="Number" title="Enter Value" type="text">

 Field 2

        <input class="form-control " id="main-label-2" name="main-field-2" placeholder="Number" title="Enter Value" type="text">

CATEGORY B <button class="btn btn-primary" style="min-width:55px;margin-right:3px;margin-bottom:3px;padding:3px" title="">Button 1</button><button class="btn btn-primary" style="min-width:55px;margin-right:3px;margin-bottom:3px;padding:3px" title="">Button 2</button>

 Field 1

        <input class="form-control " id="main-label-1" name="main-field-1" placeholder="Number" title="Enter Value" type="text">

 Field 2

        <input class="form-control " id="main-label-2" name="main-field-2" placeholder="Number" title="Enter Value" type="text">

```

答:
You need to adjust the col size for you grid to display like you want.

Take a look at the grid documentation:

https://www.w3schools.com/bootstrap/bootstrap_grid_basic.asp

Also you have different col size for phones I'm not sure you want that.

If your question is about your first two fields to be like in the screenshot, try col-md-2 for label and col-md-10 for the field. Remember that total for a row must always be 12

Title: Align fields correctly


问:
Using index function and matching to determine a value out of range then outputting the corresponding value in the same column
I am trying to determine how to output a specific value that corresponds to a value that is out of range. I have a column (D) in excel with a normal range between 90 and 110. If there are values outside of that range I want to find the first value in column D and use the corresponding value in column A to denote the out of range value.

The formula I currently have to find the out of range value is

```<code>=(INDEX(D8:D17,MATCH(TRUE,INDEX(D8:D17>110,0),0)))
</code>```

This finds the first value that is greater that 110 however I do not know how to incorporate the <90 criteria into the formula and how to output the values from that same row from column A.

Any help would be appreciated.

答:
I prefer AGGREGATE to MATCH(INDEX()):

```<code>=INDEX(A:A,AGGREGATE(15,6,ROW($D$8:$D$18)/(($D$8:$D$18>110)+($D$8:$D$18<90)),1))
</code>```

This will find the first row in which the value in D is either greater than 110 or less than 90.

Body:
I am trying to determine how to output a specific value that corresponds to a value that is out of range. I have a column (D) in excel with a normal range between 90 and 110. If there are values outside of that range I want to find the first value in column D and use the corresponding value in column A to denote the out of range value.

The formula I currently have to find the out of range value is

=(INDEX(D8:D17,MATCH(TRUE,INDEX(D8:D17>110,0),0)))

This finds the first value that is greater that 110 however I do not know how to incorporate the <90 criteria into the formula and how to output the values from that same row from column A.

Any help would be appreciated.

Body:
I prefer AGGREGATE to MATCH(INDEX()):

=INDEX(A:A,AGGREGATE(15,6,ROW($D$8:$D$18)/(($D$8:$D$18>110)+($D$8:$D$18<90)),1))

This will find the first row in which the value in D is either greater than 110 or less than 90.


问:
Verify step in bazel
I'm looking for a good recipe to run "checks" or "verify" steps in Bazel, like go vet, gofmt, pylint, cppcheck. These steps don't create any output file. The only thing that matters is the return code (like a test).

Right now I'm using the following recipe:

```<code>sh_test(
    name = "verify-pylint",
    srcs = ["verify-pylint.sh"],
    data = ["//:all-srcs"],
)
</code>```

And verify-pylint.sh looks like this:

```<code>find . -name '*.py' | xargs pylint
</code>```

This has two problems:

The verify logic is split between the shell script and the BUILD file. Ideally I would like to have both in the same place (in the BUILD file)

Anytime one of the source file changes (in //:all-srcs), bazel test verify-pylint re-runs pylint on every single file (and that can be expensive/slow).

What is the idiomatic way in bazel to run these steps?

答:
A simple solution.

In your BUILD file:

```<code>load(":gofmt.bzl", "gofmt_test")

gofmt_test(
    name = "format_test",
    srcs = glob(["*.go"]),
)
</code>```

In gofmt.bzl:

```<code>def gofmt_test(name, srcs):
  cmd = """
    export TMPDIR=.
    out=$$(gofmt -d $(SRCS))

    if [ -n "$$out" ]; then
      echo "gmfmt failed:"
      echo "$$out"
      exit 1
    fi
    touch $@
  """
  native.genrule(
      name = name,
      cmd = cmd,
      srcs = srcs,
      outs = [name + ".out"],
      tools = ["gofmt.sh"],
  )
</code>```

Some remarks:

If your wrapper script grows, you should put it in a separate .sh file.

In the genrule command, we need $$ instead $ due to escaping (see documentation)

gofmt_test is actually not a test and will run with bazel build :all. If you really need a test, see Laszlo's example and call sh_test.

I call touch to create a file because genrule requires an output to succeed.

export TMPDIR=. is needed because by default the sandbox prevents writing in other directories.

To cache results for each file (and avoid rechecking a file that hasn't changed), you'll need to create multiple actions. See Laszlo's for loop.

To simplify the code, we could provide a generic rule. Maybe this is something we should put in a standard library.

Title: Verify step in bazel

Body:
I'm looking for a good recipe to run "checks" or "verify" steps in Bazel, like go vet, gofmt, pylint, cppcheck. These steps don't create any output file. The only thing that matters is the return code (like a test).

Right now I'm using the following recipe:

sh_test(
    name = "verify-pylint",
    srcs = ["verify-pylint.sh"],
    data = ["//:all-srcs"],
)

And verify-pylint.sh looks like this:

find . -name '*.py' | xargs pylint

This has two problems:

The verify logic is split between the shell script and the BUILD file. Ideally I would like to have both in the same place (in the BUILD file)

Anytime one of the source file changes (in //:all-srcs), bazel test verify-pylint re-runs pylint on every single file (and that can be expensive/slow).

What is the idiomatic way in bazel to run these steps?

Body:
A simple solution.

In your BUILD file:

load(":gofmt.bzl", "gofmt_test")

gofmt_test(
    name = "format_test",
    srcs = glob(["*.go"]),
)

In gofmt.bzl:

def gofmt_test(name, srcs):
  cmd = """
    export TMPDIR=.
    out=$$(gofmt -d $(SRCS))

    if [ -n "$$out" ]; then
      echo "gmfmt failed:"
      echo "$$out"
      exit 1
    fi
    touch $@
  """
  native.genrule(
      name = name,
      cmd = cmd,
      srcs = srcs,
      outs = [name + ".out"],
      tools = ["gofmt.sh"],
  )

Some remarks:

If your wrapper script grows, you should put it in a separate .sh file.

In the genrule command, we need $$ instead $ due to escaping (see documentation)

gofmt_test is actually not a test and will run with bazel build :all. If you really need a test, see Laszlo's example and call sh_test.

I call touch to create a file because genrule requires an output to succeed.

export TMPDIR=. is needed because by default the sandbox prevents writing in other directories.

To cache results for each file (and avoid rechecking a file that hasn't changed), you'll need to create multiple actions. See Laszlo's for loop.

To simplify the code, we could provide a generic rule. Maybe this is something we should put in a standard library.


问:
What is the best way to tell users of my library functions that passed variables are not of the correct type
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

```<code>function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}
</code>```

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

答:
Libraries like jQuery do not inform the user of the error.

If a function is expecting a number, and a user passes a string, the function just returns without doing anything.

That way, you will avoid JavaScript errors popping up on a live website.

PS. Just make sure to always type check your inputted parameters, to avoid JavaScript errors being thrown.

OwnerDisplayName: Pim Jager

Body:
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

LastEditorDisplayName: Mitch Wheat

OwnerDisplayName: Dreas Grech

LastEditorDisplayName: Dreas Grech


问:
Use CSS to affect an outer element
This is hard to sum up in a title, so forgive me.

Basically, here is what I have:

```<code>a img {
/ * style * /
}
</code>```

However, I want to affect the a tag in this instance. Is there any way to do so in CSS without resorting to JavaScript wizardry?

答:
You want to apply styles to the  tag only if it has an image correct? In short, using straight CSS there is no way to do that.

EDIT

BUT, if you wanted to do this w/ jquery you could do it like so:

```<code>$('a').has('img').addClass('hasImg');
</code>```

then use .hasImg as your hook

```<code>a.hasImg{background:lime;display:block;height:200px;width:200px;}
</code>```

Here's a demo on JSBin I put together (view source): http://jsbin.com/owafi4

Title: Use CSS to affect an outer element

Body:
This is hard to sum up in a title, so forgive me.

Basically, here is what I have:

a img {
/ * style * /
}

However, I want to affect the a tag in this instance. Is there any way to do so in CSS without resorting to JavaScript wizardry?

Body:
You want to apply styles to the  tag only if it has an image correct? In short, using straight CSS there is no way to do that.

EDIT

BUT, if you wanted to do this w/ jquery you could do it like so:

$('a').has('img').addClass('hasImg');

then use .hasImg as your hook

a.hasImg{background:lime;display:block;height:200px;width:200px;}

Here's a demo on JSBin I put together (view source): http://jsbin.com/owafi4


问:
IndexOutOfBoundsException when adding tables to an itext 7 pdf
I tried to create a PDF with several tables (of unknown size).
After a certain number of tables (in this example: 18), the following exception is thrown:

```<code>Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 20, Size: 20
   at java.util.ArrayList$SubList.rangeCheck(Unknown Source)
   at java.util.ArrayList$SubList.get(Unknown Source)
   at com.itextpdf.layout.renderer.CollapsedTableBorders.collapseAllBordersAndEmptyRows(CollapsedTableBorders.java:77)
   at com.itextpdf.layout.renderer.CollapsedTableBorders.updateBordersOnNewPage(CollapsedTableBorders.java:617)
   at com.itextpdf.layout.renderer.TableRenderer.layout(TableRenderer.java:248)
   at com.itextpdf.layout.renderer.RootRenderer.addChild(RootRenderer.java:111)
   at com.itextpdf.layout.RootElement.add(RootElement.java:108)
   at com.itextpdf.layout.Document.add(Document.java:143)
   at com.test.MinimalITextTest.createPdf(MinimalITextTest.java:83)
   at com.test.MinimalITextTest.main(MinimalITextTest.java:66)
</code>```

I am using the snapshot version of iText 7 (7.0.3-SNAPSHOT from March 24th).

Is there any workaround or am I just doing something wrong?

Example Code that triggers the error:

```<code>package com.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;

public class MinimalITextTest {

    private static final int numberOfColumns=8;
    private static final UnitValue[] columnWeight;
    private static final int NUMBER_OF_TABLES = 18; //Does work with 17

    static {
        float[] percentArray = new float[numberOfColumns];
        for(int i=0; i<percentArray.length;i++)
        {
            percentArray[i] = 100.0f/numberOfColumns;
        }
        columnWeight=UnitValue.createPercentArray(percentArray);
    }

    private final List<Table> tables=new ArrayList<>();
    private Table currentTable;

    public MinimalITextTest()
    {
        currentTable=new Table(columnWeight)
            .setWidthPercent(100)
            .setTextAlignment(TextAlignment.CENTER)
            .setHorizontalAlignment(HorizontalAlignment.CENTER);
        tables.add(currentTable);
    }

    public static void main(String[] args) throws IOException
    {
        final char[] charArray="Minimal Example".toCharArray();
        final MinimalITextTest test = new MinimalITextTest();
        for(int k=0;k<NUMBER_OF_TABLES;k++)
        {
            for(int i=0;i<10;i++)
            {
                CellElement[] cellElement=new CellElement[charArray.length];
                for(int j=0;j<charArray.length;j++)
                {
                    cellElement[j] = new CellElement(String.valueOf(charArray[j]));
                }
                test.createRow(cellElement);
            }
            test.createNewTable();
        }
        test.createPdf("Minimal_test.pdf");
    }

    private void createNewTable() {
        currentTable=new Table(columnWeight)
            .setWidthPercent(100)
            .setTextAlignment(TextAlignment.CENTER)
            .setHorizontalAlignment(HorizontalAlignment.CENTER);
        tables.add(currentTable);
    }

    public void createPdf(String destinationFile) throws IOException {
        PdfWriter pw = new PdfWriter(new FileOutputStream(destinationFile));

        Document document = new Document(new PdfDocument(pw));
        for(Table t : tables)
        {
            document.add(t);
        }
        document.close();
    }

    public void createRow(CellElement... cells)
    {
        boolean addedACell=false;
        for(CellElement currentCell : cells)
        {
            if(currentCell==null)
            {
                continue;
            }
            addedACell = true;
            Cell cell = new Cell();
            cell.add(new Paragraph(currentCell.getText()))
                .setBorder(new SolidBorder(Color.BLACK, 0.5f))
                .setBackgroundColor(currentCell.getBackgroundColor());
            currentTable.addCell(cell);
        }
        if(addedACell)
        {
            currentTable.startNewRow();
        }
    }

    public static class CellElement
    {
        private final String text;
        private final Color color;

        public CellElement()
        {
            this.text = "";
            this.color = Color.WHITE;
        }

        public CellElement(String text)
        {
            this.text = text;
            this.color = Color.WHITE;
        }

        public CellElement(String text, Color color)
        {
            this.text = text;
            this.color = color;
        }

        public String getText() {
            return text;
        }

        public Color getBackgroundColor() {
            return color;
        }

    }
}
</code>```

答:
Hi and thanks for the question.

The problem was fixed. You can find changes in our snapshot version7.0.3-SNAPSHOT.

Body:
I tried to create a PDF with several tables (of unknown size).
After a certain number of tables (in this example: 18), the following exception is thrown:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 20, Size: 20
   at java.util.ArrayList$SubList.rangeCheck(Unknown Source)
   at java.util.ArrayList$SubList.get(Unknown Source)
   at com.itextpdf.layout.renderer.CollapsedTableBorders.collapseAllBordersAndEmptyRows(CollapsedTableBorders.java:77)
   at com.itextpdf.layout.renderer.CollapsedTableBorders.updateBordersOnNewPage(CollapsedTableBorders.java:617)
   at com.itextpdf.layout.renderer.TableRenderer.layout(TableRenderer.java:248)
   at com.itextpdf.layout.renderer.RootRenderer.addChild(RootRenderer.java:111)
   at com.itextpdf.layout.RootElement.add(RootElement.java:108)
   at com.itextpdf.layout.Document.add(Document.java:143)
   at com.test.MinimalITextTest.createPdf(MinimalITextTest.java:83)
   at com.test.MinimalITextTest.main(MinimalITextTest.java:66)

I am using the snapshot version of iText 7 (7.0.3-SNAPSHOT from March 24th).

Is there any workaround or am I just doing something wrong?

Example Code that triggers the error:

package com.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;

public class MinimalITextTest {

    private static final int numberOfColumns=8;
    private static final UnitValue[] columnWeight;
    private static final int NUMBER_OF_TABLES = 18; //Does work with 17

    static {
        float[] percentArray = new float[numberOfColumns];
        for(int i=0; i<percentArray.length;i++)
        {
            percentArray[i] = 100.0f/numberOfColumns;
        }
        columnWeight=UnitValue.createPercentArray(percentArray);
    }

    private final List
 tables=new ArrayList<>();
    private Table currentTable;

    public MinimalITextTest()
    {
        currentTable=new Table(columnWeight)
            .setWidthPercent(100)
            .setTextAlignment(TextAlignment.CENTER)
            .setHorizontalAlignment(HorizontalAlignment.CENTER);
        tables.add(currentTable);
    }

    public static void main(String[] args) throws IOException
    {
        final char[] charArray="Minimal Example".toCharArray();
        final MinimalITextTest test = new MinimalITextTest();
        for(int k=0;k<NUMBER_OF_TABLES;k++)
        {
            for(int i=0;i<10;i++)
            {
                CellElement[] cellElement=new CellElement[charArray.length];
                for(int j=0;j<charArray.length;j++)
                {
                    cellElement[j] = new CellElement(String.valueOf(charArray[j]));
                }
                test.createRow(cellElement);
            }
            test.createNewTable();
        }
        test.createPdf("Minimal_test.pdf");
    }

    private void createNewTable() {
        currentTable=new Table(columnWeight)
            .setWidthPercent(100)
            .setTextAlignment(TextAlignment.CENTER)
            .setHorizontalAlignment(HorizontalAlignment.CENTER);
        tables.add(currentTable);
    }

    public void createPdf(String destinationFile) throws IOException {
        PdfWriter pw = new PdfWriter(new FileOutputStream(destinationFile));

        Document document = new Document(new PdfDocument(pw));
        for(Table t : tables)
        {
            document.add(t);
        }
        document.close();
    }

    public void createRow(CellElement... cells)
    {
        boolean addedACell=false;
        for(CellElement currentCell : cells)
        {
            if(currentCell==null)
            {
                continue;
            }
            addedACell = true;
            Cell cell = new Cell();
            cell.add(new Paragraph(currentCell.getText()))
                .setBorder(new SolidBorder(Color.BLACK, 0.5f))
                .setBackgroundColor(currentCell.getBackgroundColor());
            currentTable.addCell(cell);
        }
        if(addedACell)
        {
            currentTable.startNewRow();
        }
    }

    public static class CellElement
    {
        private final String text;
        private final Color color;

        public CellElement()
        {
            this.text = "";
            this.color = Color.WHITE;
        }

        public CellElement(String text)
        {
            this.text = text;
            this.color = Color.WHITE;
        }

        public CellElement(String text, Color color)
        {
            this.text = text;
            this.color = color;
        }

        public String getText() {
            return text;
        }

        public Color getBackgroundColor() {
            return color;
        }

    }
}


问:
Algolia: Show all records but ranked by relevance
I need to rank records in a dataset by the relevance to a certain query but not filter out data that is irrelevant. I would like to use Algolia for this if possible.

Desired Ranking

Imagine I have a dataset of crates of fruits and their geolocations.

```<code>[
  {
    "fruits": ["apple", "orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  },
  {
    "fruits": ["banana", "apple"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["banana"],
    "_geoloc": {"lat": 5, "lng": 2}
  },
  {
    "fruits": ["apple", "banana"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  }
]
</code>```

I need to query the data so that I return all of the data but ranked by the match to the input query and the proximity to the specified geolocation.

So, if the geolocation is {"lat": 1, "lng": 2} and the query is apple, banana the resulting ranked data would be something like this:

```<code>[
  {
    "fruits": ["apple", "banana"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["banana", "apple"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["apple", "orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  },
  {
    "fruits": ["banana"],
    "_geoloc": {"lat": 5, "lng": 2}
  },
  {
    "fruits": ["orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  }
]
</code>```

The record that matches the query exactly comes first, then come records with a different word ordering, then records with some of the words (but closer proximity), and finally the record(s) with no matching words.

Tried so far

Debugging in Dashboard

So far I have used the Dashboard in Algolia to play around with this. However, irrelevant records are always filtered out, when the desire here is to always show all data (just sorted).

With the querying strategy described above it would return something like:

```<code>[
  {
    "fruits": ["apple", "banana"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["banana", "apple"],
    "_geoloc": {"lat": 8, "lng": 2}
  }
]
</code>```

The data matching the query is returned but not the rest. Even the data missing a keyword is removed.

Faceting

I have considered using disjunctive faceting to achieve this but this has two problems:

I need full-text search with typo tolerance within the word query. For example, the user could add a facet of "apple" or "cooked apples" and the records containing "apple" would still be highly ranked. Conversely, there is no limitation to what may be in the "fruits" array. That array may also contain typos or related but not exact matches.

Records not matching the query would still not be returned. With faceting, the records of "orange" and "banana", only, in the fruits array would still not be returned.

答:
There are two ways you can use Algolia for doing this: as a search engine or as a primary data source. As the first option is what Algolia recommends, I'll start with this one.

Using Algolia as a Search Engine

Algolia being a search-engine, it is designed to process search queries and return the subset of all your records that is relevant to the query.

This means Algolia is not meant to be used as a primary data-source: most of the time the engine won't return all your objects but rather the most relevant ones for the current query. This difference between a search engine and a regular database allows all the optimisations that make Algolia so fast.

In practice

For your use-case of sorting all your crates according to content and position, you could use Algolia for knowing which ones are relevant to a query, then sort your whole dataset using that information.

For example you can both get the list of crates from your primary database and perform a query in Algolia to check which ones are the most relevant.
Then you would display the Algolia results first, followed by the remaining crates from your list (maybe indicating These crates don't contain the fruits you requested (apple banana)).

You would set your index settings as such:

Searchable Attributes: "fruits" (unordered)

Ranking Formula: default (so the geo criteria is used to rank the crates whose fruits match the query)

Algolia would then return all crates that contain every fruit in the query, sorted by geographic proximity.

You could also use removeWordsIfNoResults=allOptional so if a user types orange kiwi and no crate contains both you would get the crates that contain only orange or only kiwi. Likewise, if a user typed kiwi and no crates contains it, the engine would return all crates simply sorted by geolocation.

Using Algolia as a Primary data source

If your data is only stored in Algolia, you can do two queries: a first one to get all your records and a second one to get the relevant results. You can then merge them by putting the relevant ones first, and display the resulting list.

In practice

You would use search for getting the relevant results, and browse for getting all your records by batches of 1000. Once you have both lists, you'll just have to display the relevant crates, remove the duplicates from the second list then display the remaining crates.

The index settings would be the same as previously, to filter first by content and then order by geolocation.

As in the first approach, you can also use removeWordsIfNoResults to remove words from the query until the engine finds relevant results.

Body:
I need to rank records in a dataset by the relevance to a certain query but not filter out data that is irrelevant. I would like to use Algolia for this if possible.

Desired Ranking

Imagine I have a dataset of crates of fruits and their geolocations.

[
  {
    "fruits": ["apple", "orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  },
  {
    "fruits": ["banana", "apple"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["banana"],
    "_geoloc": {"lat": 5, "lng": 2}
  },
  {
    "fruits": ["apple", "banana"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  }
]

I need to query the data so that I return all of the data but ranked by the match to the input query and the proximity to the specified geolocation.

So, if the geolocation is {"lat": 1, "lng": 2} and the query is apple, banana the resulting ranked data would be something like this:

[
  {
    "fruits": ["apple", "banana"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["banana", "apple"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["apple", "orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  },
  {
    "fruits": ["banana"],
    "_geoloc": {"lat": 5, "lng": 2}
  },
  {
    "fruits": ["orange"],
    "_geoloc": {"lat": 1, "lng": 2}
  }
]

The record that matches the query exactly comes first, then come records with a different word ordering, then records with some of the words (but closer proximity), and finally the record(s) with no matching words.

Tried so far

Debugging in Dashboard

So far I have used the Dashboard in Algolia to play around with this. However, irrelevant records are always filtered out, when the desire here is to always show all data (just sorted).

With the querying strategy described above it would return something like:

[
  {
    "fruits": ["apple", "banana"],
    "_geoloc": {"lat": 8, "lng": 2}
  },
  {
    "fruits": ["banana", "apple"],
    "_geoloc": {"lat": 8, "lng": 2}
  }
]

The data matching the query is returned but not the rest. Even the data missing a keyword is removed.

Faceting

I have considered using disjunctive faceting to achieve this but this has two problems:

I need full-text search with typo tolerance within the word query. For example, the user could add a facet of "apple" or "cooked apples" and the records containing "apple" would still be highly ranked. Conversely, there is no limitation to what may be in the "fruits" array. That array may also contain typos or related but not exact matches.

Records not matching the query would still not be returned. With faceting, the records of "orange" and "banana", only, in the fruits array would still not be returned.


问:
iPhone: Weird space at the top of UINavigationController
I'm having a strange problem with adding a UINavigationController to my iPhone application. I add the controller as follows:

```<code>myViewController *viewController = [[myViewController alloc] initWithNibName:@"myView" bundle:nil];

myNavigationViewController *navigationController = [[myNavigationViewController alloc] initWithRootViewController:viewController];

UIView *finalView = myeNavigationViewController.view;

[self.view addSubview:finalView];
</code>```

All seems to work as planned except I get a weird white space at the top of my view between the status bar and the UINavigationController title bar.
alt text http://www.andrewskinner.name/problem.png

I've searched online but don't really know what to search for. Has anyone else had this problem? Can you point me in the direction of some help?

Thanks in advance.

答:
I struggled with this for a while too using very similar code to the op's and also had a white bar above my navigation controller.

My problem occurred when adding the UINavigationController as a view in a UITabController. The space in my case was caused by the UINavigationBar part of the UINavigationController taking into account the status bar and it was actually overlapping part of the view that I was trying to show in the UINavigationController.

This is the code I ended up with in loadView in one of my UITabBarController view controllers.

```<code>SomeUITableViewController *screenList = [[SomeUITableViewController alloc] init];

UINavigationController *navController = [[UINavigationController alloc]
                                         initWithRootViewController:screenList];

CGRect frame = [[navController navigationBar] frame];

frame.origin.y = 0; // Was 20, set to 0 to not take into account the status bar.

[[navController navigationBar] setFrame:frame];

[self setView:[navController view]];
</code>```

There's some more information at http://discussions.apple.com/message.jspa?messageID=7890362.

Body:
I'm having a strange problem with adding a UINavigationController to my iPhone application. I add the controller as follows:

myViewController *viewController = [[myViewController alloc] initWithNibName:@"myView" bundle:nil];

myNavigationViewController *navigationController = [[myNavigationViewController alloc] initWithRootViewController:viewController];

UIView *finalView = myeNavigationViewController.view;

[self.view addSubview:finalView];

All seems to work as planned except I get a weird white space at the top of my view between the status bar and the UINavigationController title bar.
alt text http://www.andrewskinner.name/problem.png

I've searched online but don't really know what to search for. Has anyone else had this problem? Can you point me in the direction of some help?

Thanks in advance.

Body:
I struggled with this for a while too using very similar code to the op's and also had a white bar above my navigation controller.

My problem occurred when adding the UINavigationController as a view in a UITabController. The space in my case was caused by the UINavigationBar part of the UINavigationController taking into account the status bar and it was actually overlapping part of the view that I was trying to show in the UINavigationController.

This is the code I ended up with in loadView in one of my UITabBarController view controllers.

SomeUITableViewController *screenList = [[SomeUITableViewController alloc] init];

UINavigationController *navController = [[UINavigationController alloc]
                                         initWithRootViewController:screenList];

CGRect frame = [[navController navigationBar] frame];

frame.origin.y = 0; // Was 20, set to 0 to not take into account the status bar.

[[navController navigationBar] setFrame:frame];

[self setView:[navController view]];

There's some more information at http://discussions.apple.com/message.jspa?messageID=7890362.


问:
Wordpress Text editor does not work
I have a problem with my website. I made it with Wordpress ,

everything was Ok but I think that someone tried to hack it  today so all contents cannot be displayed .

To explain more when I write some text in text editor it's not showing on the front page of my website ! I don't understand what's the problem how can I solve it ?

http://www.ahlanfoundation.com/about-us/

من نحن ؟

مؤسسة أهلا للتسويق متخصصــة فــي التسويق الالكتروني نشــأت فكــرة تأسيســها لتكــون مؤسســة طموحــة تســعى لتقديــم حلــول مبتكــرة وابــداع لا محــدود فــي التسويق الالكتروني، وتفخــر المؤسسة بجذورهـا وهويتهـا و يدفعهـا الطمـوح لتوسـيع بـؤرة أعمالهــا . تأسســت أهلا للتسويق عــام  2016 لتصبــح إحــدى المؤسسات للتسويق الالكتروني الرائــدة فــي دول الخليج العربي وتضــع بمتنــاول جميــع العمــلاء خدمــات غيــر مســبوقة لكــي تصنــع الفــرق فــي حملاتهــم الترويجيــة والاعلانيــة لمختلــف أنشــطتهم وتوجهاتهــم . كمــا تضــم مؤسســتنا أفضــل العناصــر البشــرية مــن مختلــف الاختصاصــات لنقــدم خدمــات متميــزة تتماشــى مــع أدق متطلبــات عملائنــا المتغيــرة ســواء كانــت تصاميــم خاصــة أو الخطــط الإعلانيـة والاعلاميـة أو التسويق الالكتروني. نحـن نلتـزم بتقديـم أعلـى معاييـر الجـودة مـع إضافـة لمسـة مـن الابـداع الامحـدود.

```

when I try to inspect some elements on the browser I found it hidden.

答:
Assuming you dont have a back up because you wouldent be posting this if you did!
Deactivate  all your plugins - install wp theme 2017 - delete your theme - re install your theme (from scratch) and activate your plugins one by one whilst checking the functionality of your theme. Your plugins are prob not the issue.

You can also inspect it in the browser if you can see the  first line - double  click

```<code>    <p><span class="hide"
</code>```

and change it to

```<code>    <p><span class="show"
</code>```

Then tap enter!

Title: Wordpress Text editor does not work

Body:
I have a problem with my website. I made it with Wordpress ,

everything was Ok but I think that someone tried to hack it  today so all contents cannot be displayed .

To explain more when I write some text in text editor it's not showing on the front page of my website ! I don't understand what's the problem how can I solve it ?

http://www.ahlanfoundation.com/about-us/

من نحن ؟

مؤسسة أهلا للتسويق متخصصــة فــي التسويق الالكتروني نشــأت فكــرة تأسيســها لتكــون مؤسســة طموحــة تســعى لتقديــم حلــول مبتكــرة وابــداع لا محــدود فــي التسويق الالكتروني، وتفخــر المؤسسة بجذورهـا وهويتهـا و يدفعهـا الطمـوح لتوسـيع بـؤرة أعمالهــا . تأسســت أهلا للتسويق عــام  2016 لتصبــح إحــدى المؤسسات للتسويق الالكتروني الرائــدة فــي دول الخليج العربي وتضــع بمتنــاول جميــع العمــلاء خدمــات غيــر مســبوقة لكــي تصنــع الفــرق فــي حملاتهــم الترويجيــة والاعلانيــة لمختلــف أنشــطتهم وتوجهاتهــم . كمــا تضــم مؤسســتنا أفضــل العناصــر البشــرية مــن مختلــف الاختصاصــات لنقــدم خدمــات متميــزة تتماشــى مــع أدق متطلبــات عملائنــا المتغيــرة ســواء كانــت تصاميــم خاصــة أو الخطــط الإعلانيـة والاعلاميـة أو التسويق الالكتروني. نحـن نلتـزم بتقديـم أعلـى معاييـر الجـودة مـع إضافـة لمسـة مـن الابـداع الامحـدود.

when I try to inspect some elements on the browser I found it hidden.

Body:
Assuming you dont have a back up because you wouldent be posting this if you did!
Deactivate  all your plugins - install wp theme 2017 - delete your theme - re install your theme (from scratch) and activate your plugins one by one whilst checking the functionality of your theme. Your plugins are prob not the issue.

You can also inspect it in the browser if you can see the  first line - double  click

    <p><span class="hide"

and change it to

    <p><span class="show"

Then tap enter!


问:
Extracting information from a a java core dump with jmap(1.5)
Long story short, some coworkers are running a pretty old setup(oc4j jdk1.5.6 in x86_64) with an application which happens to be mission critical. They recently have tried to deploy a new version of the application, but as soon as they do the java process(es) throw a core dump and die.

The problem is, the core dumps seem to be fine, gdb can open them, but jmap and other tools refuse to process them:

```<code># /usr/java/jdk1.5.0_06/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Error attaching to core file: Can't attach to the core file
</code>```

And newer versions throw a exception:

```<code># jdk1.6.0_45/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at sun.tools.jmap.JMap.runTool(JMap.java:179)
        at sun.tools.jmap.JMap.main(JMap.java:110)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 20.45-b01. Target VM is 1.5.0_06-b05
        at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:224)
        at sun.jvm.hotspot.runtime.VM.<init>(VM.java:287)
        at sun.jvm.hotspot.runtime.VM.initialize(VM.java:357)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:594)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:494)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:348)
        at sun.jvm.hotspot.tools.Tool.start(Tool.java:169)
        at sun.jvm.hotspot.tools.PMap.main(PMap.java:67)
        ... 6 more
</code>```

gdb offers little information without symbols:

```<code>Reading symbols from /usr/java/jdk1.5.0_06/bin/java...(no debugging symbols found)...done.

[New Thread 9841]
[New Thread 31442]
[New Thread 31441]
...
Core was generated by `/usr/java/jdk1.5.0_06/bin/java -server -XX:+UseConcMarkSweepGC -XX:MaxHeapFreeR'.
Program terminated with signal 6, Aborted.
#0  0x0000003bbf030285 in ?? ()
(gdb) bt
#0  0x0000003bbf030285 in ?? ()
#1  0x0000003bbf031d30 in ?? ()
#2  0x0000000000000000 in ?? ()
</code>```

The only valuable information I've gathered from the core is that most threads
are blocked(I'm far from being a gdb guru):

```<code>  35 Thread 10093  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  34 Thread 10097  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  33 Thread 10099  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
</code>```

Besides, I don't know if it's really relevant. The app is almost always heavily loaded, and my bet is that there were some lock contention already but since it's another's team app my knowledge about it it's pretty shallow.

I guess this is a long shot, but is there something that we can do to get a java thread dump or something like that? Do Sun used to offer debuginfo of the jdk as I guess is avalaible now with openjdk?

Thanks in advance.

UPDATE: The other team has resolved the issue without getting info from the core dump, just by trial and error after successfully replicating the problem in a test system. I'm still intrigued about the thing: how to debug an ancient java core dump which jmap can't process, it might be valuable info for the future, althought it seems is that there is no solution to that problem. Probably the JVM memory got corrupted and that's why jmap can't process it.

答:
Jmap and other JVM utilities are extremely version sensitive. From your error, it is self explanatory that hopefully the same jvm is not used in your case.

Java VisualVM can load core dumps directly. But you must use the same jvm that created the core file.

Resource Link:

https://stackoverflow.com/a/9981498/2293534

Suggestion#1:

kjkoster has given a solution here in this tutorial.

You need to use the jmap that comes with the JVM. From your error
  message I gather that you are using a different version of jmap than
  of the JVM.

Please check what JVMs are installed on your machine and ensure than
  when you run jmap, you use the right version.

To solve such issues I never rely on path. Instead I set JAVA_HOME to
  be the one that the JVM uses and then invoke both the JVM and jmap
  like so:

Code:

```<code>$ JAVA_HOME=/usr/local/jdk1.6.0
$ export JAVA_HOME
$ ${JAVA_HOME}/bin/java ...

...

$ ${JAVA_HOME}/bin/jmap ...
</code>```

Hope this helps.

Suggestion#2:

It is a full solution step by step is given by Chamilad. Hope it will clarify your root cause and solution procedure.

Almost every Java developer knows about jmap and jstack tools that come with the JDK. These provide functionality to extract heap and thread information of a running JVM instance. Easy.

What if there’s a running JVM that has produced a deadlock and you want to take a thread dump while the process is running? You go in and run the following.

```<code>jstack pid >> thread_dump.txt
</code>```

Turns out the system doesn’t know what jstack is. You don’t panic, but you get a tiny sensation at the back of your head saying you’re not leaving early this Friday.

What has happened is the running JVM is based on a JRE and not a JDK. The JRE is a minimal runtime that doesn’t pack the monitoring and analysis tools that the JDK packs.

So what are our options here?

Stop the process. Download JDK, start the process again on top of
JDK and hope the deadlock happens again. Nope.

Start JVisualVM on your laptop and hope the process has JMX enabled. Nope.

tools.jar TO THE RESCUE!

Functionalities such as jstack are implemented in the tools.jar file which is packed inside <JDK_HOME>/lib folder. We can use this to invoke the JStack class and get a thread dump of the running process.

So we march on to download and extract the JDK, and then to run the following.

```<code>java -classpath <JDK_HOME>/lib/tools.jar sun.tools.jstack.JStack <pid> >> thread_dump.txt
</code>```

..and come across the following error.

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no attach in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
        at java.lang.Runtime.loadLibrary0(Runtime.java:870)
        at java.lang.System.loadLibrary(System.java:1122)
        at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:342)
        at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
        at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:208)
        at sun.tools.jstack.JStack.runThreadDump(JStack.java:163)
        at sun.tools.jstack.JStack.main(JStack.java:116)
</code>```

Darn it! Spoiled again!

How do we solve this? The above error is caused when the process can’t find libattach.so file which is related to the Dynamic Attach function related to JStack. Setting the following environment variable will help the JVM to find the libattach.so file.

```<code>export LD_LIBRARY_PATH=<JDK_HOME>/jre/lib/amd64/
</code>```

Now let’s run JStack again, this time with results!

```<code>java -classpath <JDK_HOME>/lib/tools.jar sun.tools.jstack.JStack <pid> >> thread_dump.txt
</code>```

Now that we have the thread dump, we move on to the heap dump. The tool we normally use is jmap but that too is not available on the JRE. So what? We can use the binary in the JDK’s bin directory right? right?

```<code>root@snowflake1 latest]# <JDK_HOME>/bin/jmap -heap <pid>
Attaching to process ID <pid>, please wait…
Error attaching to process: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 25.102-b14. Target VM is 25.91-b14
sun.jvm.hotspot.debugger.DebuggerException: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 25.102-b14. Target VM is 25.91-b14
 at sun.jvm.hotspot.HotSpotAgent.setupVM(HotSpotAgent.java:435)
 at sun.jvm.hotspot.HotSpotAgent.go(HotSpotAgent.java:305)
 at sun.jvm.hotspot.HotSpotAgent.attach(HotSpotAgent.java:140)
 at sun.jvm.hotspot.tools.Tool.start(Tool.java:185)
 at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)
 at sun.jvm.hotspot.tools.HeapSummary.main(HeapSummary.java:49)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at sun.tools.jmap.JMap.runTool(JMap.java:201)
 at sun.tools.jmap.JMap.main(JMap.java:130)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 25.102-b14. Target VM is 25.91-b14
 at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:227)
 at sun.jvm.hotspot.runtime.VM.<init>(VM.java:294)
 at sun.jvm.hotspot.runtime.VM.initialize(VM.java:370)
 at sun.jvm.hotspot.HotSpotAgent.setupVM(HotSpotAgent.java:431)
 … 11 more
</code>```

Nope! Unless you match the JDK version with the exact version the JRE is at you get the above issue (which is pretty self-explanatory). So we download the JDK of the JRE of on top our process is running and run jmap again.

```<code><JDK_HOME>/bin/jmap -dump:file=heap_dump.hprof <pid>
</code>```

Resource Link:

Extracting memory and thread dumps from a running JRE based JVM

Body:
Long story short, some coworkers are running a pretty old setup(oc4j jdk1.5.6 in x86_64) with an application which happens to be mission critical. They recently have tried to deploy a new version of the application, but as soon as they do the java process(es) throw a core dump and die.

The problem is, the core dumps seem to be fine, gdb can open them, but jmap and other tools refuse to process them:

# /usr/java/jdk1.5.0_06/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Error attaching to core file: Can't attach to the core file

And newer versions throw a exception:

# jdk1.6.0_45/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at sun.tools.jmap.JMap.runTool(JMap.java:179)
        at sun.tools.jmap.JMap.main(JMap.java:110)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 20.45-b01. Target VM is 1.5.0_06-b05
        at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:224)
        at sun.jvm.hotspot.runtime.VM.<init>(VM.java:287)
        at sun.jvm.hotspot.runtime.VM.initialize(VM.java:357)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:594)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:494)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:348)
        at sun.jvm.hotspot.tools.Tool.start(Tool.java:169)
        at sun.jvm.hotspot.tools.PMap.main(PMap.java:67)
        ... 6 more

gdb offers little information without symbols:

Reading symbols from /usr/java/jdk1.5.0_06/bin/java...(no debugging symbols found)...done.

[New Thread 9841]
[New Thread 31442]
[New Thread 31441]
...
Core was generated by `/usr/java/jdk1.5.0_06/bin/java -server -XX:+UseConcMarkSweepGC -XX:MaxHeapFreeR'.
Program terminated with signal 6, Aborted.
#0  0x0000003bbf030285 in ?? ()
(gdb) bt
#0  0x0000003bbf030285 in ?? ()
#1  0x0000003bbf031d30 in ?? ()
#2  0x0000000000000000 in ?? ()

The only valuable information I've gathered from the core is that most threads
are blocked(I'm far from being a gdb guru):

  35 Thread 10093  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  34 Thread 10097  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  33 Thread 10099  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0

Besides, I don't know if it's really relevant. The app is almost always heavily loaded, and my bet is that there were some lock contention already but since it's another's team app my knowledge about it it's pretty shallow.

I guess this is a long shot, but is there something that we can do to get a java thread dump or something like that? Do Sun used to offer debuginfo of the jdk as I guess is avalaible now with openjdk?

Thanks in advance.

UPDATE: The other team has resolved the issue without getting info from the core dump, just by trial and error after successfully replicating the problem in a test system. I'm still intrigued about the thing: how to debug an ancient java core dump which jmap can't process, it might be valuable info for the future, althought it seems is that there is no solution to that problem. Probably the JVM memory got corrupted and that's why jmap can't process it.

Body:
Jmap and other JVM utilities are extremely version sensitive. From your error, it is self explanatory that hopefully the same jvm is not used in your case.

Java VisualVM can load core dumps directly. But you must use the same jvm that created the core file.

Resource Link:

https://stackoverflow.com/a/9981498/2293534

Suggestion#1:

kjkoster has given a solution here in this tutorial.

You need to use the jmap that comes with the JVM. From your error
  message I gather that you are using a different version of jmap than
  of the JVM.

Please check what JVMs are installed on your machine and ensure than
  when you run jmap, you use the right version.

To solve such issues I never rely on path. Instead I set JAVA_HOME to
  be the one that the JVM uses and then invoke both the JVM and jmap
  like so:

Code:

$ JAVA_HOME=/usr/local/jdk1.6.0
$ export JAVA_HOME
$ ${JAVA_HOME}/bin/java ...

...

$ ${JAVA_HOME}/bin/jmap ...

Hope this helps.

Suggestion#2:

It is a full solution step by step is given by Chamilad. Hope it will clarify your root cause and solution procedure.

Almost every Java developer knows about jmap and jstack tools that come with the JDK. These provide functionality to extract heap and thread information of a running JVM instance. Easy.

What if there’s a running JVM that has produced a deadlock and you want to take a thread dump while the process is running? You go in and run the following.

jstack pid >> thread_dump.txt

Turns out the system doesn’t know what jstack is. You don’t panic, but you get a tiny sensation at the back of your head saying you’re not leaving early this Friday.

What has happened is the running JVM is based on a JRE and not a JDK. The JRE is a minimal runtime that doesn’t pack the monitoring and analysis tools that the JDK packs.

So what are our options here?

Stop the process. Download JDK, start the process again on top of
JDK and hope the deadlock happens again. Nope.

Start JVisualVM on your laptop and hope the process has JMX enabled. Nope.

tools.jar TO THE RESCUE!

Functionalities such as jstack are implemented in the tools.jar file which is packed inside <JDK_HOME>/lib folder. We can use this to invoke the JStack class and get a thread dump of the running process.

So we march on to download and extract the JDK, and then to run the following.

java -classpath <JDK_HOME>/lib/tools.jar sun.tools.jstack.JStack <pid> >> thread_dump.txt

..and come across the following error.

Exception in thread "main" java.lang.UnsatisfiedLinkError: no attach in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
        at java.lang.Runtime.loadLibrary0(Runtime.java:870)
        at java.lang.System.loadLibrary(System.java:1122)
        at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:342)
        at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
        at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:208)
        at sun.tools.jstack.JStack.runThreadDump(JStack.java:163)
        at sun.tools.jstack.JStack.main(JStack.java:116)

Darn it! Spoiled again!

How do we solve this? The above error is caused when the process can’t find libattach.so file which is related to the Dynamic Attach function related to JStack. Setting the following environment variable will help the JVM to find the libattach.so file.

export LD_LIBRARY_PATH=<JDK_HOME>/jre/lib/amd64/

Now let’s run JStack again, this time with results!

java -classpath <JDK_HOME>/lib/tools.jar sun.tools.jstack.JStack <pid> >> thread_dump.txt

Now that we have the thread dump, we move on to the heap dump. The tool we normally use is jmap but that too is not available on the JRE. So what? We can use the binary in the JDK’s bin directory right? right?

root@snowflake1 latest]# <JDK_HOME>/bin/jmap -heap <pid>
Attaching to process ID <pid>, please wait…
Error attaching to process: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 25.102-b14. Target VM is 25.91-b14
sun.jvm.hotspot.debugger.DebuggerException: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 25.102-b14. Target VM is 25.91-b14
 at sun.jvm.hotspot.HotSpotAgent.setupVM(HotSpotAgent.java:435)
 at sun.jvm.hotspot.HotSpotAgent.go(HotSpotAgent.java:305)
 at sun.jvm.hotspot.HotSpotAgent.attach(HotSpotAgent.java:140)
 at sun.jvm.hotspot.tools.Tool.start(Tool.java:185)
 at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)
 at sun.jvm.hotspot.tools.HeapSummary.main(HeapSummary.java:49)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at sun.tools.jmap.JMap.runTool(JMap.java:201)
 at sun.tools.jmap.JMap.main(JMap.java:130)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 25.102-b14. Target VM is 25.91-b14
 at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:227)
 at sun.jvm.hotspot.runtime.VM.<init>(VM.java:294)
 at sun.jvm.hotspot.runtime.VM.initialize(VM.java:370)
 at sun.jvm.hotspot.HotSpotAgent.setupVM(HotSpotAgent.java:431)
 … 11 more

Nope! Unless you match the JDK version with the exact version the JRE is at you get the above issue (which is pretty self-explanatory). So we download the JDK of the JRE of on top our process is running and run jmap again.

<JDK_HOME>/bin/jmap -dump:file=heap_dump.hprof <pid>

Resource Link:

Extracting memory and thread dumps from a running JRE based JVM

ContentLicense: CC BY-SA 4.0