问:
How to highlight active slides in Flexslider carousel?
Is it possible to highlight the current items in Flexslider carousel, so I can add a class to the active ones?

I use the basic setup of the Flexslider carousel. Now I would like to have a script that will added active to each slide inside the viewport that is visible.

This example I use:
http://flexslider.woothemes.com/basic-carousel.html

I now how to get the Flexslider properties in the start function. When I give the function the parameter I can ask for - the total amount of items in the ul, how many items it will move, and how many paging there will be. I don't know if it is possible to write a formule to calculate which one is active with the given variables, so I can highlight them.

```<code>$('.flexslider').flexslider({
        animation: "slide",
        animationLoop: false,
        slideshow: false,
        itemWidth: 460,
        itemMargin: 30,
        minItems: 2,
        maxItems: 6,
        controlNav: false,
        customDirectionNav: ".custom-direction li a",
        start: function(slider) {
            var pagingCount = slider.pagingCount;
            var move = slider.move;
            var visibleSlides = slider.visible;
            var totalSlides = slider.count;

            console.log(slider);
            console.log(slider.move);
            console.log(slider.update);

            if (totalSlides) {
                $('.slides li').addClass('active-slides');

            };
            // console.log(slider.count);
            // console.log(slider.currentSlide);
        }

    });
</code>```

I have made a start, but doesn't know how the if statement or for loop should look like to get this done.

Any ideas?
Thanks in advance.

答:
Used the accepted answer above but needed to make a couple amendments to make it work for me shown below.

Mostly handling some exceptions, dealing with half shown slides and when the move/visible are different.

```<code>window.addCurrentSlidesClass = function (slider) {
  jQuery('.flexslider li').removeClass("active-slide");

  // get visible by math rather than slider variable due to half shown slides not counting
  // var visible = slider.visible;
  var visible = Math.ceil(slider.w / slider.itemT);

  var startli = (slider.move * (slider.currentSlide));
  // var endli = (slider.move * (slider.currentSlide + 1));
  var endli = startli + visible;

  // Don't push past when you reach end of list
  if(endli > slider.count) {
    startli = startli - (endli - slider.count);
    endli = endli - (endli - slider.count);
  }

  for (i = startli + 1; i <= endli; i++) {
    jQuery('.flexslider li:nth-child(' + i + ')').addClass('active-slide');
  }
};
</code>```

Body:
Is it possible to highlight the current items in Flexslider carousel, so I can add a class to the active ones?

I use the basic setup of the Flexslider carousel. Now I would like to have a script that will added active to each slide inside the viewport that is visible.

This example I use:
http://flexslider.woothemes.com/basic-carousel.html

I now how to get the Flexslider properties in the start function. When I give the function the parameter I can ask for - the total amount of items in the ul, how many items it will move, and how many paging there will be. I don't know if it is possible to write a formule to calculate which one is active with the given variables, so I can highlight them.

$('.flexslider').flexslider({
        animation: "slide",
        animationLoop: false,
        slideshow: false,
        itemWidth: 460,
        itemMargin: 30,
        minItems: 2,
        maxItems: 6,
        controlNav: false,
        customDirectionNav: ".custom-direction li a",
        start: function(slider) {
            var pagingCount = slider.pagingCount;
            var move = slider.move;
            var visibleSlides = slider.visible;
            var totalSlides = slider.count;

            console.log(slider);
            console.log(slider.move);
            console.log(slider.update);

            if (totalSlides) {
                $('.slides li').addClass('active-slides');

            };
            // console.log(slider.count);
            // console.log(slider.currentSlide);
        }

    });

I have made a start, but doesn't know how the if statement or for loop should look like to get this done.

Any ideas?
Thanks in advance.

Body:
Used the accepted answer above but needed to make a couple amendments to make it work for me shown below.

Mostly handling some exceptions, dealing with half shown slides and when the move/visible are different.

window.addCurrentSlidesClass = function (slider) {
  jQuery('.flexslider li').removeClass("active-slide");

  // get visible by math rather than slider variable due to half shown slides not counting
  // var visible = slider.visible;
  var visible = Math.ceil(slider.w / slider.itemT);

  var startli = (slider.move * (slider.currentSlide));
  // var endli = (slider.move * (slider.currentSlide + 1));
  var endli = startli + visible;

  // Don't push past when you reach end of list
  if(endli > slider.count) {
    startli = startli - (endli - slider.count);
    endli = endli - (endli - slider.count);
  }

  for (i = startli + 1; i <= endli; i++) {
    jQuery('.flexslider li:nth-child(' + i + ')').addClass('active-slide');
  }
};


来源: stackexchange

问:
Why are parentheses required for array indexing in postgres?
In (postgres) SQL, this is valid syntax,

```<code>select (array[ [1,2,3], [4,5,6]])[1];
</code>```

but not:

```<code>select array[ [1,2,3], [4,5,6]][1];
</code>```

... which is a little surprising to me. What's going on here?

答:
This is a parser issue. PostgreSQL uses Bison parser - additional parenthesis are required as protection against parsing collisions. The query processing is in stages: parsing, analyse, planning and execution. There are not enough information in parsing time to protect bison against possible collision and then some syntaxes are not disallowed.

Because a arrays was proprietary PostgreSQL feature (very successful) and syntax was not described by ANSI, a developers preferred some compromise design like good enough for users and doesn't require too complex code. A focus of PostgreSQL is in SQL and not in arrays processing. The Bison is very good mature tool, but sometimes due speed requirements some syntaxes are difficult or impossible.

```<code>select array[ [1,2,3], [4,5,6]]::int[][1]
</code>```

There is not any magic if you know a fact, so limits in arrays types definition are syntactic sugar only. int[],int[1],int[] [100]is just int[]. Then array[ [1,2,3], [4,5,6]]::int[][1] is same like array[ [1,2,3], [4,5,6]]::int[] .. take a numeric array and cast it to integer array.

ContentLicense: CC BY-SA 3.0

Body:
In (postgres) SQL, this is valid syntax,

select (array[ [1,2,3], [4,5,6]])[1];

but not:

select array[ [1,2,3], [4,5,6]][1];

... which is a little surprising to me. What's going on here?

Body:
This is a parser issue. PostgreSQL uses Bison parser - additional parenthesis are required as protection against parsing collisions. The query processing is in stages: parsing, analyse, planning and execution. There are not enough information in parsing time to protect bison against possible collision and then some syntaxes are not disallowed.

Because a arrays was proprietary PostgreSQL feature (very successful) and syntax was not described by ANSI, a developers preferred some compromise design like good enough for users and doesn't require too complex code. A focus of PostgreSQL is in SQL and not in arrays processing. The Bison is very good mature tool, but sometimes due speed requirements some syntaxes are difficult or impossible.

select array[ [1,2,3], [4,5,6]]::int[][1]

There is not any magic if you know a fact, so limits in arrays types definition are syntactic sugar only. int[],int[1],int[] [100]is just int[]. Then array[ [1,2,3], [4,5,6]]::int[][1] is same like array[ [1,2,3], [4,5,6]]::int[] .. take a numeric array and cast it to integer array.


问:
Adding Rule into existing KiePackage and KieBase
I'm trying to add a Rule to a KiePackage that has already been defined and built using KieBuilder.

I know you can remove a rule using:

```<code>base.removeRule("com.somepackage", "ruleName");
</code>```

But is there an equivalent for adding a rule? I've tried adding a new .drl file into the KieFileSystem and using KieScanner to pick up the changes, but it doesn't seem to work:

```<code>KieBaseConfiguration config = service.newKieBaseConfiguration();
KieBase base = kContainer.newKieBase(config);

KieFileSystem fileSystem = service.newKieFileSystem();
KieBuilder builder = service.newKieBuilder(fileSystem);

fileSystem.write(originalDrlFile, someFile)
builder.buildAll()                               // first drl is loaded

fileSystem.write(newlDrlFile, someFile)

KieScanner scanner = service.newKieScanner(kContainer);
scanner.scanNow();
KieSession ksession1 = kContainer.newKieSession();

builder.buildAll()                               // reloading with new drl.
</code>```

When I evaluate a fact against ksession1, the new rules dont exist in the KieBase. Am I missing something?

答:
Where are we making a relationship between the kieBuilder and kieBase?

I have tried something like this..

```<code>kieContainer= kieService.newKieContainer(kiebuilder.getKieModule().getReleaseId());
kieSession = kieContainer.newKieSession();
</code>```

Body:
I'm trying to add a Rule to a KiePackage that has already been defined and built using KieBuilder.

