问:
Trying to get a Java function to return an array based on a string parameter passed to it
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

```<code>String[]names = initial(department)
</code>```

Departments is the name of the department being passed to the function. In the function I have:

```<code>public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }
</code>```

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

答:
The problem is that you're declaring each String[] assignInitial inside an if statements, so the scope of that variable is local to the if statement. Outside of the if statements, that variable is not declared.

To fix this, pull the declaration out of the if scope and into the method scope. You'll have to add new String[] in front of each array since array constants can only be used in initializers.

```<code>public static String[] initial (String responsibleDepartment) {

String[] assignInitial = null;

if (responsibleDepartment.equals("Accounts Receivable")) {
    // Note the new String[] below
    assignInitial = new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
 }

if (responsibleDepartment.equals("Customer Service")) {
    assignInitial = new String[] {"Mary Wexler", "Turd Ferguson"};
 }

// Other if statements here

return assignInitial;
</code>```

Note that there might be other, easier ways to find the values for assignInitial than this series of if statements. For example, you could built a switch statement or a Map<String, String>.

Body:
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

String[]names = initial(department)

Departments is the name of the department being passed to the function. In the function I have:

public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

Body:
The problem is that you're declaring each String[] assignInitial inside an if statements, so the scope of that variable is local to the if statement. Outside of the if statements, that variable is not declared.

To fix this, pull the declaration out of the if scope and into the method scope. You'll have to add new String[] in front of each array since array constants can only be used in initializers.

public static String[] initial (String responsibleDepartment) {

String[] assignInitial = null;

if (responsibleDepartment.equals("Accounts Receivable")) {
    // Note the new String[] below
    assignInitial = new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
 }

if (responsibleDepartment.equals("Customer Service")) {
    assignInitial = new String[] {"Mary Wexler", "Turd Ferguson"};
 }

// Other if statements here

return assignInitial;

Note that there might be other, easier ways to find the values for assignInitial than this series of if statements. For example, you could built a switch statement or a Map<String, String>.


来源: stackexchange

问:
Cordova Request Location Accuracy Plugin
I want to use Cordova Request Location Accuracy Plugin in my phonegap app
i add
in my config.xml and then i try to use  cordova.plugins.locationAccuracy.request(); but my console throws
TypeError: cordova.plugins.locationAccuracy is undefined
What am i missing?
Thanks!!</p>

答:
If building locally, make sure it's installed in your project:

```<code>$ cordova plugin add cordova-plugin-request-location-accuracy
</code>```

Or if building in cloud (e.g. Phonegap Build), make sure it's referenced in the config.xml:

```<code><plugin name="cordova-plugin-request-location-accuracy" spec="*" />
</code>```

Then make sure you wait for the deviceready event before referencing the plugin, because Cordova dynamically loads the JS plugin components at runtime:

```<code>document.addEventListener("deviceready", function(){
    cordova.plugins.locationAccuracy.request();
}, false);
</code>```

Check the plugin documentation for platform-specifics and the example project for an illustration of usage.

ContentLicense: CC BY-SA 3.0

Body:
If building locally, make sure it's installed in your project:

$ cordova plugin add cordova-plugin-request-location-accuracy

Or if building in cloud (e.g. Phonegap Build), make sure it's referenced in the config.xml:

<plugin name="cordova-plugin-request-location-accuracy" spec="*" />

Then make sure you wait for the deviceready event before referencing the plugin, because Cordova dynamically loads the JS plugin components at runtime:

document.addEventListener("deviceready", function(){
    cordova.plugins.locationAccuracy.request();
}, false);

Check the plugin documentation for platform-specifics and the example project for an illustration of usage.


答:
Something like this will probably work</p>

```<code>df['new col']=const1*df['is1']+.....+const6*df['im10']
</code>```

Title: Adding a column to a dataframe

Body:
I have a dataframe like this:

case    is1     is5     is10    im1     im5     im10
686     0.1406  0.2997  0.1490  0.1339  0.1350  0.1417
950     0.1602  0.3448  0.1719  0.0884  0.0962  0.1385
1005    0.1641  0.2606  0.1507  0.1306  0.1613  0.1328
1005    0.1456  0.3097  0.1825  0.1116  0.1295  0.1211

I'd like to add a 8th column using a formula, say

const1*is1+const2*is2+...const6*im10

How would I do that?

Body:
Something like this will probably work

df['new col']=const1*df['is1']+.....+const6*df['im10']


答:
Try this, initial assignInitial outside conditions and use variable in all places.</p>

```<code>public static String[] initial (String responsibleDepartment) {
    String[] assignInitial = null;

    if (responsibleDepartment.equals("Accounts Receivable")) {
        assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }
</code>```

Title: Trying to get a Java function to return an array based on a string parameter passed to it

Body:
Try this, initial assignInitial outside conditions and use variable in all places.

public static String[] initial (String responsibleDepartment) {
    String[] assignInitial = null;

    if (responsibleDepartment.equals("Accounts Receivable")) {
        assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }


答:
You need to create the variable and then assign the value to be accessible outside the if condition. Or you can return the variable right after you create it to stop the flow of the method if you don't need to do anything else in the function. </p>

```<code>public static String[] initial (String responsibleDepartment) {
    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"};
        return assignInitial;
    }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
        return assignInitial;
    }
    // and 38 more if statements with the rest of the departments. Finally I have:
    return null;
    }
</code>```

<p>If you define the variable inside the if context, it is not available to be returned after the context is completed. </p>

Body:
You need to create the variable and then assign the value to be accessible outside the if condition. Or you can return the variable right after you create it to stop the flow of the method if you don't need to do anything else in the function.

public static String[] initial (String responsibleDepartment) {
    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"};
        return assignInitial;
    }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
        return assignInitial;
    }
    // and 38 more if statements with the rest of the departments. Finally I have:
    return null;
    }

If you define the variable inside the if context, it is not available to be returned after the context is completed.


问:
xamarin form android need to open pdf with my app (no show)
I'm using this guide to open a pdf inside my app. All I want is to see my app in the list of apps that can be aple to open a file (pdf) when I press 'share'.
So, until now my iOS project works so it's an Android settings problem.

MainActivity:

```<code>[Activity(Label = "Test", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true)]
[IntentFilter(
    new[] { Intent.ActionView },
   Categories = new[]
  {
      Intent.CategoryDefault,
      Intent.CategoryBrowsable,
  },
  DataScheme = "file",
  DataMimeType = "*/*",
  DataPathPattern = ".*\\.pdf"
)]

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        string action = Intent.Action;
        string type = Intent.Type;

        global::Xamarin.Forms.Forms.Init(this, bundle);

        var application = new App();

        if (Intent.ActionView.Equals(action) && !String.IsNullOrEmpty(type))
        {
            Android.Net.Uri fileUri = Intent.Data;

            if (fileUri != null)
            {
                var fileContent = File.ReadAllBytes(fileUri.Path);
                var name = fileUri.LastPathSegment;
                application.SetExternDocument(new IncomingFile()
                {
                    Name = name,
                    Content = fileContent
                });
            }
        }

        LoadApplication(application);
    }
}
</code>```

and Manifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="com.bbinternational.inviofatture.BBInvioFatture">

<uses-sdk android:minSdkVersion="21" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
</code>```

As you can see I didn't write anything into the manifest because I used  Attributes in the main Activity.
I tried to use manifest but i can't retrieve the MainActivity android:name property using Xamarin (at runtime it allocates some random values or at least is what I know).

Thanks for the help.

Cheers guys.

答:
So, after hours of googling this dude saved me.

https://codemilltech.com/sending-files-to-a-xamarin-forms-app-part-2-android/

As i supposed the IntentFilterAttributes were wrong. This is the right version

```<code>[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = @"application/pdf")]
</code>```

Hope to help somebody.

Body:
I'm using this guide to open a pdf inside my app. All I want is to see my app in the list of apps that can be aple to open a file (pdf) when I press 'share'.
So, until now my iOS project works so it's an Android settings problem.

MainActivity:

[Activity(Label = "Test", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true)]
[IntentFilter(
    new[] { Intent.ActionView },
   Categories = new[]
  {
      Intent.CategoryDefault,
      Intent.CategoryBrowsable,
  },
  DataScheme = "file",
  DataMimeType = "*/*",
  DataPathPattern = ".*\\.pdf"
)]

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        string action = Intent.Action;
        string type = Intent.Type;

        global::Xamarin.Forms.Forms.Init(this, bundle);

        var application = new App();

        if (Intent.ActionView.Equals(action) && !String.IsNullOrEmpty(type))
        {
            Android.Net.Uri fileUri = Intent.Data;

            if (fileUri != null)
            {
                var fileContent = File.ReadAllBytes(fileUri.Path);
                var name = fileUri.LastPathSegment;
                application.SetExternDocument(new IncomingFile()
                {
                    Name = name,
                    Content = fileContent
                });
            }
        }

        LoadApplication(application);
    }
}

and Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="com.bbinternational.inviofatture.BBInvioFatture">

<uses-sdk android:minSdkVersion="21" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

As you can see I didn't write anything into the manifest because I used  Attributes in the main Activity.
I tried to use manifest but i can't retrieve the MainActivity android:name property using Xamarin (at runtime it allocates some random values or at least is what I know).

Thanks for the help.

Cheers guys.

Body:
So, after hours of googling this dude saved me.

https://codemilltech.com/sending-files-to-a-xamarin-forms-app-part-2-android/

As i supposed the IntentFilterAttributes were wrong. This is the right version

[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = @"application/pdf")]

Hope to help somebody.


问:
Extracting all named values from an ansible array
I'm not even quite sure how to describe what I'm trying to do!
So I'll just jump straight in.
I have a hosts file :

```<code>[jvbservers]
jvb0  ansible_host=serverA
jvb1  ansible_host=serverB
</code>```

etc...

And I want a list of the servers in the jvbservers group. What I've come up with so far feels a bit OTT.

```<code>  set_fact:
    jvb_names: "{{ jvb_names|default([]) + [ hostvars[groups.jvbservers[item|int]].ansible_host ] }}"
  with_sequence: start=0 end="{{groups.jvbservers|length-1}}"
