问:
Laravel multiple PDF to ZIP
I am making an external API call which returns several objects with download URL inside. Those are all PDF-s of which I would like to provide a single ZIP download link.

The way it works now is that I am downloading every single PDF to a specific user folder, and then making a ZIP out of it and presenting it back to user.

I see this as a somewhat slow and inefficient of doing things as the user will have to trigger another download for the ZIP, and this way I am making user wait basically for 2 downloads of the same file batch.

Is there a smarter way to deal with this?

```<code>$path = '/user_downloads/' . Auth::user()->id . '/';

if (!Storage::disk('uploads')->has($path)) {
    Storage::disk('uploads')->makeDirectory($path);
}

$zipper = new \Chumper\Zipper\Zipper;
$zip_filename = 'zipped/' . uniqid() . '_merged.zip';
foreach (json_decode($res)->hits as $hit) {
    $filename = public_path() . $path . uniqid() . '_file.pdf';
    copy($hit->document_download_link, $filename);
    $zipper->make($zip_filename)->add($filename);
}
</code>```

答:
The add method can receive an array of files, so, I would create the array of files inside the foreach and when finished, create the zip:

```<code>foreach (json_decode($res)->hits as $hit) {
copy($hit->document_download_link, $filename);
$files[] = public_path() . $path . uniqid() . '_file.pdf';
}

 $zipper->make($zip_filename)->add($files);
</code>```

Title: Laravel multiple PDF to ZIP

Body:
I am making an external API call which returns several objects with download URL inside. Those are all PDF-s of which I would like to provide a single ZIP download link.

The way it works now is that I am downloading every single PDF to a specific user folder, and then making a ZIP out of it and presenting it back to user.

I see this as a somewhat slow and inefficient of doing things as the user will have to trigger another download for the ZIP, and this way I am making user wait basically for 2 downloads of the same file batch.

Is there a smarter way to deal with this?

$path = '/user_downloads/' . Auth::user()->id . '/';

if (!Storage::disk('uploads')->has($path)) {
    Storage::disk('uploads')->makeDirectory($path);
}

$zipper = new \Chumper\Zipper\Zipper;
$zip_filename = 'zipped/' . uniqid() . '_merged.zip';
foreach (json_decode($res)->hits as $hit) {
    $filename = public_path() . $path . uniqid() . '_file.pdf';
    copy($hit->document_download_link, $filename);
    $zipper->make($zip_filename)->add($filename);
}

Body:
The add method can receive an array of files, so, I would create the array of files inside the foreach and when finished, create the zip:

foreach (json_decode($res)->hits as $hit) {
copy($hit->document_download_link, $filename);
$files[] = public_path() . $path . uniqid() . '_file.pdf';
}

 $zipper->make($zip_filename)->add($files);


来源: stackexchange

问:
I am unable to use database in fragments in android
I am using Database in a fragment. However when I try to initialize my database Using the line:

```<code>database=openOrCreateDatabase("firstdatabase",MODE_PRIVATE,null);
</code>```

It gives me an error saying:

Error:(47, 55) error: cannot find symbol variable MODE_PRIVATE

This is my code:

```<code>public class Expenses extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.expenses,container,false);

    final SQLiteDatabase database;
    Cursor c;
    ArrayList<String> al=new ArrayList<>();

    ImageButton img=(ImageButton)v.findViewById(R.id.img);
    final EditText commodity=(EditText)v.findViewById(R.id.commodity);
    final EditText amount=(EditText)v.findViewById(R.id.amount);
    ListView list=(ListView)v.findViewById(R.id.list);

    Calendar calendar=Calendar.getInstance();
    final int day=calendar.get(Calendar.DAY_OF_MONTH);
    final int month=calendar.get(Calendar.MONTH);
    final int year=calendar.get(Calendar.YEAR);

    registerForContextMenu(list);
    database=openOrCreateDatabase("firstdatabase",MODE_PRIVATE,null);

    img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getContext(), "Entered Successfully", Toast.LENGTH_SHORT).show();
            String c=commodity.getText().toString();
            int a=Integer.parseInt(amount.getText().toString());
            String q2="insert into expenses(day,month,year,commodity,amount)values('"+day+ "','" +month+ "','" +year+"','"+c+"','"+a+"');";
            database.execSQL(q2);
        }
    });

    String q1 = "select * from expenses";

    c = database.rawQuery(q1, null);

    c.moveToFirst();
    do {
        String comm = c.getString(c.getColumnIndex("commodity"));
        String amo = c.getString(c.getColumnIndex("amount"));

        al.add(comm + "\n" + amo);
        ArrayAdapter ad = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,al);
        list.setAdapter(ad);
    }
    while (c.moveToNext());
    return v;
}
}
</code>```

答:
Use Context.MODE_PRIVATE.

This should work.

database=getActivity().openOrCreateDatabase("firstdatabase",android.content.Context.MODE_PRIVATE ,null);

ContentLicense: CC BY-SA 3.0

Body:
I am using Database in a fragment. However when I try to initialize my database Using the line:

database=openOrCreateDatabase("firstdatabase",MODE_PRIVATE,null);

It gives me an error saying:

Error:(47, 55) error: cannot find symbol variable MODE_PRIVATE

This is my code:

public class Expenses extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.expenses,container,false);

    final SQLiteDatabase database;
    Cursor c;
    ArrayList<String> al=new ArrayList<>();

    ImageButton img=(ImageButton)v.findViewById(R.id.img);
    final EditText commodity=(EditText)v.findViewById(R.id.commodity);
    final EditText amount=(EditText)v.findViewById(R.id.amount);
    ListView list=(ListView)v.findViewById(R.id.list);

    Calendar calendar=Calendar.getInstance();
    final int day=calendar.get(Calendar.DAY_OF_MONTH);
    final int month=calendar.get(Calendar.MONTH);
    final int year=calendar.get(Calendar.YEAR);

    registerForContextMenu(list);
    database=openOrCreateDatabase("firstdatabase",MODE_PRIVATE,null);

    img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getContext(), "Entered Successfully", Toast.LENGTH_SHORT).show();
            String c=commodity.getText().toString();
            int a=Integer.parseInt(amount.getText().toString());
            String q2="insert into expenses(day,month,year,commodity,amount)values('"+day+ "','" +month+ "','" +year+"','"+c+"','"+a+"');";
            database.execSQL(q2);
        }
    });

    String q1 = "select * from expenses";

    c = database.rawQuery(q1, null);

    c.moveToFirst();
    do {
        String comm = c.getString(c.getColumnIndex("commodity"));
        String amo = c.getString(c.getColumnIndex("amount"));

        al.add(comm + "\n" + amo);
        ArrayAdapter ad = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,al);
        list.setAdapter(ad);
    }
    while (c.moveToNext());
    return v;
}
}


问:
Organization of Locale Files in rails app
I currently have the following 4 files in my config/locales of my root application:

```<code>-en.yml
-de.yml
-simple_form.en.yml
-simple_form.de.yml
</code>```

In my application.rb which resides in a spec/dummy folder for testing the application gem I have the following line of code which seems to be retrieving the translations as expected:

```<code># The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :de
</code>```

I now wish to introduce to structure to the file structure of my locales folder but when I add the additional folders and change the load path in the application.rb I am getting translation not found errors. Here is my attempt:

Attempt at including structure in config/locales of my root application:

```<code>-views
  -en.yml
  -de.yml
-models
  -en.yml
  -de.yml
-forms
  -simple_form.en.yml
  -simple_form.de.yml
</code>```

And my load path in the application.rb changed to:

```<code>config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
</code>```

According to the following rails guide:
http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-domain-name

答:
In config/application.rb:

```<code>module PointsProject
  class Application < Rails::Application
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
  end
end
</code>```

From Rails's guide on Internationalization: http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-domain-name

Body:
I currently have the following 4 files in my config/locales of my root application:

-en.yml
-de.yml
-simple_form.en.yml
-simple_form.de.yml

In my application.rb which resides in a spec/dummy folder for testing the application gem I have the following line of code which seems to be retrieving the translations as expected:

# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :de

I now wish to introduce to structure to the file structure of my locales folder but when I add the additional folders and change the load path in the application.rb I am getting translation not found errors. Here is my attempt:

Attempt at including structure in config/locales of my root application:

-views
  -en.yml
  -de.yml
-models
  -en.yml
  -de.yml
-forms
  -simple_form.en.yml
  -simple_form.de.yml

And my load path in the application.rb changed to:

config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

According to the following rails guide:
http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-domain-name

Body:
In config/application.rb:

module PointsProject
  class Application < Rails::Application
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
  end
end

From Rails's guide on Internationalization: http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-domain-name


问:
why isn't my if statement working?
I need user input to save to a database and then display on an app.
If the user's input is left blank, I need to display an error message.

I'm running into trouble with the error messages displaying at all.
When user input is blank, a blank post is saved to the db and then displayed with no content rather than displaying the error message.

I am using Python, Jinja2, Flask, HTML

Thanks!!