I know you can remove a rule using:

base.removeRule("com.somepackage", "ruleName");

But is there an equivalent for adding a rule? I've tried adding a new .drl file into the KieFileSystem and using KieScanner to pick up the changes, but it doesn't seem to work:

KieBaseConfiguration config = service.newKieBaseConfiguration();
KieBase base = kContainer.newKieBase(config);

KieFileSystem fileSystem = service.newKieFileSystem();
KieBuilder builder = service.newKieBuilder(fileSystem);

fileSystem.write(originalDrlFile, someFile)
builder.buildAll()                               // first drl is loaded

fileSystem.write(newlDrlFile, someFile)

KieScanner scanner = service.newKieScanner(kContainer);
scanner.scanNow();
KieSession ksession1 = kContainer.newKieSession();

builder.buildAll()                               // reloading with new drl.

When I evaluate a fact against ksession1, the new rules dont exist in the KieBase. Am I missing something?

Body:
Where are we making a relationship between the kieBuilder and kieBase?

I have tried something like this..

kieContainer= kieService.newKieContainer(kiebuilder.getKieModule().getReleaseId());
kieSession = kieContainer.newKieSession();


问:
Using an interface as a type
I've been looking through some production code, and I'm a little confused on the concept of using an interface as a type (object)

I saw this explanation http://download.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

Here's the code below:

```<code>public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ( (obj1).isLargerThan(obj2) > 0)
      return object1;
   else
      return object2;
}
</code>```

Where Relatable is an interface, I don't understand where it gets the logic for the isLargerThan(obj2) function call.

Can somebody make this clear for me?

答: It's assumed that the objects are actually of types that implement the interface; otherwise, you'd get a ClassCastException when casting.

ContentLicense: CC BY-SA 2.5

Title: Using an interface as a type

Body:
I've been looking through some production code, and I'm a little confused on the concept of using an interface as a type (object)

I saw this explanation http://download.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

Here's the code below:

public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ( (obj1).isLargerThan(obj2) > 0)
      return object1;
   else
      return object2;
}

Where Relatable is an interface, I don't understand where it gets the logic for the isLargerThan(obj2) function call.

Can somebody make this clear for me?


问:
using input type file with angular material 2
How can I use angular material 2 FAB buttons to open a browse input dialog? This can be done in HTML by this way.

<button type="button">
    click
</button>
<input type="file" id="file-input" style="display:none">
```

<p>I tried following the same approach with material 2, but it doesn't work.</p>

<pre class="lang-html prettyprint-override"><code><button md-mini-fab type="button">
    <label for="fileToUpload">
        <md-icon>add</md-icon>
    </label>
</button>
<input id="fileToUpload" type="file" style="display:none;">
</code>```

Are there any other ways that will work? Thank you.

答:
Here is a simple solution:

<button (click)="fileInput.click()">
  <md-icon>library_add</md-icon>
  Select
  <input #fileInput type="file" (change)="onFileInput($event)" style="display:none;" />
</button>
```

Body:
How can I use angular material 2 FAB buttons to open a browse input dialog? This can be done in HTML by this way.

<button type="button">
    click
</button>
<input type="file" id="file-input" style="display:none">

I tried following the same approach with material 2, but it doesn't work.

<button md-mini-fab type="button">

        <md-icon>add</md-icon>

</button>
<input id="fileToUpload" type="file" style="display:none;">

Are there any other ways that will work? Thank you.

Body:
Here is a simple solution:

<button (click)="fileInput.click()">
  <md-icon>library_add</md-icon>
  <span>Select</span>
  <input #fileInput type="file" (change)="onFileInput($event)" style="display:none;" />
</button>

ContentLicense: CC BY-SA 4.0


问:
Cannot query Hive view which relies on UDTF
I've created a table as follows:

```<code>CREATE TABLE TEST (ID INT, SCORE INT, NAME STRING);
</code>```

and inserted several records. I would like to perform a top-k query, returning the top records for each ID, sorted by SCORE.

I'm using the each_top_k() UDF from the Hivemall library as documented here: https://hivemall.incubator.apache.org/userguide/misc/topk.html

```<code>SELECT EACH_TOP_K(1, ID, SCORE, ID, NAME) AS (RANK, SCORE, ID, NAME) FROM (
SELECT * FROM TEST
CLUSTER BY ID
) T;
</code>```

which successfully returns the top SCORE for each ID. However, I then create a view as follows:

```<code>CREATE VIEW TEST_VIEW AS SELECT EACH_TOP_K(1, ID, SCORE, ID, NAME) AS (RANK, SCORE, ID, NAME) FROM (
SELECT * FROM TEST
CLUSTER BY ID
) T;
</code>```

and it executes successfully. However, then a simple

```<code>SELECT * FROM TEST_VIEW;
</code>```

returns the following error:

Error: Error while compiling statement: FAILED: SemanticException View
  test_view is corresponding to UDTF, rather than a SelectOperator.
  (state=42000,code=40000)

I can't find any mention of this error. Any suggestions?

答:
I would suppose that Hive has problems to infer the data type for each field for your udtf at runtime. This should solve it, try put a query on top of your query, something like </p>

```<code>CREATE VIEW TEST_VIEW AS
select cast(rank as long) as rank, cast(score as double) as score, cast(id as string) as id, cast(name as string) as name from (
SELECT EACH_TOP_K(1, ID, SCORE, ID, NAME) AS (RANK, SCORE, ID, NAME) FROM (
SELECT * FROM TEST
CLUSTER BY ID
) T ) t2;
</code>```

Body:
I've created a table as follows:

CREATE TABLE TEST (ID INT, SCORE INT, NAME STRING);

and inserted several records. I would like to perform a top-k query, returning the top records for each ID, sorted by SCORE.

I'm using the each_top_k() UDF from the Hivemall library as documented here: https://hivemall.incubator.apache.org/userguide/misc/topk.html

SELECT EACH_TOP_K(1, ID, SCORE, ID, NAME) AS (RANK, SCORE, ID, NAME) FROM (
SELECT * FROM TEST
CLUSTER BY ID
) T;

which successfully returns the top SCORE for each ID. However, I then create a view as follows:

CREATE VIEW TEST_VIEW AS SELECT EACH_TOP_K(1, ID, SCORE, ID, NAME) AS (RANK, SCORE, ID, NAME) FROM (
SELECT * FROM TEST
CLUSTER BY ID
) T;

and it executes successfully. However, then a simple

SELECT * FROM TEST_VIEW;

returns the following error:

Error: Error while compiling statement: FAILED: SemanticException View
  test_view is corresponding to UDTF, rather than a SelectOperator.
  (state=42000,code=40000)

I can't find any mention of this error. Any suggestions?

Body:
I would suppose that Hive has problems to infer the data type for each field for your udtf at runtime. This should solve it, try put a query on top of your query, something like

CREATE VIEW TEST_VIEW AS
select cast(rank as long) as rank, cast(score as double) as score, cast(id as string) as id, cast(name as string) as name from (
SELECT EACH_TOP_K(1, ID, SCORE, ID, NAME) AS (RANK, SCORE, ID, NAME) FROM (
SELECT * FROM TEST
CLUSTER BY ID
) T ) t2;


问:
XAMPP MySQL can't start
I installed xampp but mysql can't start. I have read several threads related to it, but answers there don't work for me. It keeps halting when I tried to start mysql after changing the port or even after stopping process of another mysql server. even after trying to reboot the OS and install xampp as administrator. please help. This is the error that I got:</p>

```<code>13:10:04  [mysql]   Attempting to start MySQL service...
13:10:17  [mysql]   Problem detected!
13:10:17  [mysql]   Port 3306 in use by "C:\AppServ\mysql\bin\mysqld-nt.exe MySQL"!
13:10:17  [mysql]   MySQL WILL NOT start without the configured ports free!
13:10:17  [mysql]   You need to uninstall/disable/reconfigure the blocking application
13:10:17  [mysql]   or reconfigure MySQL and the Control Panel to listen on a different port
13:10:17  [mysql]   Attempting to start MySQL service...
</code>```

答:
I had faced several issues and I can relate to this question, as its not always clear how to get mysql working on xampp; especially if u r new to a xampp environment.

Try this thread.

How can I access the MySQL command line with XAMPP for Windows?

It should get you started.

Title: XAMPP MySQL can't start

Body:
I installed xampp but mysql can't start. I have read several threads related to it, but answers there don't work for me. It keeps halting when I tried to start mysql after changing the port or even after stopping process of another mysql server. even after trying to reboot the OS and install xampp as administrator. please help. This is the error that I got:

13:10:04  [mysql]   Attempting to start MySQL service...
13:10:17  [mysql]   Problem detected!
13:10:17  [mysql]   Port 3306 in use by "C:\AppServ\mysql\bin\mysqld-nt.exe MySQL"!
13:10:17  [mysql]   MySQL WILL NOT start without the configured ports free!
13:10:17  [mysql]   You need to uninstall/disable/reconfigure the blocking application
13:10:17  [mysql]   or reconfigure MySQL and the Control Panel to listen on a different port
13:10:17  [mysql]   Attempting to start MySQL service...


问:
My code gets the error expected ')'
I have tried to look for any curly brackets or parenthesis that don't have a pair but I can't find anything. Please let me know if you find the error or any other errors. The code is supposed to take the amount of minutes you take in the shower and turn it into the amount of bottles or water you used.

```<code>#include <stdio.h>
#include <cs50.h>