</code>```

Gives me a result like I want :

```<code>ok: [localhost] => {
    "jvb_names": [
        "serverA",
        "serverB"
    ]
}
</code>```

Is this sensible? It feels like there should be a neater way to do something like :

```<code>hostvars[groups.jvbservers[*]].ansible_host
</code>```

(Where "*" would be a pattern matching all valid options. Obvs that particular syntax doesn't exist!)

答:
Have you tried this?:

```<code>- name: show all the hosts matching jvbservers
  debug:
    msg: "{{ item }}"
  with_inventory_hostnames:
    - all: jvbservers
</code>```

https://docs.ansible.com/ansible/devel/plugins/lookup/inventory_hostnames.html

Body:
I'm not even quite sure how to describe what I'm trying to do!
So I'll just jump straight in.
I have a hosts file :

[jvbservers]
jvb0  ansible_host=serverA
jvb1  ansible_host=serverB

etc...

And I want a list of the servers in the jvbservers group. What I've come up with so far feels a bit OTT.

  set_fact:
    jvb_names: "{{ jvb_names|default([]) + [ hostvars[groups.jvbservers[item|int]].ansible_host ] }}"
  with_sequence: start=0 end="{{groups.jvbservers|length-1}}"

Gives me a result like I want :

ok: [localhost] => {
    "jvb_names": [
        "serverA",
        "serverB"
    ]
}

Is this sensible? It feels like there should be a neater way to do something like :

hostvars[groups.jvbservers[*]].ansible_host

(Where "*" would be a pattern matching all valid options. Obvs that particular syntax doesn't exist!)

Body:
Have you tried this?:

- name: show all the hosts matching jvbservers
  debug:
    msg: "{{ item }}"
  with_inventory_hostnames:
    - all: jvbservers

https://docs.ansible.com/ansible/devel/plugins/lookup/inventory_hostnames.html


问:
Cannot succesfully validate reCAPTCHA via AJAX in Flask application
I am making a Flask application and I am trying to use Google reCAPTCHA for making verfication before sending form.

However, I am constantly getting an error. Software is not recognizing that I pressed reCAPTCHA button and I don't know why.
Before I put reCAPTCHA field, everything was working fine.

Below is the full code:

1) Flask:

```<code>from flask import Flask, render_template, request, jsonify
from flask_wtf.csrf import CSRFProtect
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import InputRequired
from flask_wtf.recaptcha import RecaptchaField

app = Flask(__name__)

app.config['SECRET_KEY'] = 'proba123Jakov'
app.config.update(
    RECAPTCHA_ENABLED = True,
    RECAPTCHA_PUBLIC_KEY = 'mypublickey',
    RECPATCHA_PRIVATE_KEY = 'myprivatekey',
)

csrf = CSRFProtect(app)
Bootstrap(app)

class MailForm(FlaskForm):
    firstname = StringField('Name *', _name='firstname', validators=[InputRequired()], render_kw={"placeholder": "Your name"}, id="firstnameInput")
    lastname = StringField('Surname *', _name='lastname', validators=[InputRequired()], render_kw={"placeholder": "Your surname"}, id="lastnameInput")
    recaptcha = RecaptchaField()

@app.route('/')
def contact():
    form = MailForm()
    return render_template('contactForm.html', form=form)

@app.route('/send', methods=['POST'])
def mailSend():
    global previousEmailMessage
    form = MailForm()

    if form.validate_on_submit():
        return jsonify({'firstname' : request.form.get('firstname'), 'lastname' : request.form.get('lastname')})
    return jsonify({'error' : 'You havent put all data or press recaptcha button'})

if __name__ == '__main__':
    app.run()
</code>```

2) JS:

```<code>$(document).ready(function() {

    var csrftoken = $('meta[name=csrf-token]').attr('content');

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken)
            }
        }
    });

    $('#contact-form').on('submit', function(event) { // GET METHOD IS ACTIVATED SOMEHOW

        $.ajax({
            data : {
                firstname : $('#firstnameInput').val(),
                lastname : $('#lastnameInput').val(),
                message : $('#messageInput').val()
            },
            type : 'POST',
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'
            },
            url : '/send',
            dataType: "json"
        })
        .done(function(data) {

            if (data.error) {
                $('#successAlert').hide();
                $('#errorAlert').text(data.error).show();
            }
            else {
                $('#successAlert').text("Vaša poruka je uspješno poslana!").show();
                $('#errorAlert').hide();
            }
        });
        event.preventDefault();
    });

});
</code>```

3) HTML:

```<code>{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block head %}
    {{ super() }}
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    <script src="{{ url_for('static', filename='ajaxForm.js') }}" type="text/javascript"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
{% endblock %}

{% block content %}

    <form id="contact-form">
        {{ wtf.form_field(form.firstname) }}
        {{ wtf.form_field(form.lastname) }}
        {{ wtf.form_field(form.recaptcha) }}
        <input type="submit" class="btn btn-lg btn-primary btn-block" value="SEND">
        <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
        <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
    </form>
{% endblock %}
</code>```

This is what i get when I fill the form:

Please help.

答:
I managed to solve this problem. The problem was that I was not sending reCAPTCHA field in AJAX request.

I had to to change data of the AJAX request in order to send reCAPTCHA field.

```<code>data : {
        firstname : $('#firstnameInput').val(),
        lastname : $('#lastnameInput').val(),
        recaptcha : grecaptcha.getResponse()
            }
</code>```

Afterwards, it was necessary to make different validation in Flask. If recaptcha is longer than 0, it means that reCAPTCHA checkbox was pressed.

```<code>if form.is_submitted():
    if request.form.get('recaptcha'):
        return jsonify({'firstname' : request.form.get('firstname')})
    return jsonify({'error' : 'reCAPTCHA button was not pressed'})
</code>```

Now it is working.

ContentLicense: CC BY-SA 4.0

Body:
I am making a Flask application and I am trying to use Google reCAPTCHA for making verfication before sending form.

However, I am constantly getting an error. Software is not recognizing that I pressed reCAPTCHA button and I don't know why.
Before I put reCAPTCHA field, everything was working fine.

Below is the full code:

1) Flask:

from flask import Flask, render_template, request, jsonify
from flask_wtf.csrf import CSRFProtect
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import InputRequired
from flask_wtf.recaptcha import RecaptchaField

app = Flask(__name__)

app.config['SECRET_KEY'] = 'proba123Jakov'
app.config.update(
    RECAPTCHA_ENABLED = True,
    RECAPTCHA_PUBLIC_KEY = 'mypublickey',
    RECPATCHA_PRIVATE_KEY = 'myprivatekey',
)

csrf = CSRFProtect(app)
Bootstrap(app)

class MailForm(FlaskForm):
    firstname = StringField('Name *', _name='firstname', validators=[InputRequired()], render_kw={"placeholder": "Your name"}, id="firstnameInput")
    lastname = StringField('Surname *', _name='lastname', validators=[InputRequired()], render_kw={"placeholder": "Your surname"}, id="lastnameInput")
    recaptcha = RecaptchaField()

@app.route('/')
def contact():
    form = MailForm()
    return render_template('contactForm.html', form=form)

@app.route('/send', methods=['POST'])
def mailSend():
    global previousEmailMessage
    form = MailForm()

    if form.validate_on_submit():
        return jsonify({'firstname' : request.form.get('firstname'), 'lastname' : request.form.get('lastname')})
    return jsonify({'error' : 'You havent put all data or press recaptcha button'})

if __name__ == '__main__':
    app.run()

2) JS:

$(document).ready(function() {

    var csrftoken = $('meta[name=csrf-token]').attr('content');

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken)
            }
        }
    });

    $('#contact-form').on('submit', function(event) { // GET METHOD IS ACTIVATED SOMEHOW

        $.ajax({
            data : {
                firstname : $('#firstnameInput').val(),
                lastname : $('#lastnameInput').val(),
                message : $('#messageInput').val()
            },
            type : 'POST',
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'
            },
            url : '/send',
            dataType: "json"
        })
        .done(function(data) {

            if (data.error) {
                $('#successAlert').hide();
                $('#errorAlert').text(data.error).show();
            }
            else {
                $('#successAlert').text("Vaša poruka je uspješno poslana!").show();
                $('#errorAlert').hide();
            }
        });
        event.preventDefault();
    });

});

3) HTML:

{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block head %}
    {{ super() }}
    <meta name="csrf-token" content="{{ csrf_token() }}">

{% endblock %}

{% block content %}

    <form id="contact-form">
        {{ wtf.form_field(form.firstname) }}
        {{ wtf.form_field(form.lastname) }}
        {{ wtf.form_field(form.recaptcha) }}
        <input type="submit" class="btn btn-lg btn-primary btn-block" value="SEND">

    </form>
{% endblock %}

This is what i get when I fill the form:

Please help.

Body:
I managed to solve this problem. The problem was that I was not sending reCAPTCHA field in AJAX request.

I had to to change data of the AJAX request in order to send reCAPTCHA field.

data : {
        firstname : $('#firstnameInput').val(),
        lastname : $('#lastnameInput').val(),
        recaptcha : grecaptcha.getResponse()
            }

Afterwards, it was necessary to make different validation in Flask. If recaptcha is longer than 0, it means that reCAPTCHA checkbox was pressed.

if form.is_submitted():
    if request.form.get('recaptcha'):
        return jsonify({'firstname' : request.form.get('firstname')})
    return jsonify({'error' : 'reCAPTCHA button was not pressed'})

Now it is working.


问:
In c++ why is pass by reference is directed by callee rather than by caller
In c++, the function signature defines that it will take the arguments by reference or value. Isn’t it the caller should decide what it wants to pass by reference or value?
Suppose caller does not want the function to modify its values, and is unsure of what the calle is doing inside its function. Then the caller does not have a right to say that the arguments should not be modified.

How is this C++ definiton justified?

答:
It's always caller who "decide" what callee to call based on types of arguments. There are strict resolution rules which are pretty reasonable. Search for C++ overload resolution. E.g.: http://en.cppreference.com/w/cpp/language/overload_resolution.

Different overloads are different functions with same name in source code they have different mangled name but not in object files.


答:
You may want to check extract filter:</p>

```<code>{{ groups['jvbservers'] | map('extract', hostvars, 'ansible_host') | list }}
</code>```

Title: Extracting all named values from an ansible array

Body:
You may want to check extract filter:

{{ groups['jvbservers'] | map('extract', hostvars, 'ansible_host') | list }}


问:
Optional using a generic wild card in map and orElseGet
I prepare a little example to replicate what happens in my project. I know how to workaround it, but I am very curious why it doesn't even compile. The problem is in the last return when I am using a generic wild card in the method public TestElement<?> test(), exactly the line return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));... I don't know why it doesn't compile. What am I doing wrong? Any clue?

Thanks in advance!

```<code>public class FullTest {
  public static class TestElement<T>{
    public T element;

    public TestElement(T t) {
      element = t;
    }
  }

  public static <U> TestElement<U> createElement(U input) {
    return new TestElement<>(input);
  }

  private TestElement<?> mapAux(Long element){
    return new TestElement<>(element);
  }

  private TestElement<?> orElseGetAux(Integer element){
    return new TestElement<>(element);
  }

  public TestElement<?> test(){
    Optional<Long> response =  Optional.of(5L);
    return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));
  }
}
</code>```

Update 1 - Include the error

I am using Java 8, over the last version of IntelliJ, and the error is this:

Error:(33, 78) java: incompatible types: bad return type in lambda  expression

```<code>FullTest.TestElement<capture#1 of ?> cannot be converted to FullTest.TestElement<capture#2> of ?>
</code>```

Update 2 - A little further and workaround

The use of wild card is because I need to return TesElement<> of different classes and It is the only way that I find out (in the example Long and Integer). I am open to other options...

Here a possible workaround that I prefer avoid (It is an example, I know isPresent() always return true) :

```<code>public TestElement<?> testWorkAround(){
    Optional<Long> response =  Optional.of(5L);
    TestElement<?> testElement;
    if(response.isPresent()){
      testElement = mapAux(response.get());
    }
    else{
      testElement = orElseGetAux(20);
    }
    return testElement;
  }