```<code>    if request.method == 'POST':

        blog_title = str(request.form['title'])
        blog_body = str(request.form['body'])

        title_error = ''
        body_error = ''

        if len(blog_title) == 0:
            title_error = 'Please give your blog a title'
            return title_error

        if len(blog_body) == 0:
            body_error = "Please give your blog some content"
            return body_error
        else:
            new_blog = Blog(blog_title, blog_body)
            db.session.add(new_blog)
            db.session.commit()

            blog_id = new_blog.id

            return redirect(url_for('blogs', id=blog_id))

    else:
        return render_template('/newpost_form.html')
</code>```

答:
I would consider integrating Flask-WTF. I only do flask forms that way. Provides a lot of validation tools that make it easy to work with

forms.py

```<code>from flask_wtf import FlaskForm
from wtf.fields import StringField, TextAreaField, SubmitField
from wtf.validators import DataRequired

class NewBlogForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired(message='one')])
    body = TextAreaField('Body', validators=[DataRequired(message='two')])
    submit = SubmitField('Save')
</code>```

routes.py

```<code>from forms import NewBlogForm

@app.route('/newpost', methods=['GET', 'POST'])
def new_post():
    form = NewBlogForm()
    if form.validate_on_submit():
        blog = Blog(form.title.data, form.body.data)
        db.session.add(blog)
        db.session.commit()  # should have try block to catch any errors
        return redirect(url_for('blogs', id=blog.id))
    return render_template('newposts_form.html', form=form)
</code>```

newposts_form.html

```<code><form>
    <ul>
    {% for error in form.errors %}
        <li>{{ error }}</li>
    {% endfor %}
    </ul>
    {{ form.csrf_token }}
    {{ form.title.label }}{{ form.title }}
    {{ form.body.label }}{{ form.body }}
    {{ form.submit }}
</form>
</code>```

If you are using Flask-Bootstrap they support wtf forms and show errors in a really clean way.

Title: why isn't my if statement working?

Body:
I need user input to save to a database and then display on an app.
If the user's input is left blank, I need to display an error message.

I'm running into trouble with the error messages displaying at all.
When user input is blank, a blank post is saved to the db and then displayed with no content rather than displaying the error message.

I am using Python, Jinja2, Flask, HTML

Thanks!!

    if request.method == 'POST':

        blog_title = str(request.form['title'])
        blog_body = str(request.form['body'])

        title_error = ''
        body_error = ''

        if len(blog_title) == 0:
            title_error = 'Please give your blog a title'
            return title_error

        if len(blog_body) == 0:
            body_error = "Please give your blog some content"
            return body_error
        else:
            new_blog = Blog(blog_title, blog_body)
            db.session.add(new_blog)
            db.session.commit()

            blog_id = new_blog.id

            return redirect(url_for('blogs', id=blog_id))

    else:
        return render_template('/newpost_form.html')

Body:
I would consider integrating Flask-WTF. I only do flask forms that way. Provides a lot of validation tools that make it easy to work with

forms.py

from flask_wtf import FlaskForm
from wtf.fields import StringField, TextAreaField, SubmitField
from wtf.validators import DataRequired

class NewBlogForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired(message='one')])
    body = TextAreaField('Body', validators=[DataRequired(message='two')])
    submit = SubmitField('Save')

routes.py

from forms import NewBlogForm

@app.route('/newpost', methods=['GET', 'POST'])
def new_post():
    form = NewBlogForm()
    if form.validate_on_submit():
        blog = Blog(form.title.data, form.body.data)
        db.session.add(blog)
        db.session.commit()  # should have try block to catch any errors
        return redirect(url_for('blogs', id=blog.id))
    return render_template('newposts_form.html', form=form)

newposts_form.html

<form>
    <ul>
    {% for error in form.errors %}
        <li>{{ error }}</li>
    {% endfor %}
    </ul>
    {{ form.csrf_token }}
    {{ form.title.label }}{{ form.title }}
    {{ form.body.label }}{{ form.body }}
    {{ form.submit }}
</form>

If you are using Flask-Bootstrap they support wtf forms and show errors in a really clean way.


问:
Getting switch statement to work using a json value
I created a switch statement that looks for a value of a JSON object and based on that value supplies data to the console. However it is not working. Can someone tell me what im missing?

```<code>.controller('GeoCtrl', function($scope, $http) {
    $scope.result = "";
    $http.get('http://api.airvisual.com/v2/city?country=usa&state=arizona&city=phoenix&key=PxJe9btQYWReyQFAm')
      .success(function(data, status, headers,config){
        console.log('data success');
        console.log(data); // for browser console
        $scope.result = data; // for UI
      })
      .error(function(data, status, headers,config){
        console.log('data error');
      })
      .then(function(result){
        things = result.data;
          val = $(things.data.current.pollution.aqius);
          console.log(val);
          var level;
          var health;
          var sport;
          switch (true) {
              case (val < 50):
                  level = "Good";
                  health = "Air quality is considered satisfactory, and air pollution poses little or no risk";
                  sport = "Perfect day to play!";
                  break;
              case (51 <= val && val < 100):
                  level = "Moderate";
                  health = "Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should limit prolonged outdoor exertion.";
                  break;
              case (101 <= val && val < 150):
                  level = "Unhealthy for Sensitive Groups";
                  health = "Members of sensitive groups may experience health effects. The general public is not likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (151 <= val && val < 200):
                  level = "Unhealthy";
                  health = "Unhealthy Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (201 <= val && val < 300):
                  level = "Very Unhealthy";
                  health = "Health warnings of emergency conditions. The entire population is more likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid all outdoor exertion; everyone else, especially children, should limit outdoor exertion.";
                  break;
              case (301 <= val):
                  level = "Hazardous";
                  health = "Health alert: everyone may experience more serious health effects";
                  sport = "Everyone should avoid all outdoor exertion";
          }

           console.log(level);
           console.log(health);
           console.log(sport);
      });
  })
</code>```

I can get the value using console.log but cannot get my switch statement do anything with the value.

答:
Updated answer:

Looking at your code the issue is in the promise you are returning. I think you may have gotten confused on the use of data as the return type. If you look at the object that is returned from the api you get a result set of:

```<code>{
    "data": {
        "status": "success",
        "data": {
            "city": "Phoenix",
            "state": "Arizona",
            "country": "USA",
            "location": {
                "type": "Point",
                "coordinates": [
                    -112.066299,
                    33.560299
                ]
            },
            "current": {
                "weather": {
                    "ts": "2017-07-17T06:00:00.000Z",
                    "tp": 25,
                    "pr": 1013,
                    "hu": 88,
                    "ws": 6,
                    "wd": 110,
                    "ic": "11n"
                },
                "pollution": {
                    "ts": "2017-07-17T05:00:00.000Z",
                    "aqius": 124,
                    "mainus": "p2",
                    "aqicn": 97,
                    "maincn": "p1"
                }
            }
        }
    },
    "status": 200,
    "config": {
        "method": "GET",
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "url": "http://api.airvisual.com/v2/city?country=usa&state=arizona&city=phoenix&key=PxJe9btQYWReyQFAm",
        "headers": {
            "Accept": "application/json, text/plain, */*"
        }
    },
    "statusText": "OK"
}
</code>```

So in your code you need to change the setting of result to :

```<code>  $scope.result = data.data.data;
  var val = $scope.result.current.pollution.aqius;
</code>```

This should correct the output. Click here for a working Plunkr

Body:
I created a switch statement that looks for a value of a JSON object and based on that value supplies data to the console. However it is not working. Can someone tell me what im missing?

.controller('GeoCtrl', function($scope, $http) {
    $scope.result = "";
    $http.get('http://api.airvisual.com/v2/city?country=usa&state=arizona&city=phoenix&key=PxJe9btQYWReyQFAm')
      .success(function(data, status, headers,config){
        console.log('data success');
        console.log(data); // for browser console
        $scope.result = data; // for UI
      })
      .error(function(data, status, headers,config){
        console.log('data error');
      })
      .then(function(result){
        things = result.data;
          val = $(things.data.current.pollution.aqius);
          console.log(val);
          var level;
          var health;
          var sport;
          switch (true) {
              case (val < 50):
                  level = "Good";
                  health = "Air quality is considered satisfactory, and air pollution poses little or no risk";
                  sport = "Perfect day to play!";
                  break;
              case (51 <= val && val < 100):
                  level = "Moderate";
                  health = "Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should limit prolonged outdoor exertion.";
                  break;
              case (101 <= val && val < 150):
                  level = "Unhealthy for Sensitive Groups";
                  health = "Members of sensitive groups may experience health effects. The general public is not likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (151 <= val && val < 200):
                  level = "Unhealthy";
                  health = "Unhealthy Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (201 <= val && val < 300):
                  level = "Very Unhealthy";
                  health = "Health warnings of emergency conditions. The entire population is more likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid all outdoor exertion; everyone else, especially children, should limit outdoor exertion.";
                  break;
              case (301 <= val):
                  level = "Hazardous";
                  health = "Health alert: everyone may experience more serious health effects";
                  sport = "Everyone should avoid all outdoor exertion";
          }

           console.log(level);
           console.log(health);
           console.log(sport);
      });
  })

I can get the value using console.log but cannot get my switch statement do anything with the value.

Body:
Updated answer:

Looking at your code the issue is in the promise you are returning. I think you may have gotten confused on the use of data as the return type. If you look at the object that is returned from the api you get a result set of:

{
    "data": {
        "status": "success",
        "data": {
            "city": "Phoenix",
            "state": "Arizona",
            "country": "USA",
            "location": {
                "type": "Point",
                "coordinates": [
                    -112.066299,
                    33.560299
                ]
            },
            "current": {
                "weather": {
                    "ts": "2017-07-17T06:00:00.000Z",
                    "tp": 25,
                    "pr": 1013,
                    "hu": 88,
                    "ws": 6,
                    "wd": 110,
                    "ic": "11n"
                },
                "pollution": {
                    "ts": "2017-07-17T05:00:00.000Z",
                    "aqius": 124,
                    "mainus": "p2",
                    "aqicn": 97,
                    "maincn": "p1"
                }
            }
        }
    },
    "status": 200,
    "config": {
        "method": "GET",
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "url": "http://api.airvisual.com/v2/city?country=usa&state=arizona&city=phoenix&key=PxJe9btQYWReyQFAm",
        "headers": {
            "Accept": "application/json, text/plain, */*"
        }
    },
    "statusText": "OK"
}

So in your code you need to change the setting of result to :

  $scope.result = data.data.data;
  var val = $scope.result.current.pollution.aqius;

This should correct the output. Click here for a working Plunkr


问:
Is it possible to increase the max columns of an Oracle database to store huge arrays?
For reasons that are beyond my control I need to store huge arrays (10000+ entries) in database rows, and it has to be easy to access each index of the array individually, which means I'd rather avoid serialization/blobs, if at all possible.

So my first idea, and the actual question here, is can I increase max columns for Oracle in anyway?