int main(void)

{
printf("Minutes: ");
int minutes = get_int();

if (minutes >0)
{
    int bottles = (128*(1.5*minutes)/16);
    printf("Bottles:%i \n "bottles);
}
else
{
    printf("Please type in a positive integer\n");
}

}
</code>```

Thanks for your help! :)

答:
this?</p>

```<code> printf("Bottles:%i \n ", bottles);
</code>```

Title: My code gets the error expected ')'

Body:
I have tried to look for any curly brackets or parenthesis that don't have a pair but I can't find anything. Please let me know if you find the error or any other errors. The code is supposed to take the amount of minutes you take in the shower and turn it into the amount of bottles or water you used.

#include <stdio.h>
#include <cs50.h>

int main(void)

{
printf("Minutes: ");
int minutes = get_int();

if (minutes >0)
{
    int bottles = (128*(1.5*minutes)/16);
    printf("Bottles:%i \n "bottles);
}
else
{
    printf("Please type in a positive integer\n");
}

}

Thanks for your help! :)

Body:
this?

 printf("Bottles:%i \n ", bottles);


问:
Guidelines for testing multithreaded code or ensuring that code is thread-safe
Are there any guidelines for testing multi-threaded code (other than throwing a bunch of threads at the problem and crossing your fingers).

I'm basically looking for good ways to test for data corruption, deadlocks, and other concurrency issues. Essentially I want to be able to prove that the code is thread-safe via a test.

Are there any frameworks in Java that let you easily write tests for a multithreaded scenario?

答:
I have written a lot of multi-threaded code and have never found anything much that can easily test for concurrency correctness issues that I haven't predicted. Most of the time I have to think about the scenario in which it may break and then how I might prove its correctness in an extreme version of this (often using CountDownLatches or similar to bend it in the ways I think it may break.

Definitely use FindBugs and similar static analysis tools to help find potential problems, and definitely keep your concurrency problems as simple as possible. Shared mutable memory problems are hard but it is actually quite easy to redefine the problem so you don't share mutable state, only immutable state. That makes life much simpler. Oh, and read JCiP – then read it again. And get your code reviewed.


问:
Angular 2 - testing component with router-outlet
I have created angular 2 project with angular-cli. I created separate AppRoutingModule which exports RouterModule and is added to AppModule imports array.

I have also appComponent created by angular-cli.

app.component.html

```<code><nav>
  <a *ngFor="let view of views" routerLink="{{ view.address }}" routerLinkActive="active">{{ view.text }}</a>
</nav>
<router-outlet></router-outlet>
</code>```

app.component.spec.ts

```<code>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('App: AquaparkFrontend', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    });
  });

  it('should create the app', async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it(`should have 3 views`, () => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app.views.length).toEqual(3);
  });
});
</code>```

When I try to run tests with ng test I have error:

```<code> Can't bind to 'routerLink' since it isn't a known property of 'a'. ("<nav>
      <a *ngFor="let view of views" [ERROR ->]routerLink="{{ view.address }}" routerLinkActive="active">{{ view.text }}</a>
    </nav>
    <router-outlet><"
</code>```

Do I miss something to import in test?

答:
<router-outlet> is a component in Angular2+, so need to be recognised.

So you need RouterTestingModule to test the route, otherwise, you get the error, import it from router/testing like this in your spec:

```<code>import { RouterTestingModule } from '@angular/router/testing';
</code>```

and then use it in import[] section like this:

```<code>describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports:[
        RouterTestingModule //<<< import it here also
      ],
      declarations: [
        AppComponent
      ],
      providers: [{ provide: APP_BASE_HREF, useValue: '/' }]

    }).compileComponents();
  }));
</code>```

Body:
I have created angular 2 project with angular-cli. I created separate AppRoutingModule which exports RouterModule and is added to AppModule imports array.

I have also appComponent created by angular-cli.

app.component.html

  {{ view.text }}

<router-outlet></router-outlet>

app.component.spec.ts

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('App: AquaparkFrontend', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    });
  });

  it('should create the app', async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it(`should have 3 views`, () => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app.views.length).toEqual(3);
  });
});

When I try to run tests with ng test I have error:

 Can't bind to 'routerLink' since it isn't a known property of 'a'. ("
      ]routerLink="{{ view.address }}" routerLinkActive="active">{{ view.text }}

    <router-outlet><"

Do I miss something to import in test?

Body:
<router-outlet> is a component in Angular2+, so need to be recognised.

So you need RouterTestingModule to test the route, otherwise, you get the error, import it from router/testing like this in your spec:

import { RouterTestingModule } from '@angular/router/testing';

and then use it in import[] section like this:

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports:[
        RouterTestingModule //<<< import it here also
      ],
      declarations: [
        AppComponent
      ],
      providers: [{ provide: APP_BASE_HREF, useValue: '/' }]

    }).compileComponents();
  }));


问:
How to custom url without change resources?
Our website is rails 4.2.8 and ruby 2.4.1, we have products to sell, so our routes like:

```<code>resources :products
resources :orders, only: [:new, :create, :destroy] do
        collection do
          get :success
          get :fail
          get :details
        end
</code>```

so orders url like: https://example.com/orders/new?params...

but we want add product name on url for tracking purpose, something like:

https://example.com/product_name/orders/new?params...

can I accomplish this without change route resources or controller position?

答:
In short, No you cannot..
You have to define such nested routes in your routes.rb which will change the paths and so all dependencies needs to be changed..

To be honest,

https://example.com/product_name/orders/new?params this url doesn't make sense to me..
Ideally, correct me if I am wrong, your order must be having has_many relation with the products. However, the url conveys different story...

Body:
Our website is rails 4.2.8 and ruby 2.4.1, we have products to sell, so our routes like:

resources :products
resources :orders, only: [:new, :create, :destroy] do
        collection do
          get :success
          get :fail
          get :details
        end

so orders url like: https://example.com/orders/new?params...

but we want add product name on url for tracking purpose, something like:

https://example.com/product_name/orders/new?params...

can I accomplish this without change route resources or controller position?


问:
http://localhost:50070 does not work HADOOP
I already installed Hadoop on my machine "Ubuntu 13.05" and now I have an error when browsing localhost:50070 the browser says that the page does not exist.</p>

答:
Try

```<code>namenode -format
start-all.sh
stop-all.sh
jps
</code>```

see namenode and datanode are running and browse

```<code>localhost:50070
</code>```

If localhost:50070 is still not working, then you need to allows ports. So, check

```<code>netstat -anp | grep 50070
</code>```

Body:
Try

namenode -format
start-all.sh
stop-all.sh
jps

see namenode and datanode are running and browse

localhost:50070

If localhost:50070 is still not working, then you need to allows ports. So, check

netstat -anp | grep 50070


答:
printf("Bottles:%i \n ",bottles);

add the missing comma

Title: My code gets the error expected ')'


问:
java.lang.ClassNotFoundException when submitting scala app to standalone spark cluster
I'm trying to use a Spark cluster with an application that depends only on scala 2.11 (the code is in scala), spark 2.1.0 and java 8.

My cluster is composed of 2 nodes and 1 master, each of them got all dependencies(jars), project files at the same place on an account with the same name (spark) and the same OS (Ubuntu 16.04.2 LTS).

The code I'm trying to run in IntelliJIdea :

```<code>import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.graphx._