</code>```

答:
Your call to map with the lambda (element) -> mapAux(50L) returns an Optional of what your lambda expression returns, i.e. an Optional<TestElement<?>>.  Your call later to orElseGet also takes a lambda expression that returns a TestElement<?>.

But there is no guarantee that one wildcard matches another wildcard.  Wildcards represent a specific yet unknown type, so the compiler assumes they don't match.  This means you get the compiler errors:

```<code>The method orElseGet(Supplier<? extends Main.TestElement<capture#1-of ?>>) in the type Optional<Main.TestElement<capture#1-of ?>> is not applicable for the arguments (() -> {})
Type mismatch: cannot convert from Main.TestElement<capture#3-of ?> to Main.TestElement<capture#1-of ?>
</code>```

To get this to compile, you should eliminate those wildcards so type inference can do its thing and match.  One of the following:

Make your mapAux and orElseGetAux methods both return TestElement<Long>.

```<code>private TestElement<Long> mapAux(Long element)
private TestElement<Long> orElseGetAux(Long element)
</code>```

Or, make those 2 methods generic, so that the T going in is the same T going out.

```<code>private <T> TestElement<T> mapAux(T element)
private <T> TestElement<T> orElseGetAux(T element)
</code>```

Body:
I prepare a little example to replicate what happens in my project. I know how to workaround it, but I am very curious why it doesn't even compile. The problem is in the last return when I am using a generic wild card in the method public TestElement<?> test(), exactly the line return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));... I don't know why it doesn't compile. What am I doing wrong? Any clue?

Thanks in advance!

public class FullTest {
  public static class TestElement<T>{
    public T element;

    public TestElement(T t) {
      element = t;
    }
  }

  public static  TestElement createElement(U input) {
    return new TestElement<>(input);
  }

  private TestElement<?> mapAux(Long element){
    return new TestElement<>(element);
  }

  private TestElement<?> orElseGetAux(Integer element){
    return new TestElement<>(element);
  }

  public TestElement<?> test(){
    Optional<Long> response =  Optional.of(5L);
    return response.map((element) -> mapAux(50L)).orElseGet(()-> orElseGetAux(20));
  }
}

Update 1 - Include the error

I am using Java 8, over the last version of IntelliJ, and the error is this:

Error:(33, 78) java: incompatible types: bad return type in lambda  expression

FullTest.TestElement<capture#1 of ?> cannot be converted to FullTest.TestElement<capture#2> of ?>

Update 2 - A little further and workaround

The use of wild card is because I need to return TesElement<> of different classes and It is the only way that I find out (in the example Long and Integer). I am open to other options...

Here a possible workaround that I prefer avoid (It is an example, I know isPresent() always return true) :

public TestElement<?> testWorkAround(){
    Optional<Long> response =  Optional.of(5L);
    TestElement<?> testElement;
    if(response.isPresent()){
      testElement = mapAux(response.get());
    }
    else{
      testElement = orElseGetAux(20);
    }
    return testElement;
  }

Body:
Your call to map with the lambda (element) -> mapAux(50L) returns an Optional of what your lambda expression returns, i.e. an Optional<TestElement<?>>.  Your call later to orElseGet also takes a lambda expression that returns a TestElement<?>.

But there is no guarantee that one wildcard matches another wildcard.  Wildcards represent a specific yet unknown type, so the compiler assumes they don't match.  This means you get the compiler errors:

The method orElseGet(Supplier<? extends Main.TestElement<capture#1-of ?>>) in the type Optional<Main.TestElement<capture#1-of ?>> is not applicable for the arguments (() -> {})
Type mismatch: cannot convert from Main.TestElement<capture#3-of ?> to Main.TestElement<capture#1-of ?>

To get this to compile, you should eliminate those wildcards so type inference can do its thing and match.  One of the following:

Make your mapAux and orElseGetAux methods both return TestElement<Long>.

private TestElement<Long> mapAux(Long element)
private TestElement<Long> orElseGetAux(Long element)

Or, make those 2 methods generic, so that the T going in is the same T going out.

private <T> TestElement<T> mapAux(T element)
private <T> TestElement<T> orElseGetAux(T element)


问:
UICollectionview slow data reloading
I make a request, get data, split them into 10 arrays and it takes like 2 seconds. But sorting them into UICollectionView takes almost 10 seconds to show data. Here is my code:

```<code>func makeRequest() {
    let url = URL(string: "https://api.example.com/v1/ticker/?start=" + "\(startingPoint)")
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            if let urlContent = data {
                do {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! [AnyObject]
                    var i: Int!
                    for i in 0..<jsonResult.count {
                        Global.rankArray.append(String(describing: jsonResult[i]["rank"]!!))
                        // 9 other similar lines
                    }
                    // Loading some views
                    self.dataCollection.reloadData()
                } catch {
                    print("Error")
              }
            }
        }
    }
    task.resume()
}
</code>```

So I can print everything quickly but no data is showing in the UICollectionView until 10 seconds pass. The loading time doesn't rely on the internet connection speed.

答:
The issue is you are reloading your UICollectionView on a background thread.  Anything that should immediately update the view must be run on the main thread.  Simply change your reload statement:</p>

```<code>   DispatchQueue.main.async {
      self.dataCollection.reloadData()
   }
</code>```

Title: UICollectionview slow data reloading

Body:
I make a request, get data, split them into 10 arrays and it takes like 2 seconds. But sorting them into UICollectionView takes almost 10 seconds to show data. Here is my code:

func makeRequest() {
    let url = URL(string: "https://api.example.com/v1/ticker/?start=" + "\(startingPoint)")
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            if let urlContent = data {
                do {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! [AnyObject]
                    var i: Int!
                    for i in 0..<jsonResult.count {
                        Global.rankArray.append(String(describing: jsonResult[i]["rank"]!!))
                        // 9 other similar lines
                    }
                    // Loading some views
                    self.dataCollection.reloadData()
                } catch {
                    print("Error")
              }
            }
        }
    }
    task.resume()
}

So I can print everything quickly but no data is showing in the UICollectionView until 10 seconds pass. The loading time doesn't rely on the internet connection speed.

Body:
The issue is you are reloading your UICollectionView on a background thread.  Anything that should immediately update the view must be run on the main thread.  Simply change your reload statement:

   DispatchQueue.main.async {
      self.dataCollection.reloadData()
   }


问:
How do I make a single legend for many subplots?
I am plotting the same type of information, but for different countries, with multiple subplots with Matplotlib. That is, I have nine plots on a 3x3 grid, all with the same for lines (of course, different values per line).

However, I have not figured out how to put a single legend (since all nine subplots have the same lines) on the figure just once.

How do I do that?

答:
This answer is a complement to user707650's answer on the legend position.

My first try on user707650's solution failed due to overlaps of the legend and the subplot's title.

In fact, the overlaps are caused by fig.tight_layout(), which changes the subplots' layout without considering the figure legend. However, fig.tight_layout() is necessary.

In order to avoid the overlaps, we can tell fig.tight_layout() to leave spaces for the figure's legend by fig.tight_layout(rect=(0,0,1,0.9)).

Description of tight_layout() parameters.


问:
Swift 4: How to asynchronously use URLSessionDataTask but have the requests be in a timed queue?
Basically I have some JSON data that I wish to retrieve from a bunch of URL's (all from the same host), however I can only request this data roughly every 2 seconds at minimum and only one at a time or I'll be "time banned" from the server. As you'll see below; while URLSession is very quick it also gets me time banned almost instantly when I have around 700 urls to get through.

How would I go about creating a queue in URLSession (if its functionality supports it) and while having it work asynchronously to my main thread; have it work serially on its own thread and only attempt each item in the queue after 2 seconds have past since it finished the previous request?

```<code>for url in urls {
    get(url: url)
}