Or is there an easy way to say store the array over a few rows and hide the implementation below the surface (I'm thinking stored procedure here).

Any other suggestions are also welcome!

答:
Why not store the array as a Blob?

It is very unlikely that anyone would ever code "Where Acol999 = 42 or Acol1000 = 42 ..." in SQL so if you just want to store and retreive than store it as a Big Clob or Blob depending on your data.

This will be much quicker qnd involve much less code.

If you eally want to query the contents than you really need a separate table with 1 - ONE - row per array cell. You will then be able to query this sensibly.

```
CREATE TABLE ARRAY_CELLS (
     PARENT_ID INT NOT NULL,
     INDEXNUM  INT NOT NULL,
     VALUEOF   LONG NOT NULL
    PRIMARY KEY(PARENT_ID,INDEXNUM)
);
```

You can then run queries like:-

```
 SELECT PARENT_ID from TABLE_ARRAY_CELLS WHERE VALUEOF = 42 GROUP BY PARENT_ID;
```

Which will give you a list of all the Arrays that contain value 42.

OwnerDisplayName: Robert Gould

ContentLicense: CC BY-SA 2.5

Body:
Why not store the array as a Blob?

It is very unlikely that anyone would ever code "Where Acol999 = 42 or Acol1000 = 42 ..." in SQL so if you just want to store and retreive than store it as a Big Clob or Blob depending on your data.

This will be much quicker qnd involve much less code.

If you eally want to query the contents than you really need a separate table with 1 - ONE - row per array cell. You will then be able to query this sensibly.

CREATE TABLE ARRAY_CELLS (
     PARENT_ID INT NOT NULL,
     INDEXNUM  INT NOT NULL,
     VALUEOF   LONG NOT NULL
    PRIMARY KEY(PARENT_ID,INDEXNUM)
);

You can then run queries like:-

 SELECT PARENT_ID from TABLE_ARRAY_CELLS WHERE VALUEOF = 42 GROUP BY PARENT_ID;

Which will give you a list of all the Arrays that contain value 42.

OwnerDisplayName: James Anderson


问:
How to save the data into File in java?
I have one problem, that is I have one string of data and I want to save it into a separate file every time. Please give me a suggestion.

Thanks,
vara kumar.pjd

答:
One of possible ways to get File object with unique name could be:

```<code>public static File getUniqueFile(String base, String ext, int index) {
    File f = new File(String.format("%s-%03d.%s", base, index, ext));
    return f.exists() ? getUniqueFile(base, ext, index + 1) : f;
}
</code>```

Update: and here goes basic usage/test case:

```<code>    String s = "foo string\n";

    FileWriter writer = null;

    for (int i = 0; i < 10; i++) {
        File f = getUniqueFile("out", "txt", 0);
        try {
            writer = new FileWriter(f);
            writer.write(s);
            writer.close();
            writer = null;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }

    if (writer != null) { try { writer.close(); } catch (Exception e) {} }
</code>```

Title: How to save the data into File in java?

Body:
One of possible ways to get File object with unique name could be:

public static File getUniqueFile(String base, String ext, int index) {
    File f = new File(String.format("%s-%03d.%s", base, index, ext));
    return f.exists() ? getUniqueFile(base, ext, index + 1) : f;
}

Update: and here goes basic usage/test case:

    String s = "foo string\n";

    FileWriter writer = null;

    for (int i = 0; i < 10; i++) {
        File f = getUniqueFile("out", "txt", 0);
        try {
            writer = new FileWriter(f);
            writer.write(s);
            writer.close();
            writer = null;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }

    if (writer != null) { try { writer.close(); } catch (Exception e) {} }


问:
Perform WHERE 'field' IN (list) query in Django?
To every question, there are many answers. I have a table Vote which contains the upvote/downvotes on all the question and answers. I want to perform a query something like:

Select * from vote WHERE username="some username" AND (QID="question"
  OR (AID IN (SELECT AID from Answers WHERE QID="question")))

```<code>class Question(models.Model):
    QID = models.CharField( default="",max_length=5, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=30, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=5, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=30, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.AID

class Vote(models.Model):
    username = models.ForeignKey(User,on_delete=None)
    QID = models.ForeignKey(Question,on_delete=None, null=True, blank=True)
    AID = models.ForeignKey(Answer,on_delete=None, null=True, blank=True)
    vote = models.BooleanField(default=True)

    def __str__(self):
        if self.QID is not None:
            return self.QID.QID+'_'+self.username.username+'_'+str(self.vote)
        else:
            return self.AID.AID+'_'+self.username.username+'_'+str(self.vote)
</code>```

P.S. Please note that QID and AID are foreign keys. So they will take instance of Question/Answer Model only.

答:
You could do,

```<code>from django.db.models import Q

Vote.objects.filter(username='some_username').filter(
                        Q(QID=question_id) |
                        Q(AID__QID=question_id
                        )
</code>```

NOTE : Totally agree with @schillingt's answer.

Or, if you want to get all the Vote objects of a question, then you could call the reverse relation like,

```<code>question = Question.objects.get(QID='some_id')
question.vote_set.all()
</code>```

Body:
To every question, there are many answers. I have a table Vote which contains the upvote/downvotes on all the question and answers. I want to perform a query something like:

Select * from vote WHERE username="some username" AND (QID="question"
  OR (AID IN (SELECT AID from Answers WHERE QID="question")))

class Question(models.Model):
    QID = models.CharField( default="",max_length=5, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=30, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=5, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=30, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.AID

class Vote(models.Model):
    username = models.ForeignKey(User,on_delete=None)
    QID = models.ForeignKey(Question,on_delete=None, null=True, blank=True)
    AID = models.ForeignKey(Answer,on_delete=None, null=True, blank=True)
    vote = models.BooleanField(default=True)

    def __str__(self):
        if self.QID is not None:
            return self.QID.QID+'_'+self.username.username+'_'+str(self.vote)
        else:
            return self.AID.AID+'_'+self.username.username+'_'+str(self.vote)

P.S. Please note that QID and AID are foreign keys. So they will take instance of Question/Answer Model only.

Body:
You could do,

from django.db.models import Q

Vote.objects.filter(username='some_username').filter(
                        Q(QID=question_id) |
                        Q(AID__QID=question_id
                        )

NOTE : Totally agree with @schillingt's answer.

Or, if you want to get all the Vote objects of a question, then you could call the reverse relation like,

question = Question.objects.get(QID='some_id')
question.vote_set.all()


问:
Insert JSON into PostgreSQL that contains quotation marks
I'm trying to import a JSON file into a table. I'm using the solution mentioned here: https://stackoverflow.com/a/33130304/1663462:

```<code>create temporary table temp_json (values text) on commit drop;
copy temp_json from 'data.json';

select
  values->>'annotations' as annotationstext

from   (
           select json_array_elements(replace(values,'\','\\')::json) as values
           from   temp_json
       ) a;
</code>```

Json file content is:

```<code>{"annotations": "<?xml version=\"1.0\"?>"}
</code>```

I have verified that this is a valid JSON file.

The json file contains a \" which I presume is responsible for the following error:

```<code>CREATE TABLE
COPY 1
psql:insertJson2.sql:13: ERROR:  invalid input syntax for type json
DETAIL:  Expected "," or "}", but found "1.0".
CONTEXT:  JSON data, line 1: {"annotations": "<?xml version="1.0...
</code>```

Are there any additional characters that need to be escaped?

答:
Because copy command processes escape ('\') characters for text format without any options there are two ways to import such data.

1) Process file using external utility via copy ... from program, for example using sed:

```<code>copy temp_json from program 'sed -e ''s/\\/\\\\/g'' data.json';
</code>```

It will replace all backslashes to doubled backslashes, which will be converted back to single ones by copy.

2) Use csv import:

```<code>copy temp_json from 'data.json' with (format csv, quote '|', delimiter E'\t');
</code>```

Here you should to set quote and delimiter characters such that it does not occur anywhere in your file.

And after that just use direct conversion:

```<code>select values::json->>'annotations' as annotationstext from temp_json;
</code>```

Body:
I'm trying to import a JSON file into a table. I'm using the solution mentioned here: https://stackoverflow.com/a/33130304/1663462:

create temporary table temp_json (values text) on commit drop;
copy temp_json from 'data.json';

select
  values->>'annotations' as annotationstext

from   (
           select json_array_elements(replace(values,'\','\\')::json) as values
           from   temp_json
       ) a;

Json file content is:

{"annotations": "<?xml version=\"1.0\"?>"}

I have verified that this is a valid JSON file.

The json file contains a \" which I presume is responsible for the following error:

CREATE TABLE
COPY 1
psql:insertJson2.sql:13: ERROR:  invalid input syntax for type json
DETAIL:  Expected "," or "}", but found "1.0".
CONTEXT:  JSON data, line 1: {"annotations": "<?xml version="1.0...

Are there any additional characters that need to be escaped?

Body:
Because copy command processes escape ('\') characters for text format without any options there are two ways to import such data.

1) Process file using external utility via copy ... from program, for example using sed:

copy temp_json from program 'sed -e ''s/\\/\\\\/g'' data.json';

It will replace all backslashes to doubled backslashes, which will be converted back to single ones by copy.

2) Use csv import:

copy temp_json from 'data.json' with (format csv, quote '|', delimiter E'\t');

Here you should to set quote and delimiter characters such that it does not occur anywhere in your file.

And after that just use direct conversion:

select values::json->>'annotations' as annotationstext from temp_json;


问:
Passing parameters to a view in Django
In my urls.py I have set handler404 to CustomErrorView. CustomErrorView is a generic view which generates a template for an error based on the error message and error code that it receives.

Since the handler404 is only raised in the case of a 404 error, how can I send the errorcode = 404 kwarg to CustomErrorView whenever it is raised?

Already tried-

handler404 = CustomErrorView(errorcode = 404)

 This causes an "Expected one positional argument, none given error."

 handler404 = CustomErrorView(request, errorcode = 404)

This causes a NameError (Name 'request' is not defined)

My urls.py:

```<code>from django.conf.urls import url, include
from django.contrib import admin
from blog_user.views import home, create_error_view

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', home),
    url(r'^', include('user_manager.urls')),
    ]

handler404 = create_error_view(error = 404)
handler500 = create_error_view(error = 500)
</code>```

My views.py (after using the modifications recommended by @knbk) :

```<code>from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound

def create_error_view(error = 404, mybad = False):
    def custom_error_view(request, error, mybad):
        ''' Returns a generic error page. Not completed yet. error code and messages are supposed to be modular so that it can be used anywhere for any error in the page.'''
        content = "Incorrect url"
        context= {
            'error': error,
            'content':content,
            'mybad':mybad
        }
        response = render(request, 'error.html', context=context, status=error)
        return HttpResponse(response)
    return custom_error_view
</code>```

答:
You can use a function closure to create the view function:

```<code>def create_error_view(error_code):
    def custom_error_view(request, *args, **kwargs):
        # You can access error_code here
    return custom_error_view
</code>```

Then just call create_error_view to set the handler:

```<code>handler404 = create_error_view(error_code=404)
</code>```

Or you can use functools.partial(), which basically does the same:

```<code>from functools import partial

handler404 = partial(custom_error_view, error_code=404)
</code>```

Title: Passing parameters to a view in Django

Body:
In my urls.py I have set handler404 to CustomErrorView. CustomErrorView is a generic view which generates a template for an error based on the error message and error code that it receives.

Since the handler404 is only raised in the case of a 404 error, how can I send the errorcode = 404 kwarg to CustomErrorView whenever it is raised?

Already tried-

handler404 = CustomErrorView(errorcode = 404)

 This causes an "Expected one positional argument, none given error."

 handler404 = CustomErrorView(request, errorcode = 404)

This causes a NameError (Name 'request' is not defined)

My urls.py:

from django.conf.urls import url, include
from django.contrib import admin
from blog_user.views import home, create_error_view

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', home),
    url(r'^', include('user_manager.urls')),
    ]

handler404 = create_error_view(error = 404)
handler500 = create_error_view(error = 500)

My views.py (after using the modifications recommended by @knbk) :

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound

def create_error_view(error = 404, mybad = False):
    def custom_error_view(request, error, mybad):
        ''' Returns a generic error page. Not completed yet. error code and messages are supposed to be modular so that it can be used anywhere for any error in the page.'''
        content = "Incorrect url"
        context= {
            'error': error,
            'content':content,
            'mybad':mybad
        }
        response = render(request, 'error.html', context=context, status=error)
        return HttpResponse(response)
    return custom_error_view

Body:
You can use a function closure to create the view function:

def create_error_view(error_code):
    def custom_error_view(request, *args, **kwargs):
        # You can access error_code here
    return custom_error_view

Then just call create_error_view to set the handler:

handler404 = create_error_view(error_code=404)

Or you can use functools.partial(), which basically does the same:

from functools import partial

handler404 = partial(custom_error_view, error_code=404)


问:
Variable being passed with single quotes using PHP and MYSQL
I have the following variable I want to pass to a prepare statement: $subject. It is done using PDO. Unfortunately it is being passed in with single quotes around it.Example is that i pass in maths and the query uses 'maths' instead. I have tried other answers such as bindParam, bindValue as well as specifying it is a string attribute, however I cannot get it to work. Thanks in advance if anyone knows what is wrong My code is below.

```<code>$query = "SELECT * FROM :subject;";
        $sql = $connection->prepare($query);
        $sql->bindParam(':subject', $subject);
        try{
            $sql->execute();
        }catch(Exception $e){
            echo $e;
        }
</code>```

And i get the following error:

```<code>exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''maths'' at line 1' in D:\xampp\htdocs\acards\functions.php:18
Stack trace:
#0 D:\xampp\htdocs\acards\functions.php(18): PDOStatement->execute()
#1 D:\xampp\htdocs\acards\getMathsQuestions.php(13): Functions->getFeed('maths')
#2 {main}[]
</code>```

答:
If you want to create a "flexible" query, allowing the user to input a table name you can do so by providing some PHP logic before you get to the prepare statement like

```<code> $query="SELECT * FROM $subject";
</code>```

But of course, this would open up your query to any kind of SQL-injection. But who is to say that you are not allowed to create your own "input-sanitization" on $subject before you use it in this statement? Just be aware, that this needs to be done very carefully!

Body:
I have the following variable I want to pass to a prepare statement: $subject. It is done using PDO. Unfortunately it is being passed in with single quotes around it.Example is that i pass in maths and the query uses 'maths' instead. I have tried other answers such as bindParam, bindValue as well as specifying it is a string attribute, however I cannot get it to work. Thanks in advance if anyone knows what is wrong My code is below.

$query = "SELECT * FROM :subject;";
        $sql = $connection->prepare($query);
        $sql->bindParam(':subject', $subject);
        try{
            $sql->execute();
        }catch(Exception $e){
            echo $e;
        }

And i get the following error:

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''maths'' at line 1' in D:\xampp\htdocs\acards\functions.php:18
Stack trace:
#0 D:\xampp\htdocs\acards\functions.php(18): PDOStatement->execute()
#1 D:\xampp\htdocs\acards\getMathsQuestions.php(13): Functions->getFeed('maths')
#2 {main}[]

Body:
If you want to create a "flexible" query, allowing the user to input a table name you can do so by providing some PHP logic before you get to the prepare statement like

 $query="SELECT * FROM $subject";

But of course, this would open up your query to any kind of SQL-injection. But who is to say that you are not allowed to create your own "input-sanitization" on $subject before you use it in this statement? Just be aware, that this needs to be done very carefully!


问:
max() in mysql returns 9999 not more than that?
I have a customers tables where there is a field called uniqueId Type : varchar(255) & Collation : utf8mb4_unicode_ci  ..I wanted to find the max uniqueId ..though i have entry of 10000 but it always return 9999 ..why is that?

```<code>SELECT MAX(uniqueId) FROM `customers`
</code>```

答:
could be you have a string then try cast </p>

```<code>SELECT MAX( CAST(uniqueId AS UNSIGNED) ) FROM `customers`
</code>```

Body:
I have a customers tables where there is a field called uniqueId Type : varchar(255) & Collation : utf8mb4_unicode_ci  ..I wanted to find the max uniqueId ..though i have entry of 10000 but it always return 9999 ..why is that?

SELECT MAX(uniqueId) FROM `customers`

Body:
could be you have a string then try cast

SELECT MAX( CAST(uniqueId AS UNSIGNED) ) FROM `customers`


问:
replace all word occurrence in list with index of items in another list
I have a list -

```<code>A=["hi how are you","have good day","where are you going ","do you like the place"]
</code>```

and another list -

```<code>B=["how","good","where","going","like","place"]
</code>```

List B includes some of words that exist in list A.
I want to replace all words in List B that occur in List A by their index in list B. If word doesn't exist replace it with 0

So list A after the replacement should be

```<code>["0 1 0 0","0 2 0","3 0 0 4","0 0 5 0 6"]
</code>```

I tried using for loop but it's not effiecent as my list length is > 10000. I also tried using map function but i wasn't successful

Here is my attempt :

```<code>for item in list_A:
    words=sorted(item.split(), key=len,reverse=True)
    for w in word:
        if w.strip() in list_B:
            item=item.replace(w,str(list_B.index(w.strip())))
        else:
            item=item.replace(w,0)
</code>```

答:
You can try this:</p>

```<code>A=["hi how are you","have good day","where are you going ","do you like the place"]
A = map(lambda x:x.split(), A)
B=["how","good","where","going","like","place"]
new = [[c if d == a else 0 for c, d in enumerate(i)] for i in A for a in B]

final = map(' '.join, map(lambda x: [str(i) for i in x], new))

print final
</code>```

Body:
I have a list -

A=["hi how are you","have good day","where are you going ","do you like the place"]

and another list -

B=["how","good","where","going","like","place"]

List B includes some of words that exist in list A.
I want to replace all words in List B that occur in List A by their index in list B. If word doesn't exist replace it with 0

So list A after the replacement should be

["0 1 0 0","0 2 0","3 0 0 4","0 0 5 0 6"]

I tried using for loop but it's not effiecent as my list length is > 10000. I also tried using map function but i wasn't successful

Here is my attempt :

for item in list_A:
    words=sorted(item.split(), key=len,reverse=True)
    for w in word:
        if w.strip() in list_B:
            item=item.replace(w,str(list_B.index(w.strip())))
        else:
            item=item.replace(w,0)

Body:
You can try this:

A=["hi how are you","have good day","where are you going ","do you like the place"]
A = map(lambda x:x.split(), A)
B=["how","good","where","going","like","place"]
new = [[c if d == a else 0 for c, d in enumerate(i)] for i in A for a in B]

final = map(' '.join, map(lambda x: [str(i) for i in x], new))

print final


问:
SpringBoot cannot resolve path to static resources(404)
None of the solutions to the likewise issues I've checked has worked for me. I'm using Intellij Idea Spring Initializer, which has a clear project structure:

src:

--- main:

 ---------- java:

 ---------------- myproject:

 ------------------------------ config

 ------------------------------ controller

 ------------------------------ dao

 ------------------------------ model

 ------------------------------ service

 ------------------------------
 HibernateApplication.java

--------- resources:

--------------- static:

--------------- template

Here HibernateApplication is a main runner class, a standard one provided by SpringBoot and marked @SpringBootApplication; resources is located under the main directory, and, as far I see from other examples, it serves as a web-inf folder.

In config, there's a @Configuration class:

```<code>    @Configuration
    public class AppConfig {
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new
        InternalResourceViewResolver();
        resolver.setPrefix("/resources/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }
}
</code>```

Here is my @Controller class:

```<code>@Controller
@RequestMapping("/")
public class ActorController {
    @Autowired
    private ActorService actorService;

    @GetMapping
    public String addActor(){
        //actorService.addActor();
        return "hello";
    }
}
</code>```

I'm not using here my services, all I'm trying to do is just to make him get and respond with a "hello.jsp" file that is lying exactly in resources/static folder. Its contents are dead simple:

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
Hello from Spring Boot!
</body>
</html>
</code>```

Following are my application.properties:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/sakila<br>
spring.datasource.username=root<br>
spring.datasource.password=root<br>
spring.jpa.hibernate.ddl-auto=create-drop<br>
security.basic.enabled=false<br>
</code>```

My dependencies include tomcat-embded-jasper, jstl, javax.servlet and all the necessary spring boot stuff. However, when I run localhost:8080/ I'm getting a whitelabel error page with unexpected 404 error. If my path is configured like
 .setPrefix("/resources/").setSuffix(".jsp"), it says it cannot resolve "/resources/hello.jsp". If I set prefix to ("/resources/static/"), it cannot find "/resources/static/hello.jsp".

What's the matter? Even Intellij resolves the path easily when I click Ctrl on that path and it redirects me right to "resources" folder.

P.S. OK, I've found one problem: by default Intellij has created this "myproject" folder and runner class was inside it, I've mistakenly started to add new packages inside this folder. Now I've fixed that, moving all packages out of this folder up to the 'main' folder, leaving "myproject" folder only with the runner class inside. The hierarchy now must be alright, yet still no view is returned in browser.

答:
Spotted a problem.

 1. A Thymeleaf dependency was missing.

 2. Controllers, DAO and stuff all should go as the subfolders inside the main folder with a SpringBootApplication main class. My problem was that my controller wasn't even on the component scan path.

 3. The views should be placed inside the 'templates' folder, not like in my case (mistakenly) inside 'static'. Views also (in my case) had to be html, not jsp.

 4. Eventually I deleted ViewResolver definitions in code, since my html files were detected now by SpringBoot by default.

Thanks, the question can be closed now.

ContentLicense: CC BY-SA 4.0

Body:
None of the solutions to the likewise issues I've checked has worked for me. I'm using Intellij Idea Spring Initializer, which has a clear project structure:

src:

--- main:

 ---------- java:

 ---------------- myproject:

 ------------------------------ config

 ------------------------------ controller

 ------------------------------ dao

 ------------------------------ model

 ------------------------------ service

 ------------------------------
 HibernateApplication.java

--------- resources:

--------------- static:

--------------- template

Here HibernateApplication is a main runner class, a standard one provided by SpringBoot and marked @SpringBootApplication; resources is located under the main directory, and, as far I see from other examples, it serves as a web-inf folder.

In config, there's a @Configuration class:

    @Configuration
    public class AppConfig {
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new
        InternalResourceViewResolver();
        resolver.setPrefix("/resources/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }
}

Here is my @Controller class:

@Controller
@RequestMapping("/")
public class ActorController {
    @Autowired
    private ActorService actorService;

    @GetMapping
    public String addActor(){
        //actorService.addActor();
        return "hello";
    }
}

I'm not using here my services, all I'm trying to do is just to make him get and respond with a "hello.jsp" file that is lying exactly in resources/static folder. Its contents are dead simple:

    <meta charset="UTF-8">
    <title>Hello</title>

Hello from Spring Boot!

Following are my application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/sakila

spring.datasource.username=root

spring.datasource.password=root

spring.jpa.hibernate.ddl-auto=create-drop

security.basic.enabled=false

My dependencies include tomcat-embded-jasper, jstl, javax.servlet and all the necessary spring boot stuff. However, when I run localhost:8080/ I'm getting a whitelabel error page with unexpected 404 error. If my path is configured like
 .setPrefix("/resources/").setSuffix(".jsp"), it says it cannot resolve "/resources/hello.jsp". If I set prefix to ("/resources/static/"), it cannot find "/resources/static/hello.jsp".

What's the matter? Even Intellij resolves the path easily when I click Ctrl on that path and it redirects me right to "resources" folder.

P.S. OK, I've found one problem: by default Intellij has created this "myproject" folder and runner class was inside it, I've mistakenly started to add new packages inside this folder. Now I've fixed that, moving all packages out of this folder up to the 'main' folder, leaving "myproject" folder only with the runner class inside. The hierarchy now must be alright, yet still no view is returned in browser.


答:
You should define a function to return index of word in second list:

```<code>def get_index_of_word(word):
    try:
        return str(B.index(word) + 1)
    except ValueError:
        return '0'
</code>```

And then, You can use nested list comprehension to generate the result:

```<code>[' '.join(get_index_of_word(word) for word in sentence.split()) for sentence in A]
</code>```

UPDATE

```<code>from collections import defaultdict

index = defaultdict(lambda: 0, ((word, index) for index, word in enumerate(B, 1))

[' '.join(str(index[word]) for word in sentence.split()) for sentence in A]
</code>```

Title: replace all word occurrence in list with index of items in another list

Body:
You should define a function to return index of word in second list:

def get_index_of_word(word):
    try:
        return str(B.index(word) + 1)
    except ValueError:
        return '0'

And then, You can use nested list comprehension to generate the result:

[' '.join(get_index_of_word(word) for word in sentence.split()) for sentence in A]

UPDATE

from collections import defaultdict

index = defaultdict(lambda: 0, ((word, index) for index, word in enumerate(B, 1))

[' '.join(str(index[word]) for word in sentence.split()) for sentence in A]


答:
angular.module('myApp',[])
.controller('GeoCtrl', function($scope, $http) {
    $scope.result = "";
    // Simple GET request example:
    $http({
      method: 'GET',
      url: 'http://api.airvisual.com/v2/city?country=usa&state=arizona&city=phoenix&key=PxJe9btQYWReyQFAm'
    }).then(function successCallback(data, status, headers,config) {
          $scope.result = data;
          var val = $scope.result.data.current.pollution.aqius;
          console.log(val);
          var level;
          var health;
          var sport;
          switch (val) {
              case (val < 50):
                  level = "Good";
                  health = "Air quality is considered satisfactory, and air pollution poses little or no risk";
                  sport = "Perfect day to play!";
                  break;
              case (51 <= val && val < 100):
                  level = "Moderate";
                  health = "Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should limit prolonged outdoor exertion.";
                  break;
              case (101 <= val && val < 150):
                  level = "Unhealthy for Sensitive Groups";
                  health = "Members of sensitive groups may experience health effects. The general public is not likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (151 <= val && val < 200):
                  level = "Unhealthy";
                  health = "Unhealthy Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (201 <= val && val < 300):
                  level = "Very Unhealthy";
                  health = "Health warnings of emergency conditions. The entire population is more likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid all outdoor exertion; everyone else, especially children, should limit outdoor exertion.";
                  break;
              case (301 <= val):
                  level = "Hazardous";
                  health = "Health alert: everyone may experience more serious health effects";
                  sport = "Everyone should avoid all outdoor exertion";
          }

           console.log(level);
           console.log(health);
           console.log(sport);
      }, function errorCallback(response) {

        console.log('data error');
      });
  })
```

<pre class="lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html><body ng-app="myApp"><div ng-controller="GeoCtrl"></div></body>
</html>
</code>```

Title: Getting switch statement to work using a json value

Body:
I created a switch statement that looks for a value of a JSON object and based on that value supplies data to the console. However it is not working. Can someone tell me what im missing?

.controller('GeoCtrl', function($scope, $http) {
    $scope.result = "";
    $http.get('http://api.airvisual.com/v2/city?country=usa&state=arizona&city=phoenix&key=PxJe9btQYWReyQFAm')
      .success(function(data, status, headers,config){
        console.log('data success');
        console.log(data); // for browser console
        $scope.result = data; // for UI
      })
      .error(function(data, status, headers,config){
        console.log('data error');
      })
      .then(function(result){
        things = result.data;
          val = $(things.data.current.pollution.aqius);
          console.log(val);
          var level;
          var health;
          var sport;
          switch (true) {
              case (val < 50):
                  level = "Good";
                  health = "Air quality is considered satisfactory, and air pollution poses little or no risk";
                  sport = "Perfect day to play!";
                  break;
              case (51 <= val && val < 100):
                  level = "Moderate";
                  health = "Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should limit prolonged outdoor exertion.";
                  break;
              case (101 <= val && val < 150):
                  level = "Unhealthy for Sensitive Groups";
                  health = "Members of sensitive groups may experience health effects. The general public is not likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (151 <= val && val < 200):
                  level = "Unhealthy";
                  health = "Unhealthy Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (201 <= val && val < 300):
                  level = "Very Unhealthy";
                  health = "Health warnings of emergency conditions. The entire population is more likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid all outdoor exertion; everyone else, especially children, should limit outdoor exertion.";
                  break;
              case (301 <= val):
                  level = "Hazardous";
                  health = "Health alert: everyone may experience more serious health effects";
                  sport = "Everyone should avoid all outdoor exertion";
          }

           console.log(level);
           console.log(health);
           console.log(sport);
      });
  })

I can get the value using console.log but cannot get my switch statement do anything with the value.

Body:
angular.module('myApp',[])
.controller('GeoCtrl', function($scope, $http) {
    $scope.result = "";
    // Simple GET request example:
    $http({
      method: 'GET',
      url: 'http://api.airvisual.com/v2/city?country=usa&state=arizona&city=phoenix&key=PxJe9btQYWReyQFAm'
    }).then(function successCallback(data, status, headers,config) {
          $scope.result = data;
          var val = $scope.result.data.current.pollution.aqius;
          console.log(val);
          var level;
          var health;
          var sport;
          switch (val) {
              case (val < 50):
                  level = "Good";
                  health = "Air quality is considered satisfactory, and air pollution poses little or no risk";
                  sport = "Perfect day to play!";
                  break;
              case (51 <= val && val < 100):
                  level = "Moderate";
                  health = "Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should limit prolonged outdoor exertion.";
                  break;
              case (101 <= val && val < 150):
                  level = "Unhealthy for Sensitive Groups";
                  health = "Members of sensitive groups may experience health effects. The general public is not likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (151 <= val && val < 200):
                  level = "Unhealthy";
                  health = "Unhealthy Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid prolonged outdoor exertion; everyone else, especially children, should limit prolonged outdoor exertion";
                  break;
              case (201 <= val && val < 300):
                  level = "Very Unhealthy";
                  health = "Health warnings of emergency conditions. The entire population is more likely to be affected.";
                  sport = "Active children and adults, and people with respiratory disease, such as asthma, should avoid all outdoor exertion; everyone else, especially children, should limit outdoor exertion.";
                  break;
              case (301 <= val):
                  level = "Hazardous";
                  health = "Health alert: everyone may experience more serious health effects";
                  sport = "Everyone should avoid all outdoor exertion";
          }

           console.log(level);
           console.log(health);
           console.log(sport);
      }, function errorCallback(response) {

        console.log('data error');
      });
  })

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html><body ng-app="myApp"><div ng-controller="GeoCtrl"></div></body>
</html>


问:
How do I Efficiently list **All** currently running jobs on Jenkins using Groovy
I have been trying to find a lightweight method in a Groovy scriptler script to list all currently running jobs of any type.  The only method I have found to be reliable is this:

```<code>start = System.currentTimeMillis()
def jobsFound = []
def buildingJobs = Jenkins.instance.getAllItems(Job.class).findAll {
            it.isBuilding()
    }
buildingJobs.each { job->
    allRuns = job._getRuns()
    allRuns.each {  item->
        if (!item.isBuilding()) {  return  } // This job is not building
    jobsFound.push(item.getUrl())
    }
}

timespent = (System.currentTimeMillis() - start ) / 1000
println "Time: ${timespent} seconds"
println "{jobsFound.size} jobs"

// RESULTS:
//   Time: 2.015 seconds. 15 jobs
</code>```

The problem is that the above enumerates ALL currently running jobs - we have thousands! - then enumerate all builds of each of those running jobs (some jobs have as many as 300 builds).  The above can take as long as FIVE minutes to complete depending on how many jobs are currently building.

A much more efficient method is to enumerate the active executors
but this method MISSES the pipeline (aka Workflow) jobs running on the master:

```<code>start = System.currentTimeMillis()

def busyExecutors = Jenkins.instance.computers.collect {
   c -> c.executors.findAll { it.isBusy() }
}.flatten()

def jobsFound = []
busyExecutors.each { e ->
     job = e.getCurrentExecutable()
     jobsFound.push(job.getUrl())
}

timespent = (System.currentTimeMillis() - start ) / 1000
println "Time: ${timespent} seconds. ${jobsFound.size} jobs"

// RESULTS:
//    Time: 0.005 seconds. 12 jobs
</code>```

Sure enough the discrepancy between the two counts are pipeline jobs running on the master.

I guess my question boils down to:

Is there a way to efficiently enumerate all jobs running on the master?

Clearly Jenkins does not include the master in computers, and although there is a MasterComputer class, its not clear how to get it or the OffByOneExecutors on which flyweight (pipeline) jobs run.

答:
Not directly with Jenkins types/objects but via Jenkins' Remote access API derived from From Jenkins, how do I get a list of the currently running jobs in JSON?:

```<code>http://localhost:8080/api/xml?&tree=jobs[builds[*]]&xpath=/hudson/job/build[building="true"]&wrapper=builds
</code>```

results in:

```<code><builds>
    <build _class="hudson.model.FreeStyleBuild">
        <action _class="hudson.model.CauseAction"/>
        <action/>
        <action/>
        <building>true</building>
        <displayName>#10</displayName>
        <duration>0</duration>
        <estimatedDuration>3617</estimatedDuration>
        <executor/>
        <fullDisplayName>Freestyle-Project #10</fullDisplayName>
        <id>10</id>
        <keepLog>false</keepLog>
        <number>10</number>
        <queueId>2</queueId>
        <timestamp>1499611190781</timestamp>
        <url>http://localhost:8080/job/Freestyle-Project/10/</url>
        <builtOn/>
        <changeSet _class="hudson.scm.EmptyChangeLogSet"/>
    </build>
</builds>
</code>```

Unfortunately <builtOn/>, which, I guess, is supposed to refer to the node, isn't supplied in my Jenkins v2.60.1 (yet?).

With:

```<code>http://localhost:8080/api/json?pretty=true
</code>```

you get:

```<code>...
"nodeDescription" : "the master Jenkins node",
...
"jobs" : [
  {
    "_class" : "hudson.model.FreeStyleProject",
    "name" : "Freestyle-Project",
    "url" : "http://xmg:8080/job/Freestyle-Project/",
    "color" : "aborted_anime"
  }
]
...
</code>```

which you can filter then with:

```<code>nodeDescription.equals('the master Jenkins node') && color.endsWith('_anime').
</code>```

Body:
I have been trying to find a lightweight method in a Groovy scriptler script to list all currently running jobs of any type.  The only method I have found to be reliable is this:

start = System.currentTimeMillis()
def jobsFound = []
def buildingJobs = Jenkins.instance.getAllItems(Job.class).findAll {
            it.isBuilding()
    }
buildingJobs.each { job->
    allRuns = job._getRuns()
    allRuns.each {  item->
        if (!item.isBuilding()) {  return  } // This job is not building
    jobsFound.push(item.getUrl())
    }
}

timespent = (System.currentTimeMillis() - start ) / 1000
println "Time: ${timespent} seconds"
println "{jobsFound.size} jobs"

// RESULTS:
//   Time: 2.015 seconds. 15 jobs

The problem is that the above enumerates ALL currently running jobs - we have thousands! - then enumerate all builds of each of those running jobs (some jobs have as many as 300 builds).  The above can take as long as FIVE minutes to complete depending on how many jobs are currently building.

A much more efficient method is to enumerate the active executors
but this method MISSES the pipeline (aka Workflow) jobs running on the master:

start = System.currentTimeMillis()

def busyExecutors = Jenkins.instance.computers.collect {
   c -> c.executors.findAll { it.isBusy() }
}.flatten()

def jobsFound = []
busyExecutors.each { e ->
     job = e.getCurrentExecutable()
     jobsFound.push(job.getUrl())
}

timespent = (System.currentTimeMillis() - start ) / 1000
println "Time: ${timespent} seconds. ${jobsFound.size} jobs"

// RESULTS:
//    Time: 0.005 seconds. 12 jobs

Sure enough the discrepancy between the two counts are pipeline jobs running on the master.

I guess my question boils down to:

Is there a way to efficiently enumerate all jobs running on the master?

Clearly Jenkins does not include the master in computers, and although there is a MasterComputer class, its not clear how to get it or the OffByOneExecutors on which flyweight (pipeline) jobs run.

Body:
Not directly with Jenkins types/objects but via Jenkins' Remote access API derived from From Jenkins, how do I get a list of the currently running jobs in JSON?:

http://localhost:8080/api/xml?&tree=jobs[builds[*]]&xpath=/hudson/job/build[building="true"]&wrapper=builds

results in:

<builds>
    <build _class="hudson.model.FreeStyleBuild">
        <action _class="hudson.model.CauseAction"/>
        <action/>
        <action/>
        <building>true</building>
        <displayName>#10</displayName>
        <duration>0</duration>
        <estimatedDuration>3617</estimatedDuration>
        <executor/>
        <fullDisplayName>Freestyle-Project #10</fullDisplayName>
        <id>10</id>
        <keepLog>false</keepLog>
        <number>10</number>
        <queueId>2</queueId>
        <timestamp>1499611190781</timestamp>
        <url>http://localhost:8080/job/Freestyle-Project/10/</url>
        <builtOn/>
        <changeSet _class="hudson.scm.EmptyChangeLogSet"/>
    </build>
</builds>

Unfortunately <builtOn/>, which, I guess, is supposed to refer to the node, isn't supplied in my Jenkins v2.60.1 (yet?).

With:

http://localhost:8080/api/json?pretty=true

you get:

...
"nodeDescription" : "the master Jenkins node",
...
"jobs" : [
  {
    "_class" : "hudson.model.FreeStyleProject",
    "name" : "Freestyle-Project",
    "url" : "http://xmg:8080/job/Freestyle-Project/",
    "color" : "aborted_anime"
  }
]
...

which you can filter then with:

nodeDescription.equals('the master Jenkins node') && color.endsWith('_anime').


问:
React function with multiple params
I'm having issues trying to use my delete function that calls an API method for removing that selected item from the database.

The API just accepts the page ID, so I've been trying to send the ID to the api.

This is the function that lives in the main container of the app.

```<code>  deletePage(id) {
    instance.put(`/admin/deletePage/${id}`).then((response) => {
      this.getPages();
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }
</code>```

I then pass this function down as a prop to the Dashboard component, where I create another function to handle the delete:

```<code>  handleDelete(e, id) {
    e.preventDefault()
    this.props.deletePage(id)
  }
</code>```

and finally, my render function:

```<code>render() {
    const pages = this.props.pages.map((page, i) => {
        return (
        <div key={i}>
        <h2>{page.title}</h2>
        <a href={`/admin/edit-page/${i}`}>Edit</a>
        <button onClick={this.handleDelete(i)}>Delete</button>
        </div>
        )
    });

    return (
      <div>
        <h2>Dashboard</h2>
        {pages}
      </div>
    );
  }
</code>```

Currently I get this error in console: e.preventDefault is not a function

And if I remove the preventDefault line it just causes a constant reload.

Please help. Just trying to delete stuff mwhaha

答:
you should use a higher order function to do this. Its just a function that return another function.

```<code>handleDelete(id) {
    return (event)=> {
        event.preventDefault()
        this.props.deletePage(id)
    }
}
</code>```

then call the same way you were doing before

```<code> <button onClick={this.handleDelete(i)}>Delete</button>
</code>```

Title: React function with multiple params

Body:
I'm having issues trying to use my delete function that calls an API method for removing that selected item from the database.

The API just accepts the page ID, so I've been trying to send the ID to the api.

This is the function that lives in the main container of the app.

  deletePage(id) {
    instance.put(`/admin/deletePage/${id}`).then((response) => {
      this.getPages();
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

I then pass this function down as a prop to the Dashboard component, where I create another function to handle the delete:

  handleDelete(e, id) {
    e.preventDefault()
    this.props.deletePage(id)
  }

and finally, my render function:

render() {
    const pages = this.props.pages.map((page, i) => {
        return (

{page.title}

        <a href={`/admin/edit-page/${i}`}>Edit
        <button onClick={this.handleDelete(i)}>Delete</button>

        )
    });

    return (

Dashboard

        {pages}

    );
  }

Currently I get this error in console: e.preventDefault is not a function

And if I remove the preventDefault line it just causes a constant reload.

Please help. Just trying to delete stuff mwhaha

Body:
you should use a higher order function to do this. Its just a function that return another function.

handleDelete(id) {
    return (event)=> {
        event.preventDefault()
        this.props.deletePage(id)
    }
}

then call the same way you were doing before

 <button onClick={this.handleDelete(i)}>Delete</button>


问:
SonarLint prompt "Close this 'FileReader'", when I close actually closed it in the finally block
When I ananyze some code using sonarlint in eclipse which close the FileReader in the finally block, the sonarlint prompt me that "Close this 'FileReader'" which is generated by the rule "Resources should be closed". Is this a bug from SonarLint?. Is this a bug from SonarLint?

I can't use try-with-resources features, because our project using JDK 1.6

The code is like below:

```<code>FileReader fr = null;
try {
    fr = new FileReader(pidFile);
    oldPid = new BufferedReader(fr).readLine();
}
catch (IOException e) {
    LOGGER.error(e.getMessage(), e);
}
finally {
    try {
        if (fr != null) {
            fr.close();
        }
    }
    catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
</code>```

答:
You are not closing the buffered reader in the finally block. I suggest you remove everything in the finally block and add the following

IOUtils.closeQuietly(fr);
 IOUtils.closeQuietly(oldPid);

Body:
When I ananyze some code using sonarlint in eclipse which close the FileReader in the finally block, the sonarlint prompt me that "Close this 'FileReader'" which is generated by the rule "Resources should be closed". Is this a bug from SonarLint?. Is this a bug from SonarLint?

I can't use try-with-resources features, because our project using JDK 1.6

The code is like below:

FileReader fr = null;
try {
    fr = new FileReader(pidFile);
    oldPid = new BufferedReader(fr).readLine();
}
catch (IOException e) {
    LOGGER.error(e.getMessage(), e);
}
finally {
    try {
        if (fr != null) {
            fr.close();
        }
    }
    catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
}


问:
Openshift - java.net.BindException: Permission denied
I am trying to create a simple java application that downloads a file from URL, stores the file and then uploads the file to FTP to store it.

I have a (local) working code that downloads the file to my local machine on C:\ and uses the local file to upload to FTP.

I would like to move this application to OpenShift and run it in Tomcat6 from there. This means that I have to change the C:\ drive reference to a directory in OpenShift. I referenced the "tmp" directory.

```<code>    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URL;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.log4j.Logger;

    public class AppRun {

        public static void main(String[] args) {

            Logger log = Logger.getLogger(AppRun.class);

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            String formattedDate = sdf.format(date);

            downloadFile(formattedDate);
            uploadFile(formattedDate);
        }

        // FILE DOWNLOAD
        public static void downloadFile(String formattedDate){

            Logger log = Logger.getLogger(AppRun.class);

            String sourceURL = "http://websiteURL/pdf/"+formattedDate+".pdf";
            String destinationLocation = "/tmp/"+formattedDate+".pdf";
            try {
                org.apache.commons.io.FileUtils.copyURLToFile(
                                new URL(sourceURL),
                                new File(destinationLocation)
                                );
                log.warn("/tmp/"+formattedDate+".pdf downloaded successfully!" );
            }
            catch (Exception e) {
                log.error(e);
                log.error("Source URL : " + "http://websiteURL/pdf/"+formattedDate+".pdf" + " Destination URL : " + "/tmp/"+formattedDate+".pdf");
                System.out.println("No file found!");
            }

        }

        // FILE UPLOAD
        public static void uploadFile(String formattedDate){

            Logger log = Logger.getLogger(AppRun.class);

            FTPClient client = new FTPClient();
            FileInputStream fis = null;

            try {

                client.connect("ftp.domain.com");
                client.login("user", "pass");

                // Create an InputStream of the file to be uploaded
                String originalFile = "/tmp/"+formattedDate+".pdf";
                fis = new FileInputStream(originalFile);

                //
                // Store file to server
                //
                String destinationFileName = formattedDate +".pdf";
                client.storeFile(destinationFileName, fis);
                log.warn("File " + formattedDate +".pdf uploaded successfully!");
                client.logout();

            } catch (IOException e) {
                log.error(e);
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    client.disconnect();
                } catch (IOException e) {
                    log.error(e);
                    e.printStackTrace();
                }
            }

        }
    }
</code>```

When I run the code, I can download the file but the upload part fails:

/var/lib/openshift/XXXXXXXXXXXXXXXXXXXX/app-root/runtime/repo//.openshift/cron/minutely/java:
  2015-09-15 22:27:08 WARN  AppRun:41 - /tmp/20150915.pdf downloaded
  successfully! 2015-09-15 22:27:09 ERROR AppRun:77 -
  java.net.BindException: Permission denied java.net.BindException:
  Permission denied
          at java.net.PlainSocketImpl.socketBind(Native Method)
          at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
          at java.net.ServerSocket.bind(ServerSocket.java:376)
          at java.net.ServerSocket.(ServerSocket.java:237)
          at javax.net.DefaultServerSocketFactory.createServerSocket(ServerSocketFactory.java:231)
          at org.apache.commons.net.ftp.FTPClient.openDataConnection(FTPClient.java:797)
          at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:633)
          at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:624)
          at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1976)
          at AppRun.uploadFile(AppRun.java:72)
          at AppRun.main(AppRun.java:25)

Any suggestions how to fix this would be greatly appreciated! Thanks.

答:
Configure the client for FTP PASSIVE mode.

Try adding ftp.enterLocalPassiveMode() after login.

Body:
I am trying to create a simple java application that downloads a file from URL, stores the file and then uploads the file to FTP to store it.

I have a (local) working code that downloads the file to my local machine on C:\ and uses the local file to upload to FTP.

I would like to move this application to OpenShift and run it in Tomcat6 from there. This means that I have to change the C:\ drive reference to a directory in OpenShift. I referenced the "tmp" directory.

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URL;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.log4j.Logger;

    public class AppRun {

        public static void main(String[] args) {

            Logger log = Logger.getLogger(AppRun.class);

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            String formattedDate = sdf.format(date);

            downloadFile(formattedDate);
            uploadFile(formattedDate);
        }

        // FILE DOWNLOAD
        public static void downloadFile(String formattedDate){

            Logger log = Logger.getLogger(AppRun.class);

            String sourceURL = "http://websiteURL/pdf/"+formattedDate+".pdf";
            String destinationLocation = "/tmp/"+formattedDate+".pdf";
            try {
                org.apache.commons.io.FileUtils.copyURLToFile(
                                new URL(sourceURL),
                                new File(destinationLocation)
                                );
                log.warn("/tmp/"+formattedDate+".pdf downloaded successfully!" );
            }
            catch (Exception e) {
                log.error(e);
                log.error("Source URL : " + "http://websiteURL/pdf/"+formattedDate+".pdf" + " Destination URL : " + "/tmp/"+formattedDate+".pdf");
                System.out.println("No file found!");
            }

        }

        // FILE UPLOAD
        public static void uploadFile(String formattedDate){

            Logger log = Logger.getLogger(AppRun.class);

            FTPClient client = new FTPClient();
            FileInputStream fis = null;

            try {

                client.connect("ftp.domain.com");
                client.login("user", "pass");

                // Create an InputStream of the file to be uploaded
                String originalFile = "/tmp/"+formattedDate+".pdf";
                fis = new FileInputStream(originalFile);

                //
                // Store file to server
                //
                String destinationFileName = formattedDate +".pdf";
                client.storeFile(destinationFileName, fis);
                log.warn("File " + formattedDate +".pdf uploaded successfully!");
                client.logout();

            } catch (IOException e) {
                log.error(e);
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    client.disconnect();
                } catch (IOException e) {
                    log.error(e);
                    e.printStackTrace();
                }
            }

        }
    }

When I run the code, I can download the file but the upload part fails:

/var/lib/openshift/XXXXXXXXXXXXXXXXXXXX/app-root/runtime/repo//.openshift/cron/minutely/java:
  2015-09-15 22:27:08 WARN  AppRun:41 - /tmp/20150915.pdf downloaded
  successfully! 2015-09-15 22:27:09 ERROR AppRun:77 -
  java.net.BindException: Permission denied java.net.BindException:
  Permission denied
          at java.net.PlainSocketImpl.socketBind(Native Method)
          at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
          at java.net.ServerSocket.bind(ServerSocket.java:376)
          at java.net.ServerSocket.(ServerSocket.java:237)
          at javax.net.DefaultServerSocketFactory.createServerSocket(ServerSocketFactory.java:231)
          at org.apache.commons.net.ftp.FTPClient.openDataConnection(FTPClient.java:797)
          at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:633)
          at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:624)
          at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1976)
          at AppRun.uploadFile(AppRun.java:72)
          at AppRun.main(AppRun.java:25)

Any suggestions how to fix this would be greatly appreciated! Thanks.


问:
Storyboard preview issue after converting to Swift 3/Xcode 8
Something strange happened to my project after I upgraded to Xcode 8 and converted the project to Swift 3.
Most interesting thing is that layout shows fine in the simulator but in the Preview everything is shifted to the right. Center of all devices appears to be almost at the right edge. For example I drag a label to the storyboard select Align Horizontally and add a constraint to the top... in preview it shows up for all devices shifted to the right instead of in the middle but in the simulator label is in the middle, exactly where it is supposed to be.
Also, if I create a new ViewController is would work just fine in preview and simulator... Anybody knows what can cause this issue?   </p>

答: Leaving Xcode and re-starting worked for me to get the correct view per device in Storyboard again.</p>


问:
Make whole page non-interactive except for one element
How would I make a webpage completely non-interactive to the user, but make one div (or other element) interactive?</p>

答:
You can do it with CSS only using pointer events. Set pointer-events: none on the body. Set pointer-events: auto on the target element.

var buttons = [].slice.call(document.getElementsByTagName('button'), 0);

buttons.forEach(function(button) {
  button.addEventListener('click', function() {
    console.log('responds');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  pointer-events: none;
}

.respond {
  pointer-events: auto;
}</code>```

<button>I don't respond</button>

  <button class="respond">I respond</button>

  <button>I don't respond</button>

  <button>I don't respond</button>

```

Body:
You can do it with CSS only using pointer events. Set pointer-events: none on the body. Set pointer-events: auto on the target element.

var buttons = [].slice.call(document.getElementsByTagName('button'), 0);

buttons.forEach(function(button) {
  button.addEventListener('click', function() {
    console.log('responds');
  });
});

body {
  pointer-events: none;
}

.respond {
  pointer-events: auto;
}

<button>I don't respond</button>

<div>
  <button class="respond">I respond</button>

  <button>I don't respond</button>

  <button>I don't respond</button>
</div>


问:
Changing or preventing the use of E in Python?
I'm currently trying to write a script that will create a unique ID for a user relying on a number of variables, like birthdate, name, hometown, etc. This creates a very long number that is completely unique to that user, however, to try to make the number even more unique, I want to change a random number in the string. This is what I have so far:

```<code>rand = randint(1,15)
tempid = id / 10**rand
if randint(1,2) == 1:
    tempid = tempid + randint(2,10000)
else:
    tempid = tempid - randint(5,7500)
print(id)
id = tempid * (10**rand)
print(str(id))
</code>```

The code is fairly simple. It makes the number much smaller by dividing it by a large multiple of 10, adds or subtracts a random number, and multiplies it back to it's original length, with some changed numbers in the middle. The only problem is, because it must be an integer to be able to do any math with it, Python shortens it to 1.[something]e+[something]. This isn't helpful at all, becasue now it's not an ID. Is there anyway I can change it back to its original form, where it's just a long string, or perhaps change the code so it never becomes e? Thank you!

答: Unless this is a specific exercise, you do not want to generate unique IDs the way you do. It will fail. Use the uuid module instead.

Body:
I'm currently trying to write a script that will create a unique ID for a user relying on a number of variables, like birthdate, name, hometown, etc. This creates a very long number that is completely unique to that user, however, to try to make the number even more unique, I want to change a random number in the string. This is what I have so far:

rand = randint(1,15)
tempid = id / 10**rand
if randint(1,2) == 1:
    tempid = tempid + randint(2,10000)
else:
    tempid = tempid - randint(5,7500)
print(id)
id = tempid * (10**rand)
print(str(id))

The code is fairly simple. It makes the number much smaller by dividing it by a large multiple of 10, adds or subtracts a random number, and multiplies it back to it's original length, with some changed numbers in the middle. The only problem is, because it must be an integer to be able to do any math with it, Python shortens it to 1.[something]e+[something]. This isn't helpful at all, becasue now it's not an ID. Is there anyway I can change it back to its original form, where it's just a long string, or perhaps change the code so it never becomes e? Thank you!