object Main extends App {

val sparkConf = new SparkConf()
          .setAppName("Application")
          .setMaster("spark://<IP-Address-Master>:7077")
val sparkContext = new SparkContext(sparkConf)
sparkContext.setLogLevel("ERROR")

val NB_VERTICES = 50 // vertices count (TO ADAPT)
val DENSITY = 50 // graph density (TO ADAPT)

var graph = generateGraph(NB_VERTICES, sparkContext, DENSITY)// graph generation based on vertices number and density

var hasChanged = true // boolean to loop over

while(hasChanged){
  previousGraph = graph // Save previous graph
  graph = execute(graph, 1) // Execute 1 iteration of our algorithm
  hasChanged = hasGraphChanged(previousGraph, graph) // Verify if it has changed, if it's false we break out of the loop
      }
}
</code>```

Precision : I didn't put functions like 'generateGraph' etc because i think it would make the post too long.
But important to know : this code works perfectly when runned in local instead of the cluster.
It only depend  on spark graphX, scala and java.

So when I have my cluster up and running (each worker registered and visible on web UI), I try to run this application and I get the following error :

```<code>17/06/08 16:05:00 INFO SparkContext: Running Spark version 2.1.0
17/06/08 16:05:01 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/06/08 16:05:01 WARN Utils: Your hostname, workstation resolves to a loopback address: 127.0.1.1; using 172.16.24.203 instead (on interface enx28f10e4fec2a)
17/06/08 16:05:01 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
17/06/08 16:05:01 INFO SecurityManager: Changing view acls to: spark
17/06/08 16:05:01 INFO SecurityManager: Changing modify acls to: spark
17/06/08 16:05:01 INFO SecurityManager: Changing view acls groups to:
17/06/08 16:05:01 INFO SecurityManager: Changing modify acls groups to:
17/06/08 16:05:01 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(spark); groups with view permissions: Set(); users  with modify permissions: Set(spark); groups with modify permissions: Set()
17/06/08 16:05:02 INFO Utils: Successfully started service 'sparkDriver' on port 42652.
17/06/08 16:05:02 INFO SparkEnv: Registering MapOutputTracker
17/06/08 16:05:02 INFO SparkEnv: Registering BlockManagerMaster
17/06/08 16:05:02 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
17/06/08 16:05:02 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
17/06/08 16:05:02 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-fe269631-606f-4e03-a75a-82809f4dce2d
17/06/08 16:05:02 INFO MemoryStore: MemoryStore started with capacity 869.7 MB
17/06/08 16:05:02 INFO SparkEnv: Registering OutputCommitCoordinator
17/06/08 16:05:02 INFO Utils: Successfully started service 'SparkUI' on port 4040.
17/06/08 16:05:02 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://172.16.24.203:4040
17/06/08 16:05:02 INFO StandaloneAppClient$ClientEndpoint: Connecting to master spark://172.16.24.203:7077...
17/06/08 16:05:03 INFO TransportClientFactory: Successfully created connection to /172.16.24.203:7077 after 50 ms (0 ms spent in bootstraps)
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: Connected to Spark cluster with app ID app-20170608160503-0000
17/06/08 16:05:03 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 42106.
17/06/08 16:05:03 INFO NettyBlockTransferService: Server created on 172.16.24.203:42106
17/06/08 16:05:03 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
17/06/08 16:05:03 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO BlockManagerMasterEndpoint: Registering block manager 172.16.24.203:42106 with 869.7 MB RAM, BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20170608160503-0000/0 on worker-20170608145510-172.16.24.196-41159 (172.16.24.196:41159) with 8 cores
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: Granted executor ID app-20170608160503-0000/0 on hostPort 172.16.24.196:41159 with 8 cores, 1024.0 MB RAM
17/06/08 16:05:03 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20170608160503-0000/1 on worker-20170608185509-172.16.24.210-42227 (172.16.24.210:42227) with 4 cores
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: Granted executor ID app-20170608160503-0000/1 on hostPort 172.16.24.210:42227 with 4 cores, 1024.0 MB RAM
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20170608160503-0000/0 is now RUNNING
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20170608160503-0000/1 is now RUNNING
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0
17/06/08 16:05:10 ERROR TaskSetManager: Task 1 in stage 6.0 failed 4 times; aborting job
Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 6.0 failed 4 times, most recent failure: Lost task 1.3 in stage 6.0 (TID 14, 172.16.24.196, executor 0): java.lang.ClassNotFoundException: Main$$anonfun$3
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:67)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1819)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1986)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
    at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:85)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1958)
    at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:935)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.collect(RDD.scala:934)
    at Main$.hasGraphChanged(Main.scala:168)
    at Main$.main(Main.scala:401)
    at Main.main(Main.scala)
Caused by: java.lang.ClassNotFoundException: Main$$anonfun$3
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:67)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1819)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1986)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
    at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:85)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

It appears they all register and get granted access to run this app but they fail anyway.

I tried running a simple Pi approximation in the spark-shell and it worked nice and distributed on the cluster. I don't know what it could be I tried lot of methods proposed here (setting env for JARS on each nodes, using SparkConf.addJars to add them manually etc) and i still got this error.

Anyone has an idea of what it could be ?

Thanks a lot.

答:
Is the code shown the entire code?! If so, that's exactly the issue.

Wrap your code inside an object, say object SparkApp with main entry method, and start over.

```<code>object SparkApp {
  def main(args: Array[String]): Unit = {
    // ...your code here
  }
}
</code>```

You could also use object SparkApp extends App, but that is known to sometimes lead to failures.

I'd highly recommend using the latest and greatest of Spark 2.1.1.

Body:
I'm trying to use a Spark cluster with an application that depends only on scala 2.11 (the code is in scala), spark 2.1.0 and java 8.

My cluster is composed of 2 nodes and 1 master, each of them got all dependencies(jars), project files at the same place on an account with the same name (spark) and the same OS (Ubuntu 16.04.2 LTS).

The code I'm trying to run in IntelliJIdea :

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.graphx._

object Main extends App {

val sparkConf = new SparkConf()
          .setAppName("Application")
          .setMaster("spark://<IP-Address-Master>:7077")
val sparkContext = new SparkContext(sparkConf)
sparkContext.setLogLevel("ERROR")

val NB_VERTICES = 50 // vertices count (TO ADAPT)
val DENSITY = 50 // graph density (TO ADAPT)

var graph = generateGraph(NB_VERTICES, sparkContext, DENSITY)// graph generation based on vertices number and density

var hasChanged = true // boolean to loop over

while(hasChanged){
  previousGraph = graph // Save previous graph
  graph = execute(graph, 1) // Execute 1 iteration of our algorithm
  hasChanged = hasGraphChanged(previousGraph, graph) // Verify if it has changed, if it's false we break out of the loop
      }
}

Precision : I didn't put functions like 'generateGraph' etc because i think it would make the post too long.
But important to know : this code works perfectly when runned in local instead of the cluster.
It only depend  on spark graphX, scala and java.

So when I have my cluster up and running (each worker registered and visible on web UI), I try to run this application and I get the following error :