func get(url: URL) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            DispatchQueue.main.async {
                print(error.localizedDescription)
            }
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            DispatchQueue.main.async {
                print("Server Error")
            }
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {
                        DispatchQueue.main.async {
                            self.itemsCount.append(count)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}
</code>```

答:
Recursion solves this best</p>

```<code>import Foundation
import PlaygroundSupport

// Let asynchronous code run
PlaygroundPage.current.needsIndefiniteExecution = true

func fetch(urls: [URL]) {

    guard urls.count > 0 else {
        print("Queue finished")
        return
    }

    var pendingURLs = urls
    let currentUrl = pendingURLs.removeFirst()

    print("\(pendingURLs.count)")

    let session = URLSession.shared
    let task = session.dataTask(with: currentUrl, completionHandler: { (data, response, error) in
        print("task completed")
        if let _ = error {
            print("error received")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
            return
        }

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            print("server error received")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
            return
        }
        if response.mimeType == "application/json" {
            print("json data parsed")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
        }else {
            print("unknown data")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
        }
    })

    //start execution after two seconds
    Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
        print("resume called")
        task.resume()
    }
}

var urls = [URL]()
for _ in 0..<100 {
    if let url = URL(string: "https://google.com") {
        urls.append(url)
    }
}

fetch(urls:urls)
</code>```

Body:
Basically I have some JSON data that I wish to retrieve from a bunch of URL's (all from the same host), however I can only request this data roughly every 2 seconds at minimum and only one at a time or I'll be "time banned" from the server. As you'll see below; while URLSession is very quick it also gets me time banned almost instantly when I have around 700 urls to get through.

How would I go about creating a queue in URLSession (if its functionality supports it) and while having it work asynchronously to my main thread; have it work serially on its own thread and only attempt each item in the queue after 2 seconds have past since it finished the previous request?

for url in urls {
    get(url: url)
}

func get(url: URL) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            DispatchQueue.main.async {
                print(error.localizedDescription)
            }
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            DispatchQueue.main.async {
                print("Server Error")
            }
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {
                        DispatchQueue.main.async {
                            self.itemsCount.append(count)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}

Body:
Recursion solves this best

import Foundation
import PlaygroundSupport

// Let asynchronous code run
PlaygroundPage.current.needsIndefiniteExecution = true

func fetch(urls: [URL]) {

    guard urls.count > 0 else {
        print("Queue finished")
        return
    }

    var pendingURLs = urls
    let currentUrl = pendingURLs.removeFirst()

    print("\(pendingURLs.count)")

    let session = URLSession.shared
    let task = session.dataTask(with: currentUrl, completionHandler: { (data, response, error) in
        print("task completed")
        if let _ = error {
            print("error received")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
            return
        }

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            print("server error received")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
            return
        }
        if response.mimeType == "application/json" {
            print("json data parsed")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
        }else {
            print("unknown data")
            DispatchQueue.main.async {
                fetch(urls: pendingURLs)
            }
        }
    })

    //start execution after two seconds
    Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
        print("resume called")
        task.resume()
    }
}

var urls = [URL]()
for _ in 0..<100 {
    if let url = URL(string: "https://google.com") {
        urls.append(url)
    }
}

fetch(urls:urls)


问:
How to execute Python code from within Visual Studio Code
Visual Studio Code was recently released and I liked the look of it and the features it offered, so I figured I would give it a go.

I downloaded the application from the downloads page, fired it up, messed around a bit with some of the features ... and then realized I had no idea how to actually execute any of my Python code!

I really like the look and feel/usability/features of Visual Studio Code, but I can't seem to find out how to run my Python code, a real killer because that's what I program primarily in.

Is there is a way to execute Python code in Visual Studio Code?

答: As stated in Visual Studio Code documentation, just right-click anywhere in the editor and select Run Python File in Terminal.


问:
Error when decoding base 64 to blob
I am using the following function to convert a large base64 encoded file(image or voice) into a blob file and store it in the Oracle database (Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production).

I am able to store it and retrieve it but the image is getting corrupted. Only a potion of the image is getting retrieved. I tried using small images(11KB size) and it is working fine. But for larger images(88KB to 700KB) only a portion of the image is retrieved.

The problem is with the base-64 decoding. Earlier I was not able to get even the smaller image due to corruption, but when I increased the buffer size, it came fine. Now the buffer size is at its maximum at 32767 as its the maximum for varchar2 and raw.

Can anyone provide a suitable workaround or solution.

```<code>function decode_base64(p_clob_in in clob) return blob is
    v_blob blob;
    v_result blob;
    v_offset integer;
    v_buffer_size binary_integer := 32767;     -- 24, 48, 3072
    v_buffer_varchar varchar2(32767);
    v_buffer_raw raw(32767);

  begin

    if p_clob_in is null then
      return null;
    end if;

    dbms_lob.createtemporary(v_blob, true);
    v_offset := 1;

    for i in 1 .. ceil(dbms_lob.getlength(p_clob_in) / v_buffer_size)
    loop
      dbms_lob.read(p_clob_in, v_buffer_size, v_offset, v_buffer_varchar);
      v_buffer_raw := utl_raw.cast_to_raw(v_buffer_varchar);
      v_buffer_raw := utl_encode.base64_decode(v_buffer_raw);
      dbms_lob.writeappend(v_blob, utl_raw.length(v_buffer_raw), v_buffer_raw);
      v_offset := v_offset + v_buffer_size;
    end loop;

    v_result := v_blob;
    dbms_lob.freetemporary(v_blob);

    return v_result;

  end decode_base64;
</code>```

The code that i use to call the function and insert the blob into the table is given below...

```<code> PROCEDURE create_notes (
      p_task_id              IN       NUMBER
     ,p_note_title           IN       VARCHAR2
     ,p_note_detail          IN       VARCHAR2
     ,p_attach_name          IN       VARCHAR2
     ,p_attachment           IN       CLOB
     ,p_attach_type          IN       VARCHAR2
     ,x_return_code          OUT      VARCHAR2
     ,x_return_message       OUT      VARCHAR2
   )
IS
  l_blob_data BLOB;
BEGIN
.
.
.
 IF p_attachment IS NOT NULL THEN

            SELECT incident_id INTO l_pk1_value FROM csf_ct_tasks where task_id = p_task_id;

                        l_blob_data :=  xx_utl_base64.decode_base64(p_attachment);
INSERT INTO fnd_lobs
                        (file_id, file_name, file_content_type, upload_date,
                        expiration_date, program_name, program_tag, file_data,
                        LANGUAGE, oracle_charset, file_format
                        )
                        VALUES (l_media_id, p_attach_name,p_attach_type,  -- 'audio/mpeg','application/pdf','image/jpeg'
                        SYSDATE,
                        NULL, 'FNDATTCH', NULL, l_blob_data,               --l_blob_data,EMPTY_BLOB ()
                        'US', 'UTF8', 'binary'
                        )
                        RETURNING file_data
                        INTO x_blob;
COMMIT;
END IF:
</code>```

Attaching the original picture and its decoded version, below.

答:
For those who's still looking for a correct solution - you need to decode input data in multiples of 4. In case input contains non-base64 symbols (which are ignored by built-in function utl_encode.base64_decode), it might lead to incorrect results on large files.

I've found a lot of samples on the web which do not correctly decode, posting my code below

```

    FUNCTION base64_decode(p_content CLOB) RETURN BLOB
    IS
        C_CHUNK_SIZE CONSTANT INTEGER := 12000; -- should be a multiple of 4
        C_NON_BASE64_SYM_PATTERN CONSTANT VARCHAR2(20) := '[^A-Za-z0-9+/]';
        l_chunk_buf VARCHAR2(12000);
        l_chunk_b64_buf RAW(9000);
        l_chunk_offset INTEGER := 1;
        l_chunk_size INTEGER;
        l_res BLOB;

        FUNCTION get_next_full_base64_chunk(l_data CLOB, p_cur_pos IN OUT INTEGER, p_desired_size INTEGER, p_cur_size IN OUT INTEGER) RETURN VARCHAR2 IS
            l_res VARCHAR2(12000);
            l_tail_desired_size INTEGER;
        BEGIN
            l_res := dbms_lob.substr(l_data, p_desired_size, p_cur_pos);
            p_cur_pos := p_cur_pos + p_desired_size;
            IF l_res IS NULL THEN
                RETURN NULL;
            END IF;

            l_res := regexp_replace(l_res, C_NON_BASE64_SYM_PATTERN, '');
            p_cur_size := p_cur_size + length(l_res);

            l_tail_desired_size := 4 - mod(p_cur_size, 4);
            IF l_tail_desired_size = 4 THEN
                RETURN l_res;
            ELSE
                RETURN l_res || get_next_full_base64_chunk(l_data, p_cur_pos, l_tail_desired_size, p_cur_size);
            END IF;
        END;

    BEGIN
        dbms_lob.createtemporary(l_res, false);

        WHILE true
        LOOP
            l_chunk_size := 0;
            l_chunk_buf := get_next_full_base64_chunk(p_content, l_chunk_offset, C_CHUNK_SIZE, l_chunk_size);
            EXIT WHEN l_chunk_buf IS NULL;
            l_chunk_b64_buf := utl_encode.base64_decode(utl_raw.cast_to_raw(l_chunk_buf));
            dbms_lob.writeappend(l_res, utl_raw.length(l_chunk_b64_buf), l_chunk_b64_buf);
        END LOOP;

        RETURN l_res;
    END;

```

Title: Error when decoding base 64 to blob

Body:
I am using the following function to convert a large base64 encoded file(image or voice) into a blob file and store it in the Oracle database (Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production).

I am able to store it and retrieve it but the image is getting corrupted. Only a potion of the image is getting retrieved. I tried using small images(11KB size) and it is working fine. But for larger images(88KB to 700KB) only a portion of the image is retrieved.

The problem is with the base-64 decoding. Earlier I was not able to get even the smaller image due to corruption, but when I increased the buffer size, it came fine. Now the buffer size is at its maximum at 32767 as its the maximum for varchar2 and raw.

Can anyone provide a suitable workaround or solution.

function decode_base64(p_clob_in in clob) return blob is
    v_blob blob;
    v_result blob;
    v_offset integer;
    v_buffer_size binary_integer := 32767;     -- 24, 48, 3072
    v_buffer_varchar varchar2(32767);
    v_buffer_raw raw(32767);

  begin

    if p_clob_in is null then
      return null;
    end if;

    dbms_lob.createtemporary(v_blob, true);
    v_offset := 1;

    for i in 1 .. ceil(dbms_lob.getlength(p_clob_in) / v_buffer_size)
    loop
      dbms_lob.read(p_clob_in, v_buffer_size, v_offset, v_buffer_varchar);
      v_buffer_raw := utl_raw.cast_to_raw(v_buffer_varchar);
      v_buffer_raw := utl_encode.base64_decode(v_buffer_raw);
      dbms_lob.writeappend(v_blob, utl_raw.length(v_buffer_raw), v_buffer_raw);
      v_offset := v_offset + v_buffer_size;
    end loop;

    v_result := v_blob;
    dbms_lob.freetemporary(v_blob);

    return v_result;

  end decode_base64;

The code that i use to call the function and insert the blob into the table is given below...

 PROCEDURE create_notes (
      p_task_id              IN       NUMBER
     ,p_note_title           IN       VARCHAR2
     ,p_note_detail          IN       VARCHAR2
     ,p_attach_name          IN       VARCHAR2
     ,p_attachment           IN       CLOB
     ,p_attach_type          IN       VARCHAR2
     ,x_return_code          OUT      VARCHAR2
     ,x_return_message       OUT      VARCHAR2
   )
IS
  l_blob_data BLOB;
BEGIN
.
.
.
 IF p_attachment IS NOT NULL THEN

            SELECT incident_id INTO l_pk1_value FROM csf_ct_tasks where task_id = p_task_id;

                        l_blob_data :=  xx_utl_base64.decode_base64(p_attachment);
INSERT INTO fnd_lobs
                        (file_id, file_name, file_content_type, upload_date,
                        expiration_date, program_name, program_tag, file_data,
                        LANGUAGE, oracle_charset, file_format
                        )
                        VALUES (l_media_id, p_attach_name,p_attach_type,  -- 'audio/mpeg','application/pdf','image/jpeg'
                        SYSDATE,
                        NULL, 'FNDATTCH', NULL, l_blob_data,               --l_blob_data,EMPTY_BLOB ()
                        'US', 'UTF8', 'binary'
                        )
                        RETURNING file_data
                        INTO x_blob;
COMMIT;
END IF:

Attaching the original picture and its decoded version, below.

Body:
For those who's still looking for a correct solution - you need to decode input data in multiples of 4. In case input contains non-base64 symbols (which are ignored by built-in function utl_encode.base64_decode), it might lead to incorrect results on large files.

I've found a lot of samples on the web which do not correctly decode, posting my code below

    FUNCTION base64_decode(p_content CLOB) RETURN BLOB
    IS
        C_CHUNK_SIZE CONSTANT INTEGER := 12000; -- should be a multiple of 4
        C_NON_BASE64_SYM_PATTERN CONSTANT VARCHAR2(20) := '[^A-Za-z0-9+/]';
        l_chunk_buf VARCHAR2(12000);
        l_chunk_b64_buf RAW(9000);
        l_chunk_offset INTEGER := 1;
        l_chunk_size INTEGER;
        l_res BLOB;

        FUNCTION get_next_full_base64_chunk(l_data CLOB, p_cur_pos IN OUT INTEGER, p_desired_size INTEGER, p_cur_size IN OUT INTEGER) RETURN VARCHAR2 IS
            l_res VARCHAR2(12000);
            l_tail_desired_size INTEGER;
        BEGIN
            l_res := dbms_lob.substr(l_data, p_desired_size, p_cur_pos);
            p_cur_pos := p_cur_pos + p_desired_size;
            IF l_res IS NULL THEN
                RETURN NULL;
            END IF;

            l_res := regexp_replace(l_res, C_NON_BASE64_SYM_PATTERN, '');
            p_cur_size := p_cur_size + length(l_res);

            l_tail_desired_size := 4 - mod(p_cur_size, 4);
            IF l_tail_desired_size = 4 THEN
                RETURN l_res;
            ELSE
                RETURN l_res || get_next_full_base64_chunk(l_data, p_cur_pos, l_tail_desired_size, p_cur_size);
            END IF;
        END;

    BEGIN
        dbms_lob.createtemporary(l_res, false);

        WHILE true
        LOOP
            l_chunk_size := 0;
            l_chunk_buf := get_next_full_base64_chunk(p_content, l_chunk_offset, C_CHUNK_SIZE, l_chunk_size);
            EXIT WHEN l_chunk_buf IS NULL;
            l_chunk_b64_buf := utl_encode.base64_decode(utl_raw.cast_to_raw(l_chunk_buf));
            dbms_lob.writeappend(l_res, utl_raw.length(l_chunk_b64_buf), l_chunk_b64_buf);
        END LOOP;

        RETURN l_res;
    END;


问:
How do I make this Prolog query work in a predicate?

I am trying to make this Prolog query:

```<code>placeRedBlocks(4, X), findall(Y, loopReplace(X, Y), A).
</code>```

which outputs this:

```<code>A = [[r, r, r, b], [r, r, r, r], [b, r, r, r]],
X = [b, b, b, b]
</code>```

work in the code if I only type in

```<code>placeRedBlocks(4, X).
</code>```

The code I am using:

```<code>printList([ ]).
printList([H|T]) :- print(H), nl, printList(T).

placeRedBlocks(Length, List) :-
  findall('b', between(1, Length, _), List).

replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):-
  I > -1,
  NI is I-1,
%  write([H|T]),
  replace(T, NI, X, R), !.
%  replace(L, _, _, L).

placeRedBlockUnit(A,_,0,_,A):- !.
placeRedBlockUnit(Line,Index,NumElm,Elm,NLine) :-
  replace(Line,Index,Elm,BLine),
  Index1 is Index+1,
  NumElm1 is NumElm-1,
  placeRedBlockUnit(BLine,Index1,NumElm1,Elm,NLine).

loopReplace(ListToReplace, NewList) :-
    length(ListToReplace, Len),
    TotalCount is Len-3,
    between(0, TotalCount, Iterations),
    between(3, Len, Size),
    placeRedBlockUnit(ListToReplace, Iterations, Size, 'r', NewList).
</code>```

Unfortunately, if I change placeRedBlocks to this it doesn't work.

```<code>placeRedBlocks(Length, List) :-
  findall('b', between(1, Length, _), List),
  findall(Y, loopReplace(List, Y), _).
</code>```

and I only get:

```<code>X = [b, b, b, b]
</code>```

What is happening here?
Is it possible for it to return back to the same list?

答:
I realized that as long as I use a variable twice in a predicate I don't need to make it a parameter to my predicate.

Changing this

```<code>placeRedBlocks(Length, List) :-
  findall('b', between(1, Length, _), List)
</code>```

to this

```<code>placeRedBlocks(Length, List3) :-
  findall('b', between(1, Length, _), List),
  findall(Y, loopReplace(List, Y), List2),
  append([List], List2, List3).
</code>```

made me able to use the queries in the predicate while also keeping the predicate at 2 parameters.

Body:
I am trying to make this Prolog query:

placeRedBlocks(4, X), findall(Y, loopReplace(X, Y), A).

which outputs this:

A = [[r, r, r, b], [r, r, r, r], [b, r, r, r]],
X = [b, b, b, b]

work in the code if I only type in

placeRedBlocks(4, X).

The code I am using:

printList([ ]).
printList([H|T]) :- print(H), nl, printList(T).

placeRedBlocks(Length, List) :-
  findall('b', between(1, Length, _), List).

replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):-
  I > -1,
  NI is I-1,
%  write([H|T]),
  replace(T, NI, X, R), !.
%  replace(L, _, _, L).

placeRedBlockUnit(A,_,0,_,A):- !.
placeRedBlockUnit(Line,Index,NumElm,Elm,NLine) :-
  replace(Line,Index,Elm,BLine),
  Index1 is Index+1,
  NumElm1 is NumElm-1,
  placeRedBlockUnit(BLine,Index1,NumElm1,Elm,NLine).

loopReplace(ListToReplace, NewList) :-
    length(ListToReplace, Len),
    TotalCount is Len-3,
    between(0, TotalCount, Iterations),
    between(3, Len, Size),
    placeRedBlockUnit(ListToReplace, Iterations, Size, 'r', NewList).

Unfortunately, if I change placeRedBlocks to this it doesn't work.

placeRedBlocks(Length, List) :-
  findall('b', between(1, Length, _), List),
  findall(Y, loopReplace(List, Y), _).

and I only get:

X = [b, b, b, b]

What is happening here?
Is it possible for it to return back to the same list?

Body:
I realized that as long as I use a variable twice in a predicate I don't need to make it a parameter to my predicate.

Changing this

placeRedBlocks(Length, List) :-
  findall('b', between(1, Length, _), List)

to this

placeRedBlocks(Length, List3) :-
  findall('b', between(1, Length, _), List),
  findall(Y, loopReplace(List, Y), List2),
  append([List], List2, List3).

made me able to use the queries in the predicate while also keeping the predicate at 2 parameters.


问:
MQ header - Identifier context - ApplIdentityData
We want to extract information from ApplIdentityData on MQ Header. But on the consumer side, we dont see corresponding JMS header for ApplIdentityData. I did trace on the logs and i dont find any information related to ApplIdentityData.

I am using Apache Camel to read the MQ and process the Queue Message. In the camel trace logs, i dont find anything to ApplIdentityData. Could you please help me ?

Below is the MQ Message Header and Camel File :

```<code>    StrucId  : 'MD  '  Version : 2
    Report   : 0  MsgType : 8
    Expiry   : -1  Feedback : 0
    Encoding : 273  CodedCharSetId : 819
    Format : 'MQSTR   '
    Priority : 0  Persistence : 1
    MsgId : X'414D51204445544C4437513120202020594010C12E08AD2B'
    CorrelId : X'000000000000000000000000000000000000000000000000'
    BackoutCount : 0
    ReplyToQ       : '                                                '
    ReplyToQMgr    : 'etlQ07                                        '
    ** Identity Context
    UserIdentifier : '            '
    AccountingToken :
    X'0000000000000000000000000000000000000000000000000000000000000000'
    ApplIdentityData : 'TEST_HEADER_BADRI_DEC5'
    ** Origin Context
    PutApplType    : '6'
                '
    PutDate  : '20171205'    PutTime  : '08285663'
    ApplOriginData : '    '

    GroupId : X'414D51204445544C4437513120202020594010C12E08AD2C'
    MsgSeqNumber   : '1'
    Offset         : '0'
    MsgFlags       : '1'
    OriginalLength : '-1'