17/06/08 16:05:00 INFO SparkContext: Running Spark version 2.1.0
17/06/08 16:05:01 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/06/08 16:05:01 WARN Utils: Your hostname, workstation resolves to a loopback address: 127.0.1.1; using 172.16.24.203 instead (on interface enx28f10e4fec2a)
17/06/08 16:05:01 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
17/06/08 16:05:01 INFO SecurityManager: Changing view acls to: spark
17/06/08 16:05:01 INFO SecurityManager: Changing modify acls to: spark
17/06/08 16:05:01 INFO SecurityManager: Changing view acls groups to:
17/06/08 16:05:01 INFO SecurityManager: Changing modify acls groups to:
17/06/08 16:05:01 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(spark); groups with view permissions: Set(); users  with modify permissions: Set(spark); groups with modify permissions: Set()
17/06/08 16:05:02 INFO Utils: Successfully started service 'sparkDriver' on port 42652.
17/06/08 16:05:02 INFO SparkEnv: Registering MapOutputTracker
17/06/08 16:05:02 INFO SparkEnv: Registering BlockManagerMaster
17/06/08 16:05:02 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
17/06/08 16:05:02 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
17/06/08 16:05:02 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-fe269631-606f-4e03-a75a-82809f4dce2d
17/06/08 16:05:02 INFO MemoryStore: MemoryStore started with capacity 869.7 MB
17/06/08 16:05:02 INFO SparkEnv: Registering OutputCommitCoordinator
17/06/08 16:05:02 INFO Utils: Successfully started service 'SparkUI' on port 4040.
17/06/08 16:05:02 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://172.16.24.203:4040
17/06/08 16:05:02 INFO StandaloneAppClient$ClientEndpoint: Connecting to master spark://172.16.24.203:7077...
17/06/08 16:05:03 INFO TransportClientFactory: Successfully created connection to /172.16.24.203:7077 after 50 ms (0 ms spent in bootstraps)
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: Connected to Spark cluster with app ID app-20170608160503-0000
17/06/08 16:05:03 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 42106.
17/06/08 16:05:03 INFO NettyBlockTransferService: Server created on 172.16.24.203:42106
17/06/08 16:05:03 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
17/06/08 16:05:03 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO BlockManagerMasterEndpoint: Registering block manager 172.16.24.203:42106 with 869.7 MB RAM, BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20170608160503-0000/0 on worker-20170608145510-172.16.24.196-41159 (172.16.24.196:41159) with 8 cores
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: Granted executor ID app-20170608160503-0000/0 on hostPort 172.16.24.196:41159 with 8 cores, 1024.0 MB RAM
17/06/08 16:05:03 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, 172.16.24.203, 42106, None)
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20170608160503-0000/1 on worker-20170608185509-172.16.24.210-42227 (172.16.24.210:42227) with 4 cores
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: Granted executor ID app-20170608160503-0000/1 on hostPort 172.16.24.210:42227 with 4 cores, 1024.0 MB RAM
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20170608160503-0000/0 is now RUNNING
17/06/08 16:05:03 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20170608160503-0000/1 is now RUNNING
17/06/08 16:05:03 INFO StandaloneSchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0
17/06/08 16:05:10 ERROR TaskSetManager: Task 1 in stage 6.0 failed 4 times; aborting job
Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 6.0 failed 4 times, most recent failure: Lost task 1.3 in stage 6.0 (TID 14, 172.16.24.196, executor 0): java.lang.ClassNotFoundException: Main$$anonfun$3
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:67)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1819)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1986)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
    at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:85)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1958)
    at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:935)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.collect(RDD.scala:934)
    at Main$.hasGraphChanged(Main.scala:168)
    at Main$.main(Main.scala:401)
    at Main.main(Main.scala)
Caused by: java.lang.ClassNotFoundException: Main$$anonfun$3
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:67)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1819)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1986)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
    at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:85)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

It appears they all register and get granted access to run this app but they fail anyway.

I tried running a simple Pi approximation in the spark-shell and it worked nice and distributed on the cluster. I don't know what it could be I tried lot of methods proposed here (setting env for JARS on each nodes, using SparkConf.addJars to add them manually etc) and i still got this error.

Anyone has an idea of what it could be ?

Thanks a lot.

Body:
Is the code shown the entire code?! If so, that's exactly the issue.

Wrap your code inside an object, say object SparkApp with main entry method, and start over.

object SparkApp {
  def main(args: Array[String]): Unit = {
    // ...your code here
  }
}

You could also use object SparkApp extends App, but that is known to sometimes lead to failures.

I'd highly recommend using the latest and greatest of Spark 2.1.1.


问:
Deleting directories starting with certain name from HDFS in Java
i am trying to delete hive stage files from spark using the below code. This code can delete files in a directory, but i want to delete all file starting with '.hive-staging_hive'.

Can i know the way to delete the directories starting with certain text.

```<code> Configuration conf = new Configuration();
            System.out.println("560");
            Path output = new Path("hdfs://abcd/apps/hive/warehouse/mytest.db/cdri/.hive-staging_hive_2017-06-08_20-45-20_776_7391890064363958834-1/");
            FileSystem hdfs = FileSystem.get(conf);

            System.out.println("564");

            // delete existing directory
            if (hdfs.exists(output)) {
                System.out.println("568");
                hdfs.delete(output, true);
                System.out.println("570");

            }
</code>```

答:
The simple way is to run a process form Java program and use a wildcard to delete all the files starting with ".hive-staging_hive" in a directory.

```<code>String command="hadoop fs -rm pathToDirectory/.hive-staging_hive*";
int exitValue;
try {
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    exitValue = process.exitValue();
}catch (Exception e) {
    System.out.println("Cannot run command");
    e.printStackTrace();
}
</code>```

The next way is to list all files in the directories. Filter the files that starts with ".hive-staging_hive" and delete them.

```<code>Configuration conf = new Configuration();

Path path = new Path("hdfs://localhost:9000/tmp");

FileSystem fs = FileSystem.get(path.toUri(), conf);

FileStatus[] fileStatus = fs.listStatus(path);

List<FileStatus> filesToDelete = new ArrayList<FileStatus>();

for (FileStatus file: fileStatus) {

    if (file.getPath().getName().startsWith(".hive-staging_hive")){
        filesToDelete.add(file);
    }
}

for (int i=0; i<filesToDelete.size();i++){
    fs.delete(filesToDelete.get(i).getPath(), true);
}
</code>```

Hope this helps!

Body:
i am trying to delete hive stage files from spark using the below code. This code can delete files in a directory, but i want to delete all file starting with '.hive-staging_hive'.

Can i know the way to delete the directories starting with certain text.

 Configuration conf = new Configuration();
            System.out.println("560");
            Path output = new Path("hdfs://abcd/apps/hive/warehouse/mytest.db/cdri/.hive-staging_hive_2017-06-08_20-45-20_776_7391890064363958834-1/");
            FileSystem hdfs = FileSystem.get(conf);

            System.out.println("564");

            // delete existing directory
            if (hdfs.exists(output)) {
                System.out.println("568");
                hdfs.delete(output, true);
                System.out.println("570");

            }

Body:
The simple way is to run a process form Java program and use a wildcard to delete all the files starting with ".hive-staging_hive" in a directory.

String command="hadoop fs -rm pathToDirectory/.hive-staging_hive*";
int exitValue;
try {
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    exitValue = process.exitValue();
}catch (Exception e) {
    System.out.println("Cannot run command");
    e.printStackTrace();
}

The next way is to list all files in the directories. Filter the files that starts with ".hive-staging_hive" and delete them.

Configuration conf = new Configuration();

Path path = new Path("hdfs://localhost:9000/tmp");

FileSystem fs = FileSystem.get(path.toUri(), conf);

FileStatus[] fileStatus = fs.listStatus(path);

List<FileStatus> filesToDelete = new ArrayList<FileStatus>();

for (FileStatus file: fileStatus) {

    if (file.getPath().getName().startsWith(".hive-staging_hive")){
        filesToDelete.add(file);
    }
}

for (int i=0; i<filesToDelete.size();i++){
    fs.delete(filesToDelete.get(i).getPath(), true);
}

Hope this helps!


问:
Request a connection after the form is opened as in postForm in statemachine
I've shifted to barebone code from statemachine. Here I've code(connectionRequest) inside constructor.Hence connection is called before the new form is opened. What I need is that: after the new form is opened, the connection should be called. In statemachine, if I request a connection in postForm, the form will open and then the connectionRequest is called. How can I do that here?

Home.java

```<code>public class Home extends Form {
    public Home() {
        Button test = new Button("Test");
        add(test);

        test.addActionListener(e->{
            new Test().show();
        });
    }
}
</code>```

Test.java

```<code>public class Test extends Form{
    public Test(){
        Label nameLabel = new Label("");
        add(nameLabel);

        ConnectionRequest cr = new ConnectionRequest() {

            @Override
            protected void readResponse(InputStream input) throws IOException {
                JSONParser jp = new JSONParser();
                Map parser = jp.parseJSON(new InputStreamReader(input));
                String name = (String) parser.get("name");
                nameLabel.setText(name);
            }
        };
        cr.setUrl("test.com");
        NetworkManager.getInstance().addToQueueAndWait(cr);
    }
}
</code>```

答: You can use addShowListener and call the connection request there.

Body:
I've shifted to barebone code from statemachine. Here I've code(connectionRequest) inside constructor.Hence connection is called before the new form is opened. What I need is that: after the new form is opened, the connection should be called. In statemachine, if I request a connection in postForm, the form will open and then the connectionRequest is called. How can I do that here?

Home.java

public class Home extends Form {
    public Home() {
        Button test = new Button("Test");
        add(test);

        test.addActionListener(e->{
            new Test().show();
        });
    }
}

Test.java

public class Test extends Form{
    public Test(){
        Label nameLabel = new Label("");
        add(nameLabel);

        ConnectionRequest cr = new ConnectionRequest() {

            @Override
            protected void readResponse(InputStream input) throws IOException {
                JSONParser jp = new JSONParser();
                Map parser = jp.parseJSON(new InputStreamReader(input));
                String name = (String) parser.get("name");
                nameLabel.setText(name);
            }
        };
        cr.setUrl("test.com");
        NetworkManager.getInstance().addToQueueAndWait(cr);
    }
}