</code>```

Camel File:

```<code>            <!-- Recs Prem Cash MQ Configuration START -->
        <camel:route id="rp-cash-mq-route">
                                <camel:setHeader headerName="CamelCharsetName"><camel:constant>UTF-8</camel:constant></camel:setHeader>
                            <camel:setHeader headerName="endpoint.error.folder"><camel:constant>file:///usr/local/clo/data/tlm/fuse/archive/failed</camel:constant></camel:setHeader>
                <camel:setHeader headerName="route.accessAreaId"><camel:simple resultType="Long">1</camel:simple></camel:setHeader>
                <camel:setHeader headerName="mi-endpoint"><camel:constant>st-csv-in</camel:constant></camel:setHeader>
                                <camel:setHeader headerName="CamelFileName"><camel:simple>${header.JMS_IBM_MQMD_ApplIdentityData}</camel:simple></camel:setHeader>
            <camel:to uri="direct:st-csv-in"/>
        </camel:route>
        <!-- Recs Prem Cash MQ Configuration END -->
</code>```

答:
Take a look at these two Knowledge Center pages which will tell you how to do it:

https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.0.0/com.ibm.mq.dev.doc/q032330_.htm

https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.0.0/com.ibm.mq.dev.doc/q032350_.htm

Essentially you have to configure the JMS Destination with the property "WMQ_MQMD_READ_ENABLED" set to true before receiving the message.  You can then query the property, "JMS_IBM_MQMD_ApplIdentityData" on the received message.

Body:
We want to extract information from ApplIdentityData on MQ Header. But on the consumer side, we dont see corresponding JMS header for ApplIdentityData. I did trace on the logs and i dont find any information related to ApplIdentityData.

I am using Apache Camel to read the MQ and process the Queue Message. In the camel trace logs, i dont find anything to ApplIdentityData. Could you please help me ?

Below is the MQ Message Header and Camel File :

    StrucId  : 'MD  '  Version : 2
    Report   : 0  MsgType : 8
    Expiry   : -1  Feedback : 0
    Encoding : 273  CodedCharSetId : 819
    Format : 'MQSTR   '
    Priority : 0  Persistence : 1
    MsgId : X'414D51204445544C4437513120202020594010C12E08AD2B'
    CorrelId : X'000000000000000000000000000000000000000000000000'
    BackoutCount : 0
    ReplyToQ       : '                                                '
    ReplyToQMgr    : 'etlQ07                                        '
    ** Identity Context
    UserIdentifier : '            '
    AccountingToken :
    X'0000000000000000000000000000000000000000000000000000000000000000'
    ApplIdentityData : 'TEST_HEADER_BADRI_DEC5'
    ** Origin Context
    PutApplType    : '6'
                '
    PutDate  : '20171205'    PutTime  : '08285663'
    ApplOriginData : '    '

    GroupId : X'414D51204445544C4437513120202020594010C12E08AD2C'
    MsgSeqNumber   : '1'
    Offset         : '0'
    MsgFlags       : '1'
    OriginalLength : '-1'

Camel File:

        <camel:route id="rp-cash-mq-route">
                                <camel:setHeader headerName="CamelCharsetName"><camel:constant>UTF-8</camel:constant></camel:setHeader>
                            <camel:setHeader headerName="endpoint.error.folder"><camel:constant>file:///usr/local/clo/data/tlm/fuse/archive/failed</camel:constant></camel:setHeader>
                <camel:setHeader headerName="route.accessAreaId"><camel:simple resultType="Long">1</camel:simple></camel:setHeader>
                <camel:setHeader headerName="mi-endpoint"><camel:constant>st-csv-in</camel:constant></camel:setHeader>
                                <camel:setHeader headerName="CamelFileName"><camel:simple>${header.JMS_IBM_MQMD_ApplIdentityData}</camel:simple></camel:setHeader>
            <camel:to uri="direct:st-csv-in"/>
        </camel:route>


问:
filter object_list in django template
I create a template with object_list table
I need filter by sub string then when the user will filter the table will updates online.

its not work. what the right way to do this?

I create view for this filter get the ajax request with substring value

def filters_points(request):

```<code>point_list = Point.objects.all()

try:

    req = request.GET.get("filterData")
    if req:
        point_list = Point.objects.filter(onsitePointName__icontains=req)

except AttributeError:
    print("failed")

#qs_json = serializers.serialize('json', point_list)
#return HttpResponse(qs_json, content_type='application/json')

return render_to_response('point/point_list_update.html', {'point_list': point_list})
</code>```

in HTML templete:

{% for point in point_list   %}
...
 {{ point.mangoId }}
 {{ point.onsitePointName }}
....

答:
built the input type for filter in django form:
 filterBySubstring = forms.CharField(label='substring', max_length=100, required=True)

and then get this value in the python code by:
form = PointForm(request.POST)

```<code>if request.method == 'POST':
    filter_value = form['filterBySubstring'].value()
</code>```

Title: filter object_list in django template

Body:
I create a template with object_list table
I need filter by sub string then when the user will filter the table will updates online.

its not work. what the right way to do this?

I create view for this filter get the ajax request with substring value

def filters_points(request):

point_list = Point.objects.all()

try:

    req = request.GET.get("filterData")
    if req:
        point_list = Point.objects.filter(onsitePointName__icontains=req)

except AttributeError:
    print("failed")

#qs_json = serializers.serialize('json', point_list)
#return HttpResponse(qs_json, content_type='application/json')

return render_to_response('point/point_list_update.html', {'point_list': point_list})

in HTML templete:

{% for point in point_list   %}
...
 {{ point.mangoId }}
 {{ point.onsitePointName }}
....

Body:
built the input type for filter in django form:
 filterBySubstring = forms.CharField(label='substring', max_length=100, required=True)

and then get this value in the python code by:
form = PointForm(request.POST)

if request.method == 'POST':
    filter_value = form['filterBySubstring'].value()


问:
Select values that meet different conditions on different rows?
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

```<code>userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1
</code>```

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

答:
Ok, I got downvoted on this so I decided to test it:

```<code>CREATE TABLE userrole (
  userid INT,
  roleid INT,
  PRIMARY KEY (userid, roleid)
);

CREATE INDEX ON userrole (roleid);
</code>```

Run this:

```<code><?php
ini_set('max_execution_time', 120); // takes over a minute to insert 500k+ records

$start = microtime(true);

echo "```\n";
mysql_connect('localhost', 'scratch', 'scratch');
if (mysql_error()) {
    echo "Connect error: " . mysql_error() . "\n";
}
mysql_select_db('scratch');
if (mysql_error()) {
    echo "Selct DB error: " . mysql_error() . "\n";
}

$users = 200000;
$count = 0;
for ($i=1; $i<=$users; $i++) {
    $roles = rand(1, 4);
    $available = range(1, 5);
    for ($j=0; $j<$roles; $j++) {
        $extract = array_splice($available, rand(0, sizeof($available)-1), 1);
        $id = $extract[0];
        query("INSERT INTO userrole (userid, roleid) VALUES ($i, $id)");
        $count++;
    }
}

$stop = microtime(true);
$duration = $stop - $start;
$insert = $duration / $count;

echo "$count users added.\n";
echo "Program ran for $duration seconds.\n";
echo "Insert time $insert seconds.\n";
echo "```\n";

function query($str) {
    mysql_query($str);
    if (mysql_error()) {
        echo "$str: " . mysql_error() . "\n";
    }
}
?>
</code>```

Output:

```<code>499872 users added.
Program ran for 56.5513510704 seconds.
Insert time 0.000113131663847 seconds.
</code>```

That adds 500,000 random user-role combinations and there are approximately 25,000 that match the chosen criteria.

First query:

```<code>SELECT userid
FROM userrole
WHERE roleid IN (1, 2, 3)
GROUP by userid
HAVING COUNT(1) = 3
</code>```

Query time: 0.312s

```<code>SELECT t1.userid
FROM userrole t1
JOIN userrole t2 ON t1.userid = t2.userid AND t2.roleid = 2
JOIN userrole t3 ON t2.userid = t3.userid AND t3.roleid = 3
AND t1.roleid = 1
</code>```

Query time: 0.016s

That's right.  The join version I proposed is twenty times faster than the aggregate version.

Sorry but I do this for a living and work in the real world and in the real world we test SQL and the results speak for themselves.

The reason for this should be pretty clear.  The aggregate query will scale in cost with the size of the table.  Every row is processed, aggregated and filtered (or not) through the HAVING clause.  The join version will (using an index) select a subset of the users based on a given role, then check that subset against the second role and finally that subset against the third role.  Each selection (in relational algebra terms) works on an increasingly small subset.  From this you can conclude:

The performance of the join version gets even better with a lower incidence of matches.

If there were only 500 users (out of the 500k sample above) that had the three stated roles, the join version will get significantly faster.  The aggregate version will not (and any performance improvement is a result of transporting 500 users instead of 25k, which the join version obviously gets too).

I was also curious to see how a real database (ie Oracle) would deal with this.  So I basically repeated the same exercise on Oracle XE (running on the same Windows XP desktop machine as the MySQL from the previous example) and the results are almost identical.

Joins seem to be frowned upon but as I've demonstrated, aggregate queries can be an order of magnitude slower.

Update: After some extensive testing, the picture is more complicated and the answer will depend on your data, your database and other factors. The moral of the story is test, test, test.

OwnerDisplayName: John

Body:
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

LastEditorDisplayName: John

Body:
Ok, I got downvoted on this so I decided to test it:

CREATE TABLE userrole (
  userid INT,
  roleid INT,
  PRIMARY KEY (userid, roleid)
);

CREATE INDEX ON userrole (roleid);

Run this:

<?php
ini_set('max_execution_time', 120); // takes over a minute to insert 500k+ records

$start = microtime(true);

echo "<pre>\n";
mysql_connect('localhost', 'scratch', 'scratch');
if (mysql_error()) {
    echo "Connect error: " . mysql_error() . "\n";
}
mysql_select_db('scratch');
if (mysql_error()) {
    echo "Selct DB error: " . mysql_error() . "\n";
}

$users = 200000;
$count = 0;
for ($i=1; $i<=$users; $i++) {
    $roles = rand(1, 4);
    $available = range(1, 5);
    for ($j=0; $j<$roles; $j++) {
        $extract = array_splice($available, rand(0, sizeof($available)-1), 1);
        $id = $extract[0];
        query("INSERT INTO userrole (userid, roleid) VALUES ($i, $id)");
        $count++;
    }
}

$stop = microtime(true);
$duration = $stop - $start;
$insert = $duration / $count;

echo "$count users added.\n";
echo "Program ran for $duration seconds.\n";
echo "Insert time $insert seconds.\n";
echo "</pre>\n";

function query($str) {
    mysql_query($str);
    if (mysql_error()) {
        echo "$str: " . mysql_error() . "\n";
    }
}
?>

Output:

499872 users added.
Program ran for 56.5513510704 seconds.
Insert time 0.000113131663847 seconds.

That adds 500,000 random user-role combinations and there are approximately 25,000 that match the chosen criteria.

First query:

SELECT userid
FROM userrole
WHERE roleid IN (1, 2, 3)
GROUP by userid
HAVING COUNT(1) = 3

Query time: 0.312s

SELECT t1.userid
FROM userrole t1
JOIN userrole t2 ON t1.userid = t2.userid AND t2.roleid = 2
JOIN userrole t3 ON t2.userid = t3.userid AND t3.roleid = 3
AND t1.roleid = 1

Query time: 0.016s

That's right.  The join version I proposed is twenty times faster than the aggregate version.

Sorry but I do this for a living and work in the real world and in the real world we test SQL and the results speak for themselves.

The reason for this should be pretty clear.  The aggregate query will scale in cost with the size of the table.  Every row is processed, aggregated and filtered (or not) through the HAVING clause.  The join version will (using an index) select a subset of the users based on a given role, then check that subset against the second role and finally that subset against the third role.  Each selection (in relational algebra terms) works on an increasingly small subset.  From this you can conclude:

The performance of the join version gets even better with a lower incidence of matches.

If there were only 500 users (out of the 500k sample above) that had the three stated roles, the join version will get significantly faster.  The aggregate version will not (and any performance improvement is a result of transporting 500 users instead of 25k, which the join version obviously gets too).

I was also curious to see how a real database (ie Oracle) would deal with this.  So I basically repeated the same exercise on Oracle XE (running on the same Windows XP desktop machine as the MySQL from the previous example) and the results are almost identical.

Joins seem to be frowned upon but as I've demonstrated, aggregate queries can be an order of magnitude slower.

Update: After some extensive testing, the picture is more complicated and the answer will depend on your data, your database and other factors. The moral of the story is test, test, test.

OwnerDisplayName: cletus

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: cletus


问:
Accessing a common data object in a PyQt application
I have a GUI programmed in PyQt with many widgets and different windows, etc. The data for the GUI is stored in a python object. This object should be reachable from every widget in the program. Where should I put this object?

Right now I have it in the QMainWindow instance that is used for the program's main window. The problem is that it is hard to reach the QMainWindow object from deeply nested widgets. It seems much simpler to use the QApplication instance for that, because you can get it with QtCore.QCoreApplication.instance() (as shown in this answer). However, I couldn't find any other examples encouraging you to change the QApplication class, so I wonder if it really should be used that way.

What approach would you suggest?

答:
The correct approach is to put this data/settings object in a separate module. This can then be simply imported wherever it is needed. Ideally, the module (and the code which creates the data/settings object) should be largely independent from the rest of the application.

There is no real value in tying the data/settings object to the application instance, since you would still have to import either QApplication or qApp to access it anyway. And the same thing applies to the QMainWindow - it just moves the problem to a different location, and adds an unnecessary layer of indirection. Another big problem with this approach is that the data/settings object cannot be accessed until an instance of the  application or main window becomes available. Very often, the data/settings object will be required during the initialisation of various parts of the application, so tying it to specific GUI elements can easily lead to circular dependencies, or other ordering problems.

I suppose the key design principle here is Loose Coupling: once you've decoupled your data/settings object from the GUI, the rest of the application can access it wherever and whenever it is required.


问:
Spark SQL Generating Wrong Upper and Lower Bounds for JDBC Queries
So i am currently working on a POC With Spark-SQL Where i need to parallelize the read operation using a spark-sql query in spark

```<code> JavaRDD<Row> dataset = sqlContext.read().jdbc(jdBcConnectionString, getSqlQuery(), "tran_id"
                lowerbound, upperbound, partitions, props).toJavaRDD();
</code>```

Every seems well and works fine untill you inspect the queries generated (Which in my own case is MS Sql Server).

The lower bound query is

```<code>exec sp_executesql N'SELECT * FROM table_name WHERE tran_id < 770425 or post_tran_id is null'
</code>```

while the upperbound query becomes

```<code>exec sp_executesql N'SELECT * FROM table_name WHERE tran_id >= 770425'
</code>```

One would think that the essence of specifying bounds is to get all rows where column value is between the specified lowerbound and upperbound. but this appears not to be the case

Please I am new to spark, is there another way to achieve this

答:
One would think that the essence of specifying bounds is to get all rows where column value is between the specified lowerbound and upperbound.

It is not and conditions are correct. As usual it is better to read the documentation than assume:

Notice that lowerBound and upperBound are just used to decide the partition stride, not for filtering the rows in table. So all rows in the table will be partitioned and returned. This option applies only to reading.

But it looks like lowerBound is equal to upperBound in your case.

Please I am new to spark, is there another way to achieve this

If you want filter then apply where:

```<code>dataset.where(col("tran_id").between(lowerBound, upperBound))
</code>```

or use subquery as table argument:

```<code>sqlContext.read().jdbc(
  jdBcConnectionString,
  "(SELECT * FROM table_name WHERE tran_id BETWEEN 0 AND 42) AS t", props);
</code>```

Body:
So i am currently working on a POC With Spark-SQL Where i need to parallelize the read operation using a spark-sql query in spark

 JavaRDD<Row> dataset = sqlContext.read().jdbc(jdBcConnectionString, getSqlQuery(), "tran_id"
                lowerbound, upperbound, partitions, props).toJavaRDD();

Every seems well and works fine untill you inspect the queries generated (Which in my own case is MS Sql Server).

The lower bound query is

exec sp_executesql N'SELECT * FROM table_name WHERE tran_id < 770425 or post_tran_id is null'

while the upperbound query becomes

exec sp_executesql N'SELECT * FROM table_name WHERE tran_id >= 770425'

One would think that the essence of specifying bounds is to get all rows where column value is between the specified lowerbound and upperbound. but this appears not to be the case

Please I am new to spark, is there another way to achieve this

Body:
One would think that the essence of specifying bounds is to get all rows where column value is between the specified lowerbound and upperbound.

It is not and conditions are correct. As usual it is better to read the documentation than assume:

Notice that lowerBound and upperBound are just used to decide the partition stride, not for filtering the rows in table. So all rows in the table will be partitioned and returned. This option applies only to reading.

But it looks like lowerBound is equal to upperBound in your case.

Please I am new to spark, is there another way to achieve this

If you want filter then apply where:

dataset.where(col("tran_id").between(lowerBound, upperBound))

or use subquery as table argument:

sqlContext.read().jdbc(
  jdBcConnectionString,
  "(SELECT * FROM table_name WHERE tran_id BETWEEN 0 AND 42) AS t", props);


问:
Angular(5) - lazy loading and canActivate guard - StaticInjectorError
So, we have quite a big app and we started working on optimizations.... one of the optimizations were lazy loading some parts....

so we have Demo pages with whole load of example usage that we DON'T want anywhere but on out DEV environment...

so lazy loading that part was quite easy...

in our app-routing module we have

```<code>const routes: Routes = [
    ...
    {path: 'design', canActivate: ['DevOnlyGuard'], loadChildren: 'app/pages/demo/demo.module#DemoPagesModule'},
    ...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

So without canActivate route all works fine and demo routes are loaded lazily...

now, if I add this canActivate in my guard, that looks like this

```<code>import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';
import { environment } from 'environments/environment';

@Injectable()
export class DevOnlyGuard implements  CanActivate, CanActivateChild {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return (environment.envName === 'dev');
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }
}
</code>```

I am getting this error once I hit the demo route:

ERROR Error: Uncaught (in promise): Error:
  StaticInjectorError[DevOnlyGuard]:

  StaticInjectorError[DevOnlyGuard]:
      NullInjectorError: No provider for DevOnlyGuard! Error: StaticInjectorError[DevOnlyGuard]:  ....

even if I added the Guard to the list of providers in my app.module
like

```<code>providers: [
    ...
    DevOnlyGuard,
];
</code>```

Any ideas?

答:
remove single quotes from canActivate: ['DevOnlyGuard']

Below is how should we use canActivate:

Method 1:

```<code>  @Injectable()
    class CanActivateTeam implements CanActivate {
      constructor(private permissions: Permissions, private currentUser: UserToken) {}

      canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<boolean>|Promise<boolean>|boolean {
        return this.permissions.canActivate(this.currentUser, route.params.id);
      }
    }

    @NgModule({
      imports: [
        RouterModule.forRoot([
          {
            path: 'team/:id',
            component: TeamCmp,
            canActivate: [CanActivateTeam]
          }
        ])
      ],
      providers: [CanActivateTeam, UserToken, Permissions]
    })
    class AppModule {}
</code>```

Method 2(with Single Quote...):

```<code>@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        canActivate: ['canActivateTeam']
      }
    ])
  ],
  providers: [
    {
      provide: 'canActivateTeam',
      useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true
    }
  ]
})
class AppModule {}
</code>```

Body:
So, we have quite a big app and we started working on optimizations.... one of the optimizations were lazy loading some parts....

so we have Demo pages with whole load of example usage that we DON'T want anywhere but on out DEV environment...

so lazy loading that part was quite easy...

in our app-routing module we have

const routes: Routes = [
    ...
    {path: 'design', canActivate: ['DevOnlyGuard'], loadChildren: 'app/pages/demo/demo.module#DemoPagesModule'},
    ...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

So without canActivate route all works fine and demo routes are loaded lazily...

now, if I add this canActivate in my guard, that looks like this

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';
import { environment } from 'environments/environment';

@Injectable()
export class DevOnlyGuard implements  CanActivate, CanActivateChild {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return (environment.envName === 'dev');
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }
}

I am getting this error once I hit the demo route:

ERROR Error: Uncaught (in promise): Error:
  StaticInjectorError[DevOnlyGuard]:

  StaticInjectorError[DevOnlyGuard]:
      NullInjectorError: No provider for DevOnlyGuard! Error: StaticInjectorError[DevOnlyGuard]:  ....

even if I added the Guard to the list of providers in my app.module
like

providers: [
    ...
    DevOnlyGuard,
];

Any ideas?

Body:
remove single quotes from canActivate: ['DevOnlyGuard']

Below is how should we use canActivate:

Method 1:

  @Injectable()
    class CanActivateTeam implements CanActivate {
      constructor(private permissions: Permissions, private currentUser: UserToken) {}

      canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<boolean>|Promise<boolean>|boolean {
        return this.permissions.canActivate(this.currentUser, route.params.id);
      }
    }

    @NgModule({
      imports: [
        RouterModule.forRoot([
          {
            path: 'team/:id',
            component: TeamCmp,
            canActivate: [CanActivateTeam]
          }
        ])
      ],
      providers: [CanActivateTeam, UserToken, Permissions]
    })
    class AppModule {}

Method 2(with Single Quote...):

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        canActivate: ['canActivateTeam']
      }
    ])
  ],
  providers: [
    {
      provide: 'canActivateTeam',
      useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true
    }
  ]
})
class AppModule {}