问:
Where does android.max_aspect meta make difference?
A recent blog explains that we must use

```<code><meta-data android:name="android.max_aspect" android:value="2.1" />
</code>```

in <application> element of AndroidManifest.xml for optimal display on super widescreen devices, e.g. Samsung Galaxy S8.

To test this, I installed my app (no max_aspect, no resizeableActivity flags; targetSdkVersion=22, compileSdkVersion=24) on an Android 7.1.1. emulator with custom 2960x1440 resolution. All activities, including immersive, fill the screen with no margins as shown in the blog post.

I added explicit

```<code><meta-data android:name="android.max_aspect" android:value="1.5" />
</code>```

and this also had no effect on the emulator.

So, the question: is this meta flag only checked on the real devices, or there is some configuration that I missed for my emulator?

Update: I tried to reach Neto Marin, the author of the cited blog post. I found a proud tweet  about his contribution to the global Android Dev community, but could not get an answer from him.

答:
You have to set the emulator's aspect ratio as per your need.

Try these steps:

```<code>In Android Studio, open AVD Manager
Create Virtual Device
    New Hardware Profile
    Set name: "18:9 aspect ratio screen"
    Set resolution: 1080 x 2160
    Finish
Select "18:9 aspect ratio screen"
Next
Select system image Nougat (API Level 25)
Next
AVD Name: "API Level 25 Nougat 18x9 aspect ratio screen"
Finish
</code>```

Then run on this emulator.

If you don't set a value, and android:resizeableActivity is not true, then the maximum aspect ratio defaults to 1.86 (roughly 16:9) and your app will not take advantage of the extra screen space.

You do not need to set a maximum aspect ratio if an activity's android:resizeableActivity attribute is set to true. If your app targets API level 24 or higher, this attribute defaults to true.

Body:
A recent blog explains that we must use

<meta-data android:name="android.max_aspect" android:value="2.1" />

in <application> element of AndroidManifest.xml for optimal display on super widescreen devices, e.g. Samsung Galaxy S8.

To test this, I installed my app (no max_aspect, no resizeableActivity flags; targetSdkVersion=22, compileSdkVersion=24) on an Android 7.1.1. emulator with custom 2960x1440 resolution. All activities, including immersive, fill the screen with no margins as shown in the blog post.

I added explicit

<meta-data android:name="android.max_aspect" android:value="1.5" />

and this also had no effect on the emulator.

So, the question: is this meta flag only checked on the real devices, or there is some configuration that I missed for my emulator?

Update: I tried to reach Neto Marin, the author of the cited blog post. I found a proud tweet  about his contribution to the global Android Dev community, but could not get an answer from him.

Body:
You have to set the emulator's aspect ratio as per your need.

Try these steps:

In Android Studio, open AVD Manager
Create Virtual Device
    New Hardware Profile
    Set name: "18:9 aspect ratio screen"
    Set resolution: 1080 x 2160
    Finish
Select "18:9 aspect ratio screen"
Next
Select system image Nougat (API Level 25)
Next
AVD Name: "API Level 25 Nougat 18x9 aspect ratio screen"
Finish

Then run on this emulator.

If you don't set a value, and android:resizeableActivity is not true, then the maximum aspect ratio defaults to 1.86 (roughly 16:9) and your app will not take advantage of the extra screen space.

You do not need to set a maximum aspect ratio if an activity's android:resizeableActivity attribute is set to true. If your app targets API level 24 or higher, this attribute defaults to true.


问:
Aspose slides 'Area chart' series value not shown in the tooltip
I am using aspose-slides-17.3-jdk16.jar for java. I have created the Area Chart using IChartDataWorkbook and I'm able to get the series values in the tool tip for all the charts except Area chart.

Following is the code I have done so far.

```<code>public class AreaChartSlide {

public static void main(String[] args) {

Presentation pres = new Presentation();

ISlide slide = pres.getSlides().get_Item(0);

// Creating the default chart
IChart chart = slide.getShapes().addChart(ChartType.Area, 0, 0, 500, 400);

// Getting the default chart data worksheet index
int defaultWorksheetIndex = 0;

// Getting the chart data worksheet
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();

// Delete demo series
chart.getChartData().getSeries().clear();

// Add new series
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 0, 1, "Series 1"), chart.getType());
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 0, 2, "Series 2"), chart.getType());

// Adding new categories
chart.getChartData().getCategories().add(fact.getCell(defaultWorksheetIndex, 1, 0, "Cat 1"));
chart.getChartData().getCategories().add(fact.getCell(defaultWorksheetIndex, 2, 0, "Cat 2"));

// Take first chart series
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
// Now populating series data
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 1, 1, 20));
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 2, 2, 50));
// Setting fill color for series
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(Color.RED);

// Take second chart series
series = chart.getChartData().getSeries().get_Item(1);
// Now populating series data
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 2, 1, 30));
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 2, 2, 10));
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(Color.GREEN);

pres.save("E:/PPT/Aspose.pptx", SaveFormat.Pptx);
System.out.println("done");

}
</code>```

Below is the chart output i got

Any help would be greatly appreciated.

答:
I have worked with shared sample code using Aspose.Slides for Java 17.5 on my end and have generated a presentation with Area chart having two series and two categories. I have opened the generated presentation in PowerPoint and able to observe the tool-tip text for both chart series. Please observe Series 1 and Series 2 tool-tip text display for your kind reference. I hope the shared information will be helpful. Please share, if I may help you further in this regard.

I am working as Support developer/ Evangelist at Aspose.

We are sorry for your inconvenience.

Body:
I am using aspose-slides-17.3-jdk16.jar for java. I have created the Area Chart using IChartDataWorkbook and I'm able to get the series values in the tool tip for all the charts except Area chart.

Following is the code I have done so far.

public class AreaChartSlide {

public static void main(String[] args) {

Presentation pres = new Presentation();

ISlide slide = pres.getSlides().get_Item(0);

// Creating the default chart
IChart chart = slide.getShapes().addChart(ChartType.Area, 0, 0, 500, 400);

// Getting the default chart data worksheet index
int defaultWorksheetIndex = 0;

// Getting the chart data worksheet
IChartDataWorkbook fact = chart.getChartData().getChartDataWorkbook();

// Delete demo series
chart.getChartData().getSeries().clear();

// Add new series
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 0, 1, "Series 1"), chart.getType());
chart.getChartData().getSeries().add(fact.getCell(defaultWorksheetIndex, 0, 2, "Series 2"), chart.getType());

// Adding new categories
chart.getChartData().getCategories().add(fact.getCell(defaultWorksheetIndex, 1, 0, "Cat 1"));
chart.getChartData().getCategories().add(fact.getCell(defaultWorksheetIndex, 2, 0, "Cat 2"));

// Take first chart series
IChartSeries series = chart.getChartData().getSeries().get_Item(0);
// Now populating series data
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 1, 1, 20));
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 2, 2, 50));
// Setting fill color for series
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(Color.RED);

// Take second chart series
series = chart.getChartData().getSeries().get_Item(1);
// Now populating series data
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 2, 1, 30));
series.getDataPoints().addDataPointForAreaSeries(fact.getCell(defaultWorksheetIndex, 2, 2, 10));
series.getFormat().getFill().setFillType(FillType.Solid);
series.getFormat().getFill().getSolidFillColor().setColor(Color.GREEN);

pres.save("E:/PPT/Aspose.pptx", SaveFormat.Pptx);
System.out.println("done");

}

Below is the chart output i got

Any help would be greatly appreciated.


问:
New To PHP = Investment Calculator feedback
I'm new to php and I'm wondering if I set this up right, for a question I have to do. I have to set up a loop that does $amount * (1 + $interest / 100) to find the number of years up to  $1000000. The initial amount is $10000, but I'm not quite sure if I set up my if statement correctly.

```<code><?php //Script investment.php

    //Address error handling.
    ini_set('display_errors',1);
    error_reporting(E_ALL & ~E_NOTICE);

    // In case register_globals is disabled.
    $return = 10000*(1+(15/100));
    $total = 1000000;

    if ($year=$total/$return/12){
        echo "number of years is : ".$year;
    }
?>
</code>```

答:
You can use this , </p>

```<code>$total = 1000000;
$year  = 0;
$amount = 10000;
$intrest = 15;

do {
    $int_amount = $amount*($intrest/100);
    $amount += $int_amount;
    $year++;
    echo "Year ".$year.", Amount = ".round($amount,2).", Intrest = ".round($int_amount,2)."<br/>";
} while ($amount <= $total);

echo "number of years is : ".$year;
</code>```

Body:
I'm new to php and I'm wondering if I set this up right, for a question I have to do. I have to set up a loop that does $amount * (1 + $interest / 100) to find the number of years up to  $1000000. The initial amount is $10000, but I'm not quite sure if I set up my if statement correctly.

<?php //Script investment.php

    //Address error handling.
    ini_set('display_errors',1);
    error_reporting(E_ALL & ~E_NOTICE);

    // In case register_globals is disabled.
    $return = 10000*(1+(15/100));
    $total = 1000000;

    if ($year=$total/$return/12){
        echo "number of years is : ".$year;
    }
?>

Body:
You can use this ,

$total = 1000000;
$year  = 0;
$amount = 10000;
$intrest = 15;

do {
    $int_amount = $amount*($intrest/100);
    $amount += $int_amount;
    $year++;
    echo "Year ".$year.", Amount = ".round($amount,2).", Intrest = ".round($int_amount,2)."<br/>";
} while ($amount <= $total);

echo "number of years is : ".$year;


问:
use an api recognition vision for android
I want to create an application android that films on the road as long as it is open, and if it detects an accident it sends a request to a database, I directly thought to google vision, but unfortunately it paid and so, I found watson's vision, how i can use it for android studio</p>

答:
You can write vision API,Cany Edge detection, add some machine learning and Artificial Intelligence In your code, Python is the best tool for this in terms of computation,Compile this code in the android and give video/image as Input.

your camera should always on in video recoding mode so that your code will get the video and convert it into the images and can detect if it is a incident.


问:
Layout large amount of Text
so i've got about 100 pages with different Text-Layouts. Bold Fonts in large paragraphs, italic, headlines etc .pp.

Now i'm wondering whats the best way to display them in my uiview. i cannot find an element that fits for me (UILable, Textfield, etc).

Whats the best way to do this? any ideas?

thanks for all hints!

答: Have you considered a UIWebView?</p>

Title: Layout large amount of Text

Body: Have you considered a UIWebView?


问:
EOFError in Devise::PasswordsController#create
I am running into an issue with mailing password resets from my Ruby on Rails application. The password reset mailing used to work, however, now it does not. Password resets are the only emails that the server sends. Once I submit the email that I'd like to get a password for, Rails displays this on full trace:

EOFError in Devise::PasswordsController#create
end of file reached

Rails.root: /home/path/to/app