问:
How do I retrieve a specific image from a specific link? (Programming Beginner)

I'm a programming beginner - so apologies if this question is not appropriate. I have tried my best to search the internet for an answer for the better part of today.
I'm trying to retrieve the image from this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992

I am using the code below: (I know it fetches all of the images.)

My question is - why does this code work on this link: http://www.imdb.com/title/tt0076759/?ref_=nv_sr_5 but not on this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992 ?

```<code>import urllib2
import os
from BeautifulSoup import BeautifulSoup

URL = "http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992"
default_dir = os.path.join(os.path.expanduser("~"),"Pictures")
opener = urllib2.build_opener()
urllib2.install_opener(opener)
soup = BeautifulSoup(urllib2.urlopen(URL).read())
imgs = soup.findAll("img",{"alt":True, "src":True})

for img in imgs:
    img_url = img["src"]
    filename = os.path.join(default_dir, img_url.split("/")[-1])
    img_data = opener.open(img_url)
    f = open(filename,"wb")
    f.write(img_data.read())
    f.close()
</code>```

I would like to fetch the image from this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992

I am currently getting no images with the above code from this link. It works with other links though.

答:
this is because the img tags inside that url don't have the alt attribute, which you are defining for filtering those img tags with:

```<code>imgs = soup.findAll("img",{"alt":True, "src":True})
</code>```

that list returns empty.

Body:
I'm a programming beginner - so apologies if this question is not appropriate. I have tried my best to search the internet for an answer for the better part of today.
I'm trying to retrieve the image from this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992

I am using the code below: (I know it fetches all of the images.)

My question is - why does this code work on this link: http://www.imdb.com/title/tt0076759/?ref_=nv_sr_5 but not on this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992 ?

import urllib2
import os
from BeautifulSoup import BeautifulSoup

URL = "http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992"
default_dir = os.path.join(os.path.expanduser("~"),"Pictures")
opener = urllib2.build_opener()
urllib2.install_opener(opener)
soup = BeautifulSoup(urllib2.urlopen(URL).read())
imgs = soup.findAll("img",{"alt":True, "src":True})

for img in imgs:
    img_url = img["src"]
    filename = os.path.join(default_dir, img_url.split("/")[-1])
    img_data = opener.open(img_url)
    f = open(filename,"wb")
    f.write(img_data.read())
    f.close()

I would like to fetch the image from this link: http://www.imdb.com/title/tt0076759/mediaviewer/rm2809748992

I am currently getting no images with the above code from this link. It works with other links though.

Body:
this is because the img tags inside that url don't have the alt attribute, which you are defining for filtering those img tags with:

imgs = soup.findAll("img",{"alt":True, "src":True})

that list returns empty.


问:
JPA - Criteria API and EmbeddedId
I want to use criteria to make the following query. I have an Entity with EmbeddedId defined:

```<code> @Entity
 @Table(name="TB_INTERFASES")
 public class Interfase implements Serializable {

  @EmbeddedId
  private InterfaseId id;
 }

 @Embeddable
 public class InterfaseId implements Serializable {
  @Column(name="CLASE")
  private String clase;
 }
</code>```

And the criteria query that i am trying to do is:

```<code> CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
 CriteriaQuery<Interfase> criteriaQuery = criteriaBuilder.createQuery(Interfase.class);
 Root<Interfase> entity = criteriaQuery.from(Interfase.class);
 criteriaQuery.where(
   criteriaBuilder.equal(entity.get("clase"), "Clase"),
 );
</code>```

But this is throwing an IllegalArgumentException:

```<code>java.lang.IllegalArgumentException: Not an managed type: class InterfaseId
</code>```

i've tried with this queries too:

```<code> Root<Interfase> entity = criteriaQuery.from(Interfase.class);
 criteriaQuery.where(
   criteriaBuilder.equal(entity.get("id").get("clase"), "Clase"),
 );
</code>```

and this one too...

```<code> Root<Interfase> entity = criteriaQuery.from(Interfase.class);
 criteriaQuery.where(
   criteriaBuilder.equal(entity.get("id.clase", "Clase"),
 );
</code>```

with no luck.
So my question is how can i make a query with criteria when my classes are using Embedded and EmbeddedId annotations?

Thanks!.
Mauro.

答:
Try to copy and paste the metamodel classes into the same folder where your entities are saved (in NetBeans 8.2 they are automatically generated and have the same name of your entity but with an underscore at the end. Should be something like Interfase_ and InterfaseId_).

Force the import of the metamodel classes Interfase_ and InterfaseId_ and refer to the desired field.

```<code>CriteriaBuilder builder = em.getCriteriaBuilder();

CriteriaQuery<Interfase> criteria = builder.createQuery(Interfase.class);
Root<Interfase> interfaseRoot = criteria.from(Interfase.class);
criteria.select(interfaseRoot);
criteria.where(builder.equal(interfaseRoot.get(Interfase_.id).get(InterfaseId_.clase),"Referencia 111"));
List<Interfase> interfases = em.createQuery(criteria).getResultList();
</code>```

Title: JPA - Criteria API and EmbeddedId

Body:
I want to use criteria to make the following query. I have an Entity with EmbeddedId defined:

 @Entity
 @Table(name="TB_INTERFASES")
 public class Interfase implements Serializable {

  @EmbeddedId
  private InterfaseId id;
 }

 @Embeddable
 public class InterfaseId implements Serializable {
  @Column(name="CLASE")
  private String clase;
 }

And the criteria query that i am trying to do is:

 CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
 CriteriaQuery<Interfase> criteriaQuery = criteriaBuilder.createQuery(Interfase.class);
 Root<Interfase> entity = criteriaQuery.from(Interfase.class);
 criteriaQuery.where(
   criteriaBuilder.equal(entity.get("clase"), "Clase"),
 );

But this is throwing an IllegalArgumentException:

java.lang.IllegalArgumentException: Not an managed type: class InterfaseId

i've tried with this queries too:

 Root<Interfase> entity = criteriaQuery.from(Interfase.class);
 criteriaQuery.where(
   criteriaBuilder.equal(entity.get("id").get("clase"), "Clase"),
 );

and this one too...

 Root<Interfase> entity = criteriaQuery.from(Interfase.class);
 criteriaQuery.where(
   criteriaBuilder.equal(entity.get("id.clase", "Clase"),
 );

with no luck.
So my question is how can i make a query with criteria when my classes are using Embedded and EmbeddedId annotations?

Thanks!.
Mauro.

Body:
Try to copy and paste the metamodel classes into the same folder where your entities are saved (in NetBeans 8.2 they are automatically generated and have the same name of your entity but with an underscore at the end. Should be something like Interfase_ and InterfaseId_).

Force the import of the metamodel classes Interfase_ and InterfaseId_ and refer to the desired field.

CriteriaBuilder builder = em.getCriteriaBuilder();

CriteriaQuery<Interfase> criteria = builder.createQuery(Interfase.class);
Root<Interfase> interfaseRoot = criteria.from(Interfase.class);
criteria.select(interfaseRoot);
criteria.where(builder.equal(interfaseRoot.get(Interfase_.id).get(InterfaseId_.clase),"Referencia 111"));
List<Interfase> interfases = em.createQuery(criteria).getResultList();