```<code>/usr/lib/ruby/1.9.1/openssl/buffering.rb:174:in `sysread_nonblock'
/usr/lib/ruby/1.9.1/openssl/buffering.rb:174:in `read_nonblock'
/usr/lib/ruby/1.9.1/net/protocol.rb:141:in `rbuf_fill'
/usr/lib/ruby/1.9.1/net/protocol.rb:122:in `readuntil'
/usr/lib/ruby/1.9.1/net/protocol.rb:132:in `readline'
/usr/lib/ruby/1.9.1/net/smtp.rb:929:in `recv_response'
/usr/lib/ruby/1.9.1/net/smtp.rb:915:in `block in getok'
/usr/lib/ruby/1.9.1/net/smtp.rb:939:in `critical'
/usr/lib/ruby/1.9.1/net/smtp.rb:913:in `getok'
/usr/lib/ruby/1.9.1/net/smtp.rb:907:in `quit'
/usr/lib/ruby/1.9.1/net/smtp.rb:613:in `do_finish'
/usr/lib/ruby/1.9.1/net/smtp.rb:522:in `ensure in start'
/usr/lib/ruby/1.9.1/net/smtp.rb:522:in `start'
mail (2.5.4) lib/mail/network/delivery_methods/smtp.rb:112:in `deliver!'
mail (2.5.4) lib/mail/message.rb:2129:in `do_delivery'
mail (2.5.4) lib/mail/message.rb:232:in `block in deliver'
actionmailer (4.1.1) lib/action_mailer/base.rb:527:in `block in deliver_mail'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `block in instrument'
activesupport (4.1.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `instrument'
actionmailer (4.1.1) lib/action_mailer/base.rb:525:in `deliver_mail'
mail (2.5.4) lib/mail/message.rb:232:in `deliver'
devise (3.4.1) lib/devise/models/authenticatable.rb:178:in `send_devise_notification'
devise (3.4.1) lib/devise/models/recoverable.rb:99:in `send_reset_password_instructions_notification'
devise (3.4.1) lib/devise/models/recoverable.rb:49:in `send_reset_password_instructions'
devise (3.4.1) lib/devise/models/recoverable.rb:116:in `send_reset_password_instructions'
devise (3.4.1) app/controllers/devise/passwords_controller.rb:13:in `create'
actionpack (4.1.1) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.1.1) lib/abstract_controller/base.rb:189:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.1.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (4.1.1) lib/active_support/callbacks.rb:113:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:113:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:86:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:86:in `run_callbacks'
actionpack (4.1.1) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `block in instrument'
activesupport (4.1.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `instrument'
actionpack (4.1.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
actionpack (4.1.1) lib/abstract_controller/base.rb:136:in `process'
actionview (4.1.1) lib/action_view/rendering.rb:30:in `process'
actionpack (4.1.1) lib/action_controller/metal.rb:195:in `dispatch'
actionpack (4.1.1) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
actionpack (4.1.1) lib/action_controller/metal.rb:231:in `block in action'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:80:in `call'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:48:in `call'
actionpack (4.1.1) lib/action_dispatch/routing/mapper.rb:45:in `call'
actionpack (4.1.1) lib/action_dispatch/journey/router.rb:71:in `block in call'
actionpack (4.1.1) lib/action_dispatch/journey/router.rb:59:in `each'
actionpack (4.1.1) lib/action_dispatch/journey/router.rb:59:in `call'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:676:in `call'
warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
warden (1.2.3) lib/warden/manager.rb:34:in `catch'
warden (1.2.3) lib/warden/manager.rb:34:in `call'
rack (1.5.2) lib/rack/etag.rb:23:in `call'
rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
rack (1.5.2) lib/rack/head.rb:11:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/flash.rb:254:in `call'
rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/cookies.rb:560:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (4.1.1) lib/active_support/callbacks.rb:82:in `run_callbacks'
actionpack (4.1.1) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/reloader.rb:73:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.1.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.1.1) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.1.1) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.1.1) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
rack (1.5.2) lib/rack/runtime.rb:17:in `call'
activesupport (4.1.1) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/static.rb:64:in `call'
rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
railties (4.1.1) lib/rails/engine.rb:514:in `call'
railties (4.1.1) lib/rails/application.rb:144:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
rack (1.5.2) lib/rack/content_length.rb:14:in `call'
rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
/usr/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
/usr/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
/usr/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'
</code>```

My devise.rb contains:

```<code>config.mailer_sender = "accounts@mydomain.com"

# Configure the class responsible to send e-mails.
config.mailer = 'Devise::Mailer'
</code>```

My development.rb contains:

```<code>config.action_mailer.default_url_options = { :host => 'subdomain.mydomain.com' }
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"

config.action_mailer.smtp_settings = {
  address: "smtp-relay.gmail.com",       port: 465,
  domain: "mydomain.com",
  authentication: "plain",
  enable_starttls_auto: false,
  tls: true
}
</code>```

I'm not sure what exactly is going wrong here. The email is generated just fine, and displayed on the server logs. However, it hits a 500 error when attempting to send it.

Anyone know where I should look to figure out what's going on?

答:
Improper SMTP settings seem to be the cause of many EOFErrors with Devise.

Use ssl: true and remove any TLS options for port 465. If you'd rather use TLS, use port 587.

Source: Email client settings for Gmail

EDIT: Sorry, that suggestion was totally wrong. The tls and ssl options are actually just aliases of each other.

Note: According to this article, mail clients often use the terms “SSL” and “TLS” to refer not to the actual security protocols themselves, but rather to the practices of initiating a connection over a secure channel (so-called “SSL”) vs. starting off insecure, and then switching over to encrypted communication after establishing an initial handshake (so-called “TLS” but actually STARTTLS).

To clarify, you had it right to begin with:

port 465 can go with either ssl: true OR tls: true, and

port 587 goes with enable_starttls_auto: true (which is default, and thus not required).

So I don't know what was wrong with your configuration. Did you ever figure it out?

Body:
I am running into an issue with mailing password resets from my Ruby on Rails application. The password reset mailing used to work, however, now it does not. Password resets are the only emails that the server sends. Once I submit the email that I'd like to get a password for, Rails displays this on full trace:

EOFError in Devise::PasswordsController#create
end of file reached

Rails.root: /home/path/to/app

/usr/lib/ruby/1.9.1/openssl/buffering.rb:174:in `sysread_nonblock'
/usr/lib/ruby/1.9.1/openssl/buffering.rb:174:in `read_nonblock'
/usr/lib/ruby/1.9.1/net/protocol.rb:141:in `rbuf_fill'
/usr/lib/ruby/1.9.1/net/protocol.rb:122:in `readuntil'
/usr/lib/ruby/1.9.1/net/protocol.rb:132:in `readline'
/usr/lib/ruby/1.9.1/net/smtp.rb:929:in `recv_response'
/usr/lib/ruby/1.9.1/net/smtp.rb:915:in `block in getok'
/usr/lib/ruby/1.9.1/net/smtp.rb:939:in `critical'
/usr/lib/ruby/1.9.1/net/smtp.rb:913:in `getok'
/usr/lib/ruby/1.9.1/net/smtp.rb:907:in `quit'
/usr/lib/ruby/1.9.1/net/smtp.rb:613:in `do_finish'
/usr/lib/ruby/1.9.1/net/smtp.rb:522:in `ensure in start'
/usr/lib/ruby/1.9.1/net/smtp.rb:522:in `start'
mail (2.5.4) lib/mail/network/delivery_methods/smtp.rb:112:in `deliver!'
mail (2.5.4) lib/mail/message.rb:2129:in `do_delivery'
mail (2.5.4) lib/mail/message.rb:232:in `block in deliver'
actionmailer (4.1.1) lib/action_mailer/base.rb:527:in `block in deliver_mail'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `block in instrument'
activesupport (4.1.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `instrument'
actionmailer (4.1.1) lib/action_mailer/base.rb:525:in `deliver_mail'
mail (2.5.4) lib/mail/message.rb:232:in `deliver'
devise (3.4.1) lib/devise/models/authenticatable.rb:178:in `send_devise_notification'
devise (3.4.1) lib/devise/models/recoverable.rb:99:in `send_reset_password_instructions_notification'
devise (3.4.1) lib/devise/models/recoverable.rb:49:in `send_reset_password_instructions'
devise (3.4.1) lib/devise/models/recoverable.rb:116:in `send_reset_password_instructions'
devise (3.4.1) app/controllers/devise/passwords_controller.rb:13:in `create'
actionpack (4.1.1) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.1.1) lib/abstract_controller/base.rb:189:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.1.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (4.1.1) lib/active_support/callbacks.rb:113:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:113:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:229:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
activesupport (4.1.1) lib/active_support/callbacks.rb:86:in `call'
activesupport (4.1.1) lib/active_support/callbacks.rb:86:in `run_callbacks'
actionpack (4.1.1) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `block in instrument'
activesupport (4.1.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.1.1) lib/active_support/notifications.rb:159:in `instrument'
actionpack (4.1.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (4.1.1) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
actionpack (4.1.1) lib/abstract_controller/base.rb:136:in `process'
actionview (4.1.1) lib/action_view/rendering.rb:30:in `process'
actionpack (4.1.1) lib/action_controller/metal.rb:195:in `dispatch'
actionpack (4.1.1) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
actionpack (4.1.1) lib/action_controller/metal.rb:231:in `block in action'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:80:in `call'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:48:in `call'
actionpack (4.1.1) lib/action_dispatch/routing/mapper.rb:45:in `call'
actionpack (4.1.1) lib/action_dispatch/journey/router.rb:71:in `block in call'
actionpack (4.1.1) lib/action_dispatch/journey/router.rb:59:in `each'
actionpack (4.1.1) lib/action_dispatch/journey/router.rb:59:in `call'
actionpack (4.1.1) lib/action_dispatch/routing/route_set.rb:676:in `call'
warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
warden (1.2.3) lib/warden/manager.rb:34:in `catch'
warden (1.2.3) lib/warden/manager.rb:34:in `call'
rack (1.5.2) lib/rack/etag.rb:23:in `call'
rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
rack (1.5.2) lib/rack/head.rb:11:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/flash.rb:254:in `call'
rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/cookies.rb:560:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (4.1.1) lib/active_support/callbacks.rb:82:in `run_callbacks'
actionpack (4.1.1) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/reloader.rb:73:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.1.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.1.1) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.1.1) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.1.1) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
rack (1.5.2) lib/rack/runtime.rb:17:in `call'
activesupport (4.1.1) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
actionpack (4.1.1) lib/action_dispatch/middleware/static.rb:64:in `call'
rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
railties (4.1.1) lib/rails/engine.rb:514:in `call'
railties (4.1.1) lib/rails/application.rb:144:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
rack (1.5.2) lib/rack/content_length.rb:14:in `call'
rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
/usr/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
/usr/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
/usr/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

My devise.rb contains:

config.mailer_sender = "accounts@mydomain.com"

# Configure the class responsible to send e-mails.
config.mailer = 'Devise::Mailer'

My development.rb contains:

config.action_mailer.default_url_options = { :host => 'subdomain.mydomain.com' }
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"

config.action_mailer.smtp_settings = {
  address: "smtp-relay.gmail.com",       port: 465,
  domain: "mydomain.com",
  authentication: "plain",
  enable_starttls_auto: false,
  tls: true
}

I'm not sure what exactly is going wrong here. The email is generated just fine, and displayed on the server logs. However, it hits a 500 error when attempting to send it.

Anyone know where I should look to figure out what's going on?


问:
How to execute a batch file on uninstall in Inno Setup?
I'm using code from How do you execute command line tools without using batch file in Inno Setup response to execute all my batch files on installation (before, after).

Now I want to execute them just when user click "YES" to uninstaller, but can't find a way to do it. It executes before the confirmation

Here is my code from [Code] section:

function InitializeUninstall(): Boolean;
var
  ResultCode : Integer;
begin
  Result := True;
  Exec(ExpandConstant('{app}\scripts\unset.bat'), '', '',
       SW_HIDE, ewWaitUntilTerminated, ResultCode);
end;
```

答:
Move your code to the CurUninstallStepChanged(usUninstall). That event is triggered after the confirmation of uninstallation.

procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
  ResultCode : Integer;
begin
  if CurUninstallStep = usUninstall then
  begin
    Exec(ExpandConstant('{app}\scripts\unset.bat'), '', '',
         SW_HIDE, ewWaitUntilTerminated, ResultCode);
  end;
end;
```
<hr />
<p>Though it's easier to use <code>[UninstallRun]</code> section.</p>
```[UninstallRun]
Filename: "{app}\scripts\unset.bat"; Flags: runhidden
```

The section is also processed after the confirmation, but before any files are uninstalled. See Uninstallation order.

Note that in general, you should not use batch files. You better script everything in Pascal code. That way you get much more robust code and better error handling.

Note that ironically, the question you point to was asked to avoid using batch files in Inno Setup.

Body:
Move your code to the CurUninstallStepChanged(usUninstall). That event is triggered after the confirmation of uninstallation.

procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
  ResultCode : Integer;
begin
  if CurUninstallStep = usUninstall then
  begin
    Exec(ExpandConstant('{app}\scripts\unset.bat'), '', '',
         SW_HIDE, ewWaitUntilTerminated, ResultCode);
  end;
end;

Though it's easier to use [UninstallRun] section.

[UninstallRun]
Filename: "{app}\scripts\unset.bat"; Flags: runhidden

The section is also processed after the confirmation, but before any files are uninstalled. See Uninstallation order.

Note that in general, you should not use batch files. You better script everything in Pascal code. That way you get much more robust code and better error handling.

Note that ironically, the question you point to was asked to avoid using batch files in Inno Setup.


问:
Jenkins UI : Read from properties File
I am trying to create a job and select Extended Choice Parameters option, where in the Parameter Type I select is Multi-Level Multi Select. It asks me for a property file. I have a normal Maven workspace , wherein I have included a certain test.properties file in the basedir of the project. However I am not sure how to retrieve the same in the Jenkins UI.

It does not take any path. I am new to Jenkins. How can we read properties from a file, directly into Jenkins UI for Extended Choice Parameters?

答:
You can add property file by EnvInject plugin
See http://www.360logica.com/blog/how-to-change-the-data-into-properties-file-using-jenkins/</p>

Title: Jenkins UI : Read from properties File