问:
How do I make a function work in a derived class?
So this is my code. It has an abstact class named PC and 3 derived classes named HomePC, GamingPC and WorkStationPC. It has to do 4 things: 1)Create new pc of whatever type, 2)Upgrade a pc that already exists, 3)Delete a pc that already exists and 4)Print all pcs of a certain type. I managed to make the "new" and "print" functions work. I can't figure out how to make the "upgrade" and "delete" functions work. I suppose they will be similar. If someone has an idea of how I can do it please let me know.

Thank you!

```<code>#include <iostream>
#include <string>
#include <vector>

using namespace std;

class PC{
protected:
    string operatingSystem;
    int ramSlots;
    int pcieSlots;
    int cpu;
    int totalRamSlots;
    int gbPerRam;
    int ssd;
    int cost;
public:
    virtual void Print() = 0;
    virtual void Upgrade(string opt) = 0;

    PC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlots, int ramGB, int ssdGB, int pcCost){
        operatingSystem = OS;
        ramSlots = moboRam;
        pcieSlots = moboPcie;
        cpu = numOfCores;
        totalRamSlots = ramSlots;
        gbPerRam = ramGB;
        ssd = ssdGB;
        cost = pcCost;
    }
};

class HomePC: public PC{
private:
    string model;
public:
    HomePC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlot, int ramGB, int ssdGB, int pcCost, string mdl):PC(OS, moboRam, moboPcie, numOfCores, ramSlot, ramGB, ssdGB, pcCost){
        model = mdl;
    }

    void set_totalRamSlots(int ramSlots){totalRamSlots = ramSlots;}
    void set_gbPerRam(int ramGB){gbPerRam = ramGB;}
    void set_cpu(int numOfCores){cpu = numOfCores;}

    //delete spaces

    void Print(){ cout << "Μodel: " << model << endl << "Operating System: MacOS" <<endl << "Motherboard: 2 RAM slot(s), 0 GPU slot(s)" << endl << "CPU: " << cpu << endl << "RAM: " << totalRamSlots << " stick(s), " << gbPerRam << " GigaBytes" << endl << "SSD: 256" << endl << "Cost: 800EUR" << endl;}
    void Upgrade(string opt){ cout << opt << endl;}

    //delete spaces

    string get_model() const {return model;}
};

class GamingPC: public PC{
private:
    string model;
    int gpu;
public:
    GamingPC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlot, int ramGB, int ssdGB, int pcCost, int numOfGpus, string mdl):PC(OS, moboRam, moboPcie, numOfCores, ramSlot, ramGB, ssdGB, pcCost){
        model = mdl;
        gpu = numOfGpus;
    }

    //delete spaces

    void set_totalRamSlots(int ramSlots){totalRamSlots = ramSlots;}
    void set_gbPerRam(int ramGB){gbPerRam = ramGB;}
    void set_cpu(int numOfCores){cpu = numOfCores;}
    void set_gpu(int numOfGpus){gpu = numOfGpus;}

    //delete spaces

    void Print(){ cout << "Μodel: " << model << endl << "Operating System: MacOS" << endl << "Motherboard: 4 RAM slot(s), 2 GPU slot(s)" << endl << "CPU: " << cpu << endl << "RAM: "<< totalRamSlots << " stick(s), " << gbPerRam << " GigaBytes" << endl << "SSD: 256" << endl << "GPU: " << gpu << endl << "Cost: 1300EUR" << endl;}
    void Upgrade(string opt){ cout << opt << endl;}

    //delete spaces

    string get_model() const {return model;}
};

class WorkStationPC: public PC{
private:
    string model;
    int gpu;
    bool afterburner;
public:
    WorkStationPC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlot, int ramGB, int ssdGB, int pcCost, int numOfGpus, bool aburner, string mdl):PC(OS, moboRam, moboPcie, numOfCores, ramSlot, ramGB, ssdGB, pcCost){
        model = mdl;
        gpu = numOfGpus;
        afterburner = aburner;
    }

    //delete spaces

    void set_totalRamSlots(int ramSlots){totalRamSlots = ramSlots;}
    void set_gbPerRam(int ramGB){gbPerRam = ramGB;}
    void set_cpu(int numOfCores){cpu = numOfCores;}
    void set_gpu(int numOfGpus){gpu = numOfGpus;}
    void set_afterburner(int aburner){afterburner = aburner;}

    //delete spaces

    void Print(){ cout << "Μodel: " << model << endl << "Operating System: MacOS" << endl << "Motherboard: 8 RAM slot(s), 1 GPU slot(s)" << endl << "CPU: " << cpu << endl << "RAM: " << totalRamSlots << " stick(s), " << gbPerRam << " GigaBytes" << endl << "SSD: 256" << endl << "GPU: " << gpu << endl << "Afterburner: " << afterburner << endl << "Cost: 1600EUR" << endl;}
    void Upgrade(string opt){ cout << opt << endl;}

    //delete spaces

    string get_model() const {return model;}
};

int main(){
    vector<int> count_homepc;
    vector<int> count_gamingpc;
    vector<int> count_workstationpc;
    int i, k = 0;
    string input, opCode, key=" ", pcType, pcModel, data[5];
    size_t pos = 0;
    vector<PC*> pcList;
    do{
        cout << "---Enter an operation:" << endl;
        getline(cin,input);
        pos=input.find(key);
        opCode=input.substr(0,pos);
        input.erase(0,pos + 1);
        if(opCode=="new"){
            pos=input.find(key);
            pcType=input.substr(0,pos);
            input.erase(0,pos + 1);
            pcModel=input;
            if(pcType=="homepc"){
                HomePC* myPC = new HomePC("MacOS", 2, 0, 2, 1, 4, 256, 800, pcModel);
                pcList.push_back(myPC);
                count_homepc.push_back(k);
            }else if(pcType=="gamingpc"){
                GamingPC* myPC = new GamingPC("Windows", 4, 2, 6, 2, 8, 1024, 1300, 1, pcModel);
                pcList.push_back(myPC);
                count_gamingpc.push_back(k);
            }else if(pcType=="workstationpc"){
                WorkStationPC* myPC = new WorkStationPC("Linux", 8, 1, 6, 4, 16, 2048, 1600, 0, 0, pcModel);
                pcList.push_back(myPC);
                count_workstationpc.push_back(k);
            }else cout << "Wrong PC type, try again." << endl;
        }else if(opCode=="upgrade"){
            pos=input.find(key);
            pcModel=input.substr(0,pos);
            input.erase(0,pos + 1);
            cout << input << endl;
        }else if(opCode=="delete"){
            cout << "WIP" << endl;
        }else if(opCode=="print"){
            cout << endl;
            int point;
            if(input=="homepc"){
                for(i=0;i<count_homepc.size();i++){
                    point = count_homepc[i];
                    pcList[point]->Print();
                    cout << endl;
                }
            }else if(input=="gamingpc"){
                for(i=0;i<count_gamingpc.size();i++){
                    point = count_gamingpc[i];
                    pcList[point]->Print();
                    cout << endl;
                }
            }else if(input=="workstationpc"){
                for(i=0;i<count_workstationpc.size();i++){
                    point = count_workstationpc[i];
                    pcList[point]->Print();
                    cout << endl;
                }
            }
        }else if(opCode!="q") cout << "Wrong operation, try again." << endl;
        k++;
    }while(opCode!="q"); //when someone inputs the string "q" the loop ends
    return 0;
}
</code>```

答: You can delete or upgrade based on a unique ID you give to each PC. That way you can have multiple PCs with the same model and same names. This ID could be the index of the pcList vector given for that pc when pushed into that vector. When the user input the operation "new" and a pc you can output pcList.size() which will be given as an ID to the new PC. And when the user wants to upgrade or delete he has to specify the ID of the pc he wants to modify</p>

Body:
So this is my code. It has an abstact class named PC and 3 derived classes named HomePC, GamingPC and WorkStationPC. It has to do 4 things: 1)Create new pc of whatever type, 2)Upgrade a pc that already exists, 3)Delete a pc that already exists and 4)Print all pcs of a certain type. I managed to make the "new" and "print" functions work. I can't figure out how to make the "upgrade" and "delete" functions work. I suppose they will be similar. If someone has an idea of how I can do it please let me know.

Thank you!

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class PC{
protected:
    string operatingSystem;
    int ramSlots;
    int pcieSlots;
    int cpu;
    int totalRamSlots;
    int gbPerRam;
    int ssd;
    int cost;
public:
    virtual void Print() = 0;
    virtual void Upgrade(string opt) = 0;

    PC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlots, int ramGB, int ssdGB, int pcCost){
        operatingSystem = OS;
        ramSlots = moboRam;
        pcieSlots = moboPcie;
        cpu = numOfCores;
        totalRamSlots = ramSlots;
        gbPerRam = ramGB;
        ssd = ssdGB;
        cost = pcCost;
    }
};

class HomePC: public PC{
private:
    string model;
public:
    HomePC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlot, int ramGB, int ssdGB, int pcCost, string mdl):PC(OS, moboRam, moboPcie, numOfCores, ramSlot, ramGB, ssdGB, pcCost){
        model = mdl;
    }

    void set_totalRamSlots(int ramSlots){totalRamSlots = ramSlots;}
    void set_gbPerRam(int ramGB){gbPerRam = ramGB;}
    void set_cpu(int numOfCores){cpu = numOfCores;}

    //delete spaces

    void Print(){ cout << "Μodel: " << model << endl << "Operating System: MacOS" <<endl << "Motherboard: 2 RAM slot(s), 0 GPU slot(s)" << endl << "CPU: " << cpu << endl << "RAM: " << totalRamSlots << " stick(s), " << gbPerRam << " GigaBytes" << endl << "SSD: 256" << endl << "Cost: 800EUR" << endl;}
    void Upgrade(string opt){ cout << opt << endl;}

    //delete spaces

    string get_model() const {return model;}
};

class GamingPC: public PC{
private:
    string model;
    int gpu;
public:
    GamingPC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlot, int ramGB, int ssdGB, int pcCost, int numOfGpus, string mdl):PC(OS, moboRam, moboPcie, numOfCores, ramSlot, ramGB, ssdGB, pcCost){
        model = mdl;
        gpu = numOfGpus;
    }

    //delete spaces

    void set_totalRamSlots(int ramSlots){totalRamSlots = ramSlots;}
    void set_gbPerRam(int ramGB){gbPerRam = ramGB;}
    void set_cpu(int numOfCores){cpu = numOfCores;}
    void set_gpu(int numOfGpus){gpu = numOfGpus;}

    //delete spaces

    void Print(){ cout << "Μodel: " << model << endl << "Operating System: MacOS" << endl << "Motherboard: 4 RAM slot(s), 2 GPU slot(s)" << endl << "CPU: " << cpu << endl << "RAM: "<< totalRamSlots << " stick(s), " << gbPerRam << " GigaBytes" << endl << "SSD: 256" << endl << "GPU: " << gpu << endl << "Cost: 1300EUR" << endl;}
    void Upgrade(string opt){ cout << opt << endl;}

    //delete spaces

    string get_model() const {return model;}
};

class WorkStationPC: public PC{
private:
    string model;
    int gpu;
    bool afterburner;
public:
    WorkStationPC(string OS, int moboRam, int moboPcie, int numOfCores, int ramSlot, int ramGB, int ssdGB, int pcCost, int numOfGpus, bool aburner, string mdl):PC(OS, moboRam, moboPcie, numOfCores, ramSlot, ramGB, ssdGB, pcCost){
        model = mdl;
        gpu = numOfGpus;
        afterburner = aburner;
    }

    //delete spaces

    void set_totalRamSlots(int ramSlots){totalRamSlots = ramSlots;}
    void set_gbPerRam(int ramGB){gbPerRam = ramGB;}
    void set_cpu(int numOfCores){cpu = numOfCores;}
    void set_gpu(int numOfGpus){gpu = numOfGpus;}
    void set_afterburner(int aburner){afterburner = aburner;}

    //delete spaces

    void Print(){ cout << "Μodel: " << model << endl << "Operating System: MacOS" << endl << "Motherboard: 8 RAM slot(s), 1 GPU slot(s)" << endl << "CPU: " << cpu << endl << "RAM: " << totalRamSlots << " stick(s), " << gbPerRam << " GigaBytes" << endl << "SSD: 256" << endl << "GPU: " << gpu << endl << "Afterburner: " << afterburner << endl << "Cost: 1600EUR" << endl;}
    void Upgrade(string opt){ cout << opt << endl;}

    //delete spaces

    string get_model() const {return model;}
};

int main(){
    vector<int> count_homepc;
    vector<int> count_gamingpc;
    vector<int> count_workstationpc;
    int i, k = 0;
    string input, opCode, key=" ", pcType, pcModel, data[5];
    size_t pos = 0;
    vector<PC*> pcList;
    do{
        cout << "---Enter an operation:" << endl;
        getline(cin,input);
        pos=input.find(key);
        opCode=input.substr(0,pos);
        input.erase(0,pos + 1);
        if(opCode=="new"){
            pos=input.find(key);
            pcType=input.substr(0,pos);
            input.erase(0,pos + 1);
            pcModel=input;
            if(pcType=="homepc"){
                HomePC* myPC = new HomePC("MacOS", 2, 0, 2, 1, 4, 256, 800, pcModel);
                pcList.push_back(myPC);
                count_homepc.push_back(k);
            }else if(pcType=="gamingpc"){
                GamingPC* myPC = new GamingPC("Windows", 4, 2, 6, 2, 8, 1024, 1300, 1, pcModel);
                pcList.push_back(myPC);
                count_gamingpc.push_back(k);
            }else if(pcType=="workstationpc"){
                WorkStationPC* myPC = new WorkStationPC("Linux", 8, 1, 6, 4, 16, 2048, 1600, 0, 0, pcModel);
                pcList.push_back(myPC);
                count_workstationpc.push_back(k);
            }else cout << "Wrong PC type, try again." << endl;
        }else if(opCode=="upgrade"){
            pos=input.find(key);
            pcModel=input.substr(0,pos);
            input.erase(0,pos + 1);
            cout << input << endl;
        }else if(opCode=="delete"){
            cout << "WIP" << endl;
        }else if(opCode=="print"){
            cout << endl;
            int point;
            if(input=="homepc"){
                for(i=0;i<count_homepc.size();i++){
                    point = count_homepc[i];
                    pcList[point]->Print();
                    cout << endl;
                }
            }else if(input=="gamingpc"){
                for(i=0;i<count_gamingpc.size();i++){
                    point = count_gamingpc[i];
                    pcList[point]->Print();
                    cout << endl;
                }
            }else if(input=="workstationpc"){
                for(i=0;i<count_workstationpc.size();i++){
                    point = count_workstationpc[i];
                    pcList[point]->Print();
                    cout << endl;
                }
            }
        }else if(opCode!="q") cout << "Wrong operation, try again." << endl;
        k++;
    }while(opCode!="q"); //when someone inputs the string "q" the loop ends
    return 0;
}


来源: stackexchange

问:
ConcurrentLinkedQueue Questions
Could you please clarify if we need to use explicit synchronization or locks for using ConcurrentLinkedQueue? I am specifically interested in knowing if sync calls are needed for following ConcurrentLinkedQueue methods.

add

clear

size

Possibly size is the only method which might require explicit sync since it's a not an atomic method but ConcurrentLinkedQueue java docs say that

"Beware that, unlike in most
  collections, the size method is NOT a
  constant-time operation. Because of
  the asynchronous nature of these
  queues, determining the current number
  of elements requires a traversal of
  the elements. "

which make me believe that though size call may be slow but it doesn't require any explicit sync call.

Thanks in advance ...

答:
It is unnecessary to synchronize to preserve the internal structure of the queue. However it may be necessary to linearise other invariants of your structure.

For instance size() is fairly meaningless in any shared mutable container. All it can ever tell you is something about what it was the last time you asked, not what it is now, unless you stop the world and prevent concurrent modification. It is only useful for indicative monitoring purposes, you should never use it in your algorithm.

Similarly, clear() doesn't really mean much without some kind of external intervention. Clear what? The things that are in it at the time you call clear? In a concurrent structure answering that is a difficult if not impossible question.

So, you are better off using it as a simple thread-safe queue (only offering and polling) and steering clear of the others unless you externally lock.

ContentLicense: CC BY-SA 2.5

Title: ConcurrentLinkedQueue Questions

ContentLicense: CC BY-SA 3.0


问:
"mask cannot be scalar" in keras.max() function
When I used Keras.max(box_scores,keep_dims=False) in an assignment, I got an error, and it was "mask cannot be scalar".
But when I used Keras.max(box_scores,axis=-1,keep_dims=False) , I got the result. But I don't understand it.What is the purpose of axis=-1 in this function to correct this error?

```<code>box_scores = box_confidence * box_class_probs
box_classes = K.argmax(box_scores, axis=-1)
box_class_scores = K.max(box_scores,keepdims=False)
filtering_mask = ((box_class_scores)>=threshold)
scores = tf.boolean_mask(box_class_scores,filtering_mask ,name="filtering_scores")
boxes = tf.boolean_mask(boxes,filtering_mask ,name="filtering_boxes")
classes = tf.boolean_mask(box_classes,filtering_mask ,name="filtering_classes")
</code>```

Here, box_confidence = tensor of shape (19, 19, 5, 1),
    boxes -- tensor of shape (19, 19, 5, 4),
    box_class_probs -- tensor of shape (19, 19, 5, 80),
    and threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box.

答:
For max function axis parameter specifies a list of dimensions (or one dimension or None for all dimensions) over which max is computed. When negative integers are used they are interpreted similarly to Python negative indicies of array (i.e. -1 means the last dimension, -2 - second from last, etc.).

So when you're not specifying axis argument the default value None is used resulting in scalar output (i.e. maximum of all values in the tensor). When you are specifying axis=-1 only the last dimension is reduced so from tensor of shape (a,b,c,d) you'll get a tensor of shape (a,b,c).

Strangely, keras documentation doesn't specify it here max reference.

ContentLicense: CC BY-SA 4.0

Body:
When I used Keras.max(box_scores,keep_dims=False) in an assignment, I got an error, and it was "mask cannot be scalar".
But when I used Keras.max(box_scores,axis=-1,keep_dims=False) , I got the result. But I don't understand it.What is the purpose of axis=-1 in this function to correct this error?

box_scores = box_confidence * box_class_probs
box_classes = K.argmax(box_scores, axis=-1)
box_class_scores = K.max(box_scores,keepdims=False)
filtering_mask = ((box_class_scores)>=threshold)
scores = tf.boolean_mask(box_class_scores,filtering_mask ,name="filtering_scores")
boxes = tf.boolean_mask(boxes,filtering_mask ,name="filtering_boxes")
classes = tf.boolean_mask(box_classes,filtering_mask ,name="filtering_classes")

Here, box_confidence = tensor of shape (19, 19, 5, 1),
    boxes -- tensor of shape (19, 19, 5, 4),
    box_class_probs -- tensor of shape (19, 19, 5, 80),
    and threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box.


问:
POST requests not working with token validation checks
With flask_jwt_extended, whenever I'm trying to send a POST request with the following decorators:

```<code>@jwt_refresh_token_required
@jwt_required
</code>```

I am having this 401 error:

```<code>{
    "msg": "Missing CSRF token"
}
</code>```

When I use a GET instead, it's working fine.
I have read the documentation that talk about double submit protection, but that does not solve my problem. Any ideas how I could fix my issue?
The code to reproduce the problem is below.

Below is the structure of my code:

```<code>- src/__init.py__ # where I put all configs
- src/auth.py # where are the endpoints
</code>```

init.py

login_serializer = URLSafeTimedSerializer(SERIALIZER_SECRET_KEY)
jwt = JWTManager()

def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = SERIALIZER_SECRET_KEY
    app.config['JWT_SECRET_KEY'] = JWT_SECRET_KEY
    app.config['JWT_TOKEN_LOCATION'] = ['cookies']
    app.config['JWT_COOKIE_CSRF_PROTECT'] = True
    db.init_app(app)
    jwt.init_app(app)

    # blueprint for auth routes in our app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from .routes import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
```

<p>auth.py </p>

<pre class="lang-py prettyprint-override"><code>import logging
from flask import Blueprint, request, current_app as app, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from . import login_serializer, jwt
from flask_jwt_extended import (jwt_required, jwt_refresh_token_required,
                                get_jwt_identity, get_raw_jwt, unset_jwt_cookies,
                                current_user, create_access_token, create_refresh_token, set_access_cookies, set_refresh_cookies)

auth = Blueprint('auth', __name__)

def set_response_cookies(token_identity, resp=None, token_types=["access", "refresh"]):
    """
    Helper function to set cookies in response
    """
    logging.warning("Setting cookies")
    resp = jsonify(resp)
    token_types.sort()
    if token_types == ["access", "refresh"]:
        access_token = create_access_token(identity = token_identity)
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token, "refresh_token": refresh_token})
        set_access_cookies(resp, access_token)
        set_refresh_cookies(resp, refresh_token)
        return resp
    elif token_types == ["access"]:
        access_token = create_access_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token})
        set_access_cookies(resp, access_token)
        return resp
    elif token_types == ["refresh"]:
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"refresh_token": refresh_token})
        set_refresh_cookies(resp, refresh_token)
        return resp
    else:
        raise ValueError("Wrong Call to this function")

@jwt.user_claims_loader
def add_claims_to_access_token(identity):
    """
    """
    return {
        'email': identity
    }

@jwt.user_loader_callback_loader
def user_loader_callback(identity):
    """
    Ignore Here, but I use it to get a User object (not mentionned here) from a Token.
    """
    return User.objects(
        email=identity,
    ).first()

@auth.route('/token', methods=['POST'])
def token_post():
    """ obj =
    {"email": "email", "password": "password"} => Tokens
    """
    obj = request.get_json()
    resp = set_response_cookies(obj["email"], {"token": True}, ["access", "refresh"])
    return resp, 200

@auth.route('/token/access', methods=['POST'])
@jwt_refresh_token_required
def refresh_access_cookies():
    if current_user:
        resp = set_response_cookies(current_user.email, {"token_refreshed": True}, ["access"])
    return resp, 200
</code>```

So, here, all I have to do to reproduce the error is:

Make a POST request to /token => In postman, my response will get all cookies and headers.

Make a POST request to /token/access => Give the error mentioned above.

答:
On your configuration, you enabled JWT_COOKIE_CSRF_PROTECT to true.

For devep purpose, the error will be gone if you can set it to False which may not safe.

On production, You need to pass csrf_token on your request header.

I think this links can help you.

https://flask-jwt-extended.readthedocs.io/en/stable/tokens_in_cookies/ (see the last section)

https://flask-wtf.readthedocs.io/en/stable/csrf.html

Body:
With flask_jwt_extended, whenever I'm trying to send a POST request with the following decorators:

@jwt_refresh_token_required
@jwt_required

I am having this 401 error:

{
    "msg": "Missing CSRF token"
}

When I use a GET instead, it's working fine.
I have read the documentation that talk about double submit protection, but that does not solve my problem. Any ideas how I could fix my issue?
The code to reproduce the problem is below.

Below is the structure of my code:

- src/__init.py__ # where I put all configs
- src/auth.py # where are the endpoints

init.py

login_serializer = URLSafeTimedSerializer(SERIALIZER_SECRET_KEY)
jwt = JWTManager()

def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = SERIALIZER_SECRET_KEY
    app.config['JWT_SECRET_KEY'] = JWT_SECRET_KEY
    app.config['JWT_TOKEN_LOCATION'] = ['cookies']
    app.config['JWT_COOKIE_CSRF_PROTECT'] = True
    db.init_app(app)
    jwt.init_app(app)

    # blueprint for auth routes in our app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from .routes import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

auth.py

import logging
from flask import Blueprint, request, current_app as app, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from . import login_serializer, jwt
from flask_jwt_extended import (jwt_required, jwt_refresh_token_required,
                                get_jwt_identity, get_raw_jwt, unset_jwt_cookies,
                                current_user, create_access_token, create_refresh_token, set_access_cookies, set_refresh_cookies)

auth = Blueprint('auth', __name__)

def set_response_cookies(token_identity, resp=None, token_types=["access", "refresh"]):
    """
    Helper function to set cookies in response
    """
    logging.warning("Setting cookies")
    resp = jsonify(resp)
    token_types.sort()
    if token_types == ["access", "refresh"]:
        access_token = create_access_token(identity = token_identity)
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token, "refresh_token": refresh_token})
        set_access_cookies(resp, access_token)
        set_refresh_cookies(resp, refresh_token)
        return resp
    elif token_types == ["access"]:
        access_token = create_access_token(identity = token_identity)
        if not resp:
            resp = jsonify({"access_token": access_token})
        set_access_cookies(resp, access_token)
        return resp
    elif token_types == ["refresh"]:
        refresh_token = create_refresh_token(identity = token_identity)
        if not resp:
            resp = jsonify({"refresh_token": refresh_token})
        set_refresh_cookies(resp, refresh_token)
        return resp
    else:
        raise ValueError("Wrong Call to this function")

@jwt.user_claims_loader
def add_claims_to_access_token(identity):
    """
    """
    return {
        'email': identity
    }

@jwt.user_loader_callback_loader
def user_loader_callback(identity):
    """
    Ignore Here, but I use it to get a User object (not mentionned here) from a Token.
    """
    return User.objects(
        email=identity,
    ).first()

@auth.route('/token', methods=['POST'])
def token_post():
    """ obj =
    {"email": "email", "password": "password"} => Tokens
    """
    obj = request.get_json()
    resp = set_response_cookies(obj["email"], {"token": True}, ["access", "refresh"])
    return resp, 200

@auth.route('/token/access', methods=['POST'])
@jwt_refresh_token_required
def refresh_access_cookies():
    if current_user:
        resp = set_response_cookies(current_user.email, {"token_refreshed": True}, ["access"])
    return resp, 200

So, here, all I have to do to reproduce the error is:

Make a POST request to /token => In postman, my response will get all cookies and headers.

Make a POST request to /token/access => Give the error mentioned above.


问:
405 vs 403 returned from Spring Controllers when using @PreAuthorize
We recently started using the @PreAuthorize annotation with our REST endpoints. It works great, however, I did have a question regarding the HTTP code returned when issuing a GET vs. a POST or PUT.
It appears that when a user is not authorized to access the controller's REST endpoint that the HTTP status returned is different for GET and PUT/POST.

So for example, if I have an endpoint that is a GET and has a @PreAuthorize annotation and the user doesn't have access, a 403 Forbidden is returned. This is what I expect.

If the same annotation is then placed on a controller method that is a POST or a PUT, the HTTP response is 405 Method Not Allowed (note that when properly authorized the POST/PUT method returns 200 as expected).

When stepping through the code you can see that the underlying security filter returns a 403, but in the POST/PUT scenario the status code is dropped/ignored and replaced with a 405, much like it does when a NullPointerExcpetion occurs in your controller code.

Is this the expected behavior or should a 403 Forbidden always be returned for users who do not have access to an end point?

答:
For me the problem was inside the SecurityConfiguration.

By removing the line .and().exceptionHandling().accessDeniedPage("/access-denied") i got 403 Forbidden instead of 405 Method not allowed which is most probably what you would expect.


问:
rails db:migrate fails due to duplicate table
I got some problems about my database.

I've generated a model Comment once, but this Comment migration not what I wanted, so I drop it, and succeeded to drop. Now I try to re-generate it, and keep running rails db:migrate, but something went wrong.

It shows :

"PG::DuplicateTable: ERROR:  relation "comments" already exists",

I've checked my schema.rb, did not have this comment table.

My database using "psql", and Rails version is "Rails 6.0.2.2". I've been searched related problem, but seems like not what I faced.

答:
If the data is not important you could just start fresh by dropping the current database and create a new one

```<code>rake db:drop
rake db:create
rake db:migrate
</code>```

If you are sure that those migrations already have been run before, then you can go and modify the schema migrations table directly where rails stores all migrations that have been run already.

First log into your postgres and choose the correct database

```<code>sudo -u postgres psql
\c db_name
</code>```

then to view the current migrations in the schema table

```<code>select * from schema_migrations;
</code>```

that will show you the current migrations that rails considers as done.

Then check you migrations folder, get the version of all the migration files you want to skip running, the file name starts with the version
for example
20200401212538_add_country_name.rb
the first numeric 20200401212538 part is the version

then insert them into the migrations table

```<code>insert  into schema_migrations VALUES ('version_of_migration');
</code>```

Or you could also delete migrations so you could re-run them if you want to.

After that running rake db:migrate should work just fine without trying to recreate the tables.

Another solutions you might consider is that in your migrations you check first if table exists or not before trying to create it.

Body:
If the data is not important you could just start fresh by dropping the current database and create a new one

rake db:drop
rake db:create
rake db:migrate

If you are sure that those migrations already have been run before, then you can go and modify the schema migrations table directly where rails stores all migrations that have been run already.

First log into your postgres and choose the correct database

sudo -u postgres psql
\c db_name

then to view the current migrations in the schema table

select * from schema_migrations;

that will show you the current migrations that rails considers as done.

Then check you migrations folder, get the version of all the migration files you want to skip running, the file name starts with the version
for example
20200401212538_add_country_name.rb
the first numeric 20200401212538 part is the version

then insert them into the migrations table

insert  into schema_migrations VALUES ('version_of_migration');

Or you could also delete migrations so you could re-run them if you want to.

After that running rake db:migrate should work just fine without trying to recreate the tables.

Another solutions you might consider is that in your migrations you check first if table exists or not before trying to create it.


问:
What is causing a from error in Laravel 7?
I would like to make a form with bootstrap.

I don't know why the second one causes an error.
What kind of things do you think could be the cause?

```<code>    //OK
    <form action="{{ route('contact_confirm') }}" method="POST">
        {{ csrf_field() }}
        <button class="btn btn-primary btn-xl" type="submit">Send</button></div>
        <input id="title" type="text" name = "title"  />
        <input id="title" type="text" name = "body"  />
    </form>
</code>```

```<code>    //NG
    <div class="row">
        <div class="col-lg-8 mx-auto">
            <form id="contactForm" 　action="{{ route('contact_confirm') }}" method="POST">
                {{ csrf_field() }}
                <div class="control-group">
                    <div class="form-group floating-label-form-group controls mb-0 pb-2">
                        <label>TITLE</label>
                        <input class="form-control" id="title" type="text" name = "title" placeholder="Title" required="required" data-validation-required-message="Please enter your name." />
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="control-group">
                    <div class="form-group floating-label-form-group controls mb-0 pb-2">
                        <label>CONTENTS</label>
                        <textarea class="form-control" id="message" rows="5" name ="body" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <br />
                <div class="form-group">
                    <button class="btn btn-primary btn-xl" id="sendMessageButton" type="submit">Send</button>
                </div>
            </form>

</code>```

答:
It's really strange that you didn't provide any error log or any kind of a message what so ever. However, your problem is exactly here:

　action=

In the opening form, remove the extra two spaces The second one is a hidden not accepted character

Body:
I would like to make a form with bootstrap.

I don't know why the second one causes an error.
What kind of things do you think could be the cause?

    //OK
    <form action="{{ route('contact_confirm') }}" method="POST">
        {{ csrf_field() }}
        <button class="btn btn-primary btn-xl" type="submit">Send</button>

        <input id="title" type="text" name = "title"  />
        <input id="title" type="text" name = "body"  />
    </form>

    //NG

            <form id="contactForm" 　action="{{ route('contact_confirm') }}" method="POST">
                {{ csrf_field() }}

                        TITLE
                        <input class="form-control" id="title" type="text" name = "title" placeholder="Title" required="required" data-validation-required-message="Please enter your name." />

                        CONTENTS
                        <textarea class="form-control" id="message" rows="5" name ="body" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>

                    <button class="btn btn-primary btn-xl" id="sendMessageButton" type="submit">Send</button>

            </form>


问:
Filtering wrong using a timestamp range in django views
When I want to filter my model using one exactly date I use the following code line,

```<code>today = datetime.datetime.now().date()
today_data = DevData.objects.filter(data_timestamp__date=today)
</code>```

And when I want to filter using a range of days, I use the following code line,

```<code>last7days = datetime.datetime.now().date() - datetime.timedelta(days=7)
last7days_data = DevData.objects.filter(data_timestamp__range=(last7days,today))
</code>```

The problem is that when I use this second code, appears a warning and runs very very slow,

RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-05-31 00:00:00) while time zone support is active.

How can I do it better?

I found this post, but don't understand how to solve it. Can somebody help me please?

答:
The fact that it runs rather slow is likely because you did not set a database index on the data_timestamp field, you can add one by specifying a db_index=True parameter [Django-doc]:

```<code>class DevData(models.Data):
    data_timestamp = models.DateTimeField(<b>db_index=True</b>)
    # …</code>```

You can furthermore filter the data by adding a __date lookup [Django-doc] in the query:

```<code>last7days = datetime.datetime.now().date() - datetime.timedelta(days=7)
last7days_data = DevData.objects.filter(
    <b>data_timestamp__date__range</b>=(last7days,today)
)</code>```

Body:
When I want to filter my model using one exactly date I use the following code line,

today = datetime.datetime.now().date()
today_data = DevData.objects.filter(data_timestamp__date=today)

And when I want to filter using a range of days, I use the following code line,

last7days = datetime.datetime.now().date() - datetime.timedelta(days=7)
last7days_data = DevData.objects.filter(data_timestamp__range=(last7days,today))

The problem is that when I use this second code, appears a warning and runs very very slow,

RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-05-31 00:00:00) while time zone support is active.

How can I do it better?

I found this post, but don't understand how to solve it. Can somebody help me please?

Body:
The fact that it runs rather slow is likely because you did not set a database index on the data_timestamp field, you can add one by specifying a db_index=True parameter [Django-doc]:

class DevData(models.Data):
    data_timestamp = models.DateTimeField(db_index=True)
    # …

You can furthermore filter the data by adding a __date lookup [Django-doc] in the query:

last7days = datetime.datetime.now().date() - datetime.timedelta(days=7)
last7days_data = DevData.objects.filter(
    data_timestamp__date__range=(last7days,today)
)


问:
Whats possible in a for loop
So today I went to an interview and one of the questions was the following (C# context).

```<code>//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}
</code>```

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

答:
Java supports this for structure.
In other languages like C, you can have any expression instead of a condition-clause.
This clause doesn't have to be related and could use different variables.

```<code>for({declaration-clause}; {condition-clause}; {expression-clause})
</code>```

The syntax is just an extension of the declaration and expression notations in C.

```<code>int i = 10, j = 0; // a declaration
j++, i--; // an expression.
</code>```

Too many to mention.

It may be bad practice if you cannot determine what the code means.  In your case you were able to figure it out even if you wouldn't have written it that way.

A for loop is never required You can always replace it with a while loop so, no.

Title: Whats possible in a for loop

Body:
So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

Body:
Java supports this for structure.
In other languages like C, you can have any expression instead of a condition-clause.
This clause doesn't have to be related and could use different variables.

for({declaration-clause}; {condition-clause}; {expression-clause})

The syntax is just an extension of the declaration and expression notations in C.

int i = 10, j = 0; // a declaration
j++, i--; // an expression.

Too many to mention.

It may be bad practice if you cannot determine what the code means.  In your case you were able to figure it out even if you wouldn't have written it that way.

A for loop is never required You can always replace it with a while loop so, no.


问:
TypeError: The superclass is not an object
I am trying to get my program to use this.state, however I got this error. Anyone know how to fix it?

答:
You should use as Component instead of Component().

Try as:

```<code>export default class Tables extends React.Component {
   // definition
}
</code>```

I hope this helps!

Body:
You should use as Component instead of Component().

Try as:

export default class Tables extends React.Component {
   // definition
}

I hope this helps!


问:
Best way to initialize form data on menu item selection in Spring MVC with JSP
I am having some menu items which are calling .jsp files, my menu related code is like:

```<code><li class="nav-item dropdown">
 <a class="nav-link dropdown-toggle text-white" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">menu2</a>
    <div class="dropdown-menu ">
        <a href="drop1.jsp" class="dropdown-item">drop1</a>
        <a href="drop2.jsp" class="dropdown-item">drop2</a>
        <a href="drop3.jsp" class="dropdown-item">drop3</a>
    </div>
</li>
</code>```

Requirement: [1] When user select any menu item For example: 'drop1' I want to fetch some data from the database and those fetched data I want to display in drop1.jsp.

Note: I am using spring security5.3.2, JSP, Java8 and Spring 5.2.6

答:
I'm Not getting your 1st requirement. </p>

<p>About 2nd you can use a simple Ajax call to the controller and return the response msg on the same page,  the page will not get refresh and you will be on the same page with all stufs done in background. </p>

Body:
I am having some menu items which are calling .jsp files, my menu related code is like:

 menu2

        drop1
        drop2
        drop3

Requirement: [1] When user select any menu item For example: 'drop1' I want to fetch some data from the database and those fetched data I want to display in drop1.jsp.

Note: I am using spring security5.3.2, JSP, Java8 and Spring 5.2.6

Body:
I'm Not getting your 1st requirement.

About 2nd you can use a simple Ajax call to the controller and return the response msg on the same page,  the page will not get refresh and you will be on the same page with all stufs done in background.


问:
My text in my clock python is not aligning properly
My text in my turtle module is not aligning properly, it is aligned up and to the left. I want it to align exactly where the turtle is. Can anyone help? I tried setting the xcor and ycor of the turtle up and to the left by 5 units and that did not work. Any help would be greatly appreciated.

Code:

```<code>import time
from datetime import datetime,date
import turtle
t = turtle.Pen()

while True:
    turtle.tracer(0, 0)
    hour_hand = float(datetime.today().hour)
    minute_hand = float(datetime.today().minute)
    second_hand = float(datetime.today().second)

    # Draw circle
    t.hideturtle()
    t.circle(150)
    t.left(90)
    t.up()
    t.forward(150)
    t.down()

    # Draw hands
    t.right(float(float(minute_hand) * 6))
    t.forward(100)
    t.backward(100)
    t.left(float(float(minute_hand) * 6))
    t.right(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.forward(50)
    t.backward(50)
    t.left(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.right(second_hand * 6)
    t.forward(125)
    t.backward(125)
    t.left(second_hand * 6)

    # Draw ticks
    for x in range(0, 12):
        t.up()
        t.forward(130)
        t.down()
        t.forward(20)
        t.backward(20)
        t.up()
        t.backward(130)
        t.down()
        t.right(30)
    for y in range(0, 60):
        t.up()
        t.forward(140)
        t.down()
        t.forward(10)
        t.backward(10)
        t.up()
        t.backward(140)
        t.down()
        t.right(6)
    t.up()

    # Draw numbers
    t.right(32.5)
    for z in range(1, 12):
        t.forward(130)
        t.sety(t.ycor() - 5)
        t.setx(t.xcor() - 5)
        t.write(z, align = 'center', font = ('Times New Roman', 16))
        t.sety(t.ycor() + 5)
        t.setx(t.xcor() + 5)
        t.backward(130)
        t.right(30)
    t.forward(130)
    t.write(12, align = 'center', font = ('Times New Roman', 16))
    turtle.update()
    t.hideturtle()
    time.sleep(0.85)
    t.reset()
</code>```

I don't really want to use tkinter, it is too complicated.

答:
I don't really want to use tkinter, it is too complicated.

I don't think it's too complicated and it is the most straight-forward solution to center the text vertically.

Use the following code to get the height of text in your font:

```<code>from tkinter import font

t = turtle.Pen()

font_config = font.Font(font=('Times New Roman', 16))
font_height = font_config.metrics("linespace")
</code>```

Then draw your text using font_height/2 as the vertical offset:

```<code>        t.sety(t.ycor() - font_height/2)
        t.write(z, align="center", font=font_config)
        t.sety(t.ycor() + font_height/2)
</code>```

Body:
My text in my turtle module is not aligning properly, it is aligned up and to the left. I want it to align exactly where the turtle is. Can anyone help? I tried setting the xcor and ycor of the turtle up and to the left by 5 units and that did not work. Any help would be greatly appreciated.

Code:

import time
from datetime import datetime,date
import turtle
t = turtle.Pen()

while True:
    turtle.tracer(0, 0)
    hour_hand = float(datetime.today().hour)
    minute_hand = float(datetime.today().minute)
    second_hand = float(datetime.today().second)

    # Draw circle
    t.hideturtle()
    t.circle(150)
    t.left(90)
    t.up()
    t.forward(150)
    t.down()

    # Draw hands
    t.right(float(float(minute_hand) * 6))
    t.forward(100)
    t.backward(100)
    t.left(float(float(minute_hand) * 6))
    t.right(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.forward(50)
    t.backward(50)
    t.left(int(float(hour_hand) * 30 + float(minute_hand) / 60 * 30))
    t.right(second_hand * 6)
    t.forward(125)
    t.backward(125)
    t.left(second_hand * 6)

    # Draw ticks
    for x in range(0, 12):
        t.up()
        t.forward(130)
        t.down()
        t.forward(20)
        t.backward(20)
        t.up()
        t.backward(130)
        t.down()
        t.right(30)
    for y in range(0, 60):
        t.up()
        t.forward(140)
        t.down()
        t.forward(10)
        t.backward(10)
        t.up()
        t.backward(140)
        t.down()
        t.right(6)
    t.up()

    # Draw numbers
    t.right(32.5)
    for z in range(1, 12):
        t.forward(130)
        t.sety(t.ycor() - 5)
        t.setx(t.xcor() - 5)
        t.write(z, align = 'center', font = ('Times New Roman', 16))
        t.sety(t.ycor() + 5)
        t.setx(t.xcor() + 5)
        t.backward(130)
        t.right(30)
    t.forward(130)
    t.write(12, align = 'center', font = ('Times New Roman', 16))
    turtle.update()
    t.hideturtle()
    time.sleep(0.85)
    t.reset()

I don't really want to use tkinter, it is too complicated.

Body:
I don't really want to use tkinter, it is too complicated.

I don't think it's too complicated and it is the most straight-forward solution to center the text vertically.

Use the following code to get the height of text in your font:

from tkinter import font

t = turtle.Pen()

font_config = font.Font(font=('Times New Roman', 16))
font_height = font_config.metrics("linespace")

Then draw your text using font_height/2 as the vertical offset:

        t.sety(t.ycor() - font_height/2)
        t.write(z, align="center", font=font_config)
        t.sety(t.ycor() + font_height/2)


问:
Why is the property of an inner div not being applied?
I'm very new to web-dev, so please bear with me. I am using Jekyll to generate my webpage. So I created some custom classes, and specified the css properties in the corresponding _sass file.

The following are the two classes which are relevant to the question:

```<code>.quote{
        width: 100%;
        margin: auto;
        text-align: center;
        background-color: #171717;
        font-size: 25px;
        padding: 10px;

        &.author{
            width: 50%;
            float: right;
            font-size: 20px;
            color: red;
            padding: 10px;
        }
  }
</code>```

This is the css code generated by Jekyll:

section .quote { width: 100%; margin: auto; text-align: center; background-color: #171717; font-size: 25px; padding: 10px; }

section .quote.author { width: 50%; float: right; font-size: 20px; color: red; padding: 10px; }
```

<p>The following is the relevant HTML code:</p>

<pre class="lang-html prettyprint-override"><code><div class="quote">

        <div id="randomquote">
            Hello there, this is supposed to show a quote.
         </div>

        <div class="author">
            This should be the author's name.
        </div>

</div>
</code>```

However, the properties of author class are not applied to the inner div. Rather it has the properties corresponding to quote. Why is that? Am I missing something?

Please note that I intend to use author inside quote.

答:
Add a space between your & and .author in CSS.  See here:

https://jsfiddle.net/y4j6ua1r/1/

Also in your generated code, there should be a space between .quote and .author See here:

https://jsfiddle.net/y4j6ua1r/2/

Body:
I'm very new to web-dev, so please bear with me. I am using Jekyll to generate my webpage. So I created some custom classes, and specified the css properties in the corresponding _sass file.

The following are the two classes which are relevant to the question:

.quote{
        width: 100%;
        margin: auto;
        text-align: center;
        background-color: #171717;
        font-size: 25px;
        padding: 10px;

        &.author{
            width: 50%;
            float: right;
            font-size: 20px;
            color: red;
            padding: 10px;
        }
  }

This is the css code generated by Jekyll:

section .quote { width: 100%; margin: auto; text-align: center; background-color: #171717; font-size: 25px; padding: 10px; }

section .quote.author { width: 50%; float: right; font-size: 20px; color: red; padding: 10px; }

The following is the relevant HTML code:

            Hello there, this is supposed to show a quote.

            This should be the author's name.

However, the properties of author class are not applied to the inner div. Rather it has the properties corresponding to quote. Why is that? Am I missing something?

Please note that I intend to use author inside quote.


问:
Which standard does VS2005, VS2008 follow?
Do they both follow the C++03 released in 2003?</p>

答: Yes, both of them follow C++03. VS2010 has some C++0x features. The most complete feature support is offered by GCC at the moment. </p>


问:
How to force older packages to install on newer versions of R?
I cannot install proj4string into my current version of R (2.15.1):

```<code>Warning message:
package ‘proj4string’ is not available (for R version 2.15.1)
</code>```

I assume this is because 2.15.1 is fairly new and the package just hasn't been updated.  Is there a general mechanism for forcing R to install an older version of a binary package (realizing that there may be bugs that result)?

答:
You can use install_version from the package devtools to install a specific package version.

To find the package version:

Search for the CRAN page of the package. E.g. for ggmap it is https://CRAN.R-project.org/package=ggmap

Check the archived packages. See heading "Downloads" and "Old Sources:"

Example code for package ggmap

```<code>devtools::install_version(
  "ggmap",
  version = "2.6",
  repos = "http://cran.us.r-project.org"
)
</code>```

Body:
I cannot install proj4string into my current version of R (2.15.1):

Warning message:
package ‘proj4string’ is not available (for R version 2.15.1)

I assume this is because 2.15.1 is fairly new and the package just hasn't been updated.  Is there a general mechanism for forcing R to install an older version of a binary package (realizing that there may be bugs that result)?

Body:
You can use install_version from the package devtools to install a specific package version.

To find the package version:

Search for the CRAN page of the package. E.g. for ggmap it is https://CRAN.R-project.org/package=ggmap

Check the archived packages. See heading "Downloads" and "Old Sources:"

Example code for package ggmap

devtools::install_version(
  "ggmap",
  version = "2.6",
  repos = "http://cran.us.r-project.org"
)


问:
Condense multiple combobox coding on Microsoft Excel VBA
I'm trying to condense the following code. I'm thinking a loop function may work, but it also may not because of the difference in VBA item. Any insight?</p>

```<code>If CheckBox1.Value = True _
    Then
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox2.Value = True _
    Then
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox3.Value = True _
    Then
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox4.Value = True _
    Then
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox5.Value = True _
    Then
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox6.Value = True _
    Then
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox7.Value = True _
    Then
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox8.Value = True _
    Then
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox9.Value = True _
    Then
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox10.Value = True _
    Then
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox11.Value = True _
    Then
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox12.Value = True _
    Then
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox13.Value = True _
    Then
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox14.Value = True _
    Then
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If
</code>```

答:
This is not a full answer - but the bones of a solution could include this structure</p>

```<code>  Dim xCtrl As Object, dVal As Variant, xRng As Range

  For Each xCtrl In Me.Controls
    If Left(xCtrl.name, 8) = "CheckBox" Then
       dVal = Val(Mid(xCtrl.name, 9))
       If dVal >= 1 And dVal < 15 Then
          If xCtrl.Value = True then
             ' ComboBox is True ... Update here
          Else
             ' ComboBox is False ... Update here
          End If
       End If
    End If
  Next xCtrl
</code>```

Body:
I'm trying to condense the following code. I'm thinking a loop function may work, but it also may not because of the difference in VBA item. Any insight?

If CheckBox1.Value = True _
    Then
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox2.Value = True _
    Then
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox3.Value = True _
    Then
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox4.Value = True _
    Then
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox5.Value = True _
    Then
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox6.Value = True _
    Then
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox7.Value = True _
    Then
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox8.Value = True _
    Then
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox9.Value = True _
    Then
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox10.Value = True _
    Then
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox11.Value = True _
    Then
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox12.Value = True _
    Then
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox13.Value = True _
    Then
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox14.Value = True _
    Then
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

Body:
This is not a full answer - but the bones of a solution could include this structure

  Dim xCtrl As Object, dVal As Variant, xRng As Range

  For Each xCtrl In Me.Controls
    If Left(xCtrl.name, 8) = "CheckBox" Then
       dVal = Val(Mid(xCtrl.name, 9))
       If dVal >= 1 And dVal < 15 Then
          If xCtrl.Value = True then
             ' ComboBox is True ... Update here
          Else
             ' ComboBox is False ... Update here
          End If
       End If
    End If
  Next xCtrl


问:
Is there a way to automate reinstalling packages and their dependencies in r?
So I used installR on Rstudio to update R to version 4.0.0, and it copied the files of my packages into the library file in the R, the directory being: C:\Users\Ibrahim\Documents\R\R-4.0.0\library

Whenever I'd call on a package, for example tidytext, it would give me:

```<code>library(tidytext)
Error: package or namespace load failed for ‘tidytext’:
 package ‘tidytext’ was installed before R 4.0.0: please re-install it
</code>```

And then I'd try installing it, and it would give me:

```<code>install.packages('tidytext')
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/tidytext_0.2.4.zip'
Content type 'application/zip' length 3008780 bytes (2.9 MB)
downloaded 2.9 MB

package ‘tidytext’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\Ibrahim\AppData\Local\Temp\Rtmpmo5Lza\downloaded_packages
</code>```

Calling it again gives:

```<code>library(tidytext)
Error: package or namespace load failed for ‘tidytext’:
 package ‘tokenizers’ was installed before R 4.0.0: please re-install it
</code>```

And I would keep installing the next dependency and recalling the package until it would finally work.

I tried to automate this with this code I found:

```<code>lib_loc <- "C:/Users/Ibrahim/Documents/R/R-4.0.0/library"
to_install <- unname(installed.packages(lib.loc = lib_loc)[, "Package"])
to_install
install.packages(pkgs = to_install)
install.packages(pkgs = to_install, dependencies=T, INSTALL_opts='--no-lock')
</code>```

And that would create a bunch of .zip files to the directory: C:\Users\Ibrahim\AppData\Local\Temp\Rtmpmo5Lza\downloaded_packages

But after a while, it eventually locks, creating a folder/file called 00LOCK in the initial /library directory, and stop the process.

And I would then delete it, but when I'd run the code again, I guess maybe it redoes many of the files already done, and still eventually locks again. Am I doing anything wrong? Is there a way I can fix this? It's a real pain to do it manually. Should I just reinstall RStudio?

答:
Some R packages really need recompilation after upgrade of R to a newer version. This could be your case. To reinstall and update these old packages (i.e. packages built under an earlier version of R) you can try to run this code in R console:

```<code>update.packages(ask = FALSE,
                checkBuilt = TRUE)
</code>```

The ask parameter prevents R from constantly asking you to confirm every update of every package, while the checkBuilt parameter is to reinstall all packages built under an earlier version of R.

For more information see the documentation or type  ?update.packages in your R console in RStudio. Hope this helps!

Body:
So I used installR on Rstudio to update R to version 4.0.0, and it copied the files of my packages into the library file in the R, the directory being: C:\Users\Ibrahim\Documents\R\R-4.0.0\library

Whenever I'd call on a package, for example tidytext, it would give me:

library(tidytext)
Error: package or namespace load failed for ‘tidytext’:
 package ‘tidytext’ was installed before R 4.0.0: please re-install it

And then I'd try installing it, and it would give me:

install.packages('tidytext')
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/tidytext_0.2.4.zip'
Content type 'application/zip' length 3008780 bytes (2.9 MB)
downloaded 2.9 MB

package ‘tidytext’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\Ibrahim\AppData\Local\Temp\Rtmpmo5Lza\downloaded_packages

Calling it again gives:

library(tidytext)
Error: package or namespace load failed for ‘tidytext’:
 package ‘tokenizers’ was installed before R 4.0.0: please re-install it

And I would keep installing the next dependency and recalling the package until it would finally work.

I tried to automate this with this code I found:

lib_loc <- "C:/Users/Ibrahim/Documents/R/R-4.0.0/library"
to_install <- unname(installed.packages(lib.loc = lib_loc)[, "Package"])
to_install
install.packages(pkgs = to_install)
install.packages(pkgs = to_install, dependencies=T, INSTALL_opts='--no-lock')

And that would create a bunch of .zip files to the directory: C:\Users\Ibrahim\AppData\Local\Temp\Rtmpmo5Lza\downloaded_packages

But after a while, it eventually locks, creating a folder/file called 00LOCK in the initial /library directory, and stop the process.

And I would then delete it, but when I'd run the code again, I guess maybe it redoes many of the files already done, and still eventually locks again. Am I doing anything wrong? Is there a way I can fix this? It's a real pain to do it manually. Should I just reinstall RStudio?

Body:
Some R packages really need recompilation after upgrade of R to a newer version. This could be your case. To reinstall and update these old packages (i.e. packages built under an earlier version of R) you can try to run this code in R console:

update.packages(ask = FALSE,
                checkBuilt = TRUE)

The ask parameter prevents R from constantly asking you to confirm every update of every package, while the checkBuilt parameter is to reinstall all packages built under an earlier version of R.

For more information see the documentation or type  ?update.packages in your R console in RStudio. Hope this helps!


问:
How to parse nested parenthesis only in first level in C#
I would like to write C# code that parses nested parenthesis to array elements, but only on first level. An example is needed for sure:

I want this string:

```<code>"(example (to (parsing nested paren) but) (first lvl only))"
</code>```

tp be parsed into:

```<code>["example", "(to (parsing nested paren) but)", "(first lvl only)"]
</code>```

I was thinking about using regex but can't figure out how to properly use them without implementing this behaviour from scratch.

In the case of malformed inputs I would like to return an empty array, or an array ["error"]

答:
RegEx is not recursive. You either count bracket level, or recurse.

An non-recursive parser loop I tested for the example you show is..

```<code>    string SplitFirstLevel(string s)
    {
        List<string> result = new List<string>();
        int p = 0, level = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '(')
            {
                level++;
                if (level == 1) p = i + 1;
                if (level == 2)
                {
                    result.Add('"' + s.Substring(p, i - p) + '"');
                    p = i;
                }
            }
            if (s[i] == ')')
                if (--level == 0)
                  result.Add('"' + s.Substring(p, i - p) + '"');
        }
        return "[" + String.Join(",", result) + "]";
    }
</code>```

Note: after some more testing, I see your specification is unclear. How to delimit orphaned level 1 terms, that is terms without bracketing ?

For example, my parser translates

```<code>   (example (to (parsing nested paren) but) (first lvl only))
   to:
   ["example ","(to (parsing nested paren) but) ","(first lvl only)"]
</code>```

and

```<code>   (example (to (parsing nested paren)) but (first lvl only))
   to:
   ["example ","(to (parsing nested paren)) but ","(first lvl only)"]
</code>```

In either case, "example" gets a separate term, while "but" is grouped with the first term. In the first example this is logical, it is in the bracketing, but it may be unwanted behaviour in the second case, where "but" should be separated, like "example", which also has no bracketing (?)

Body:
I would like to write C# code that parses nested parenthesis to array elements, but only on first level. An example is needed for sure:

I want this string:

"(example (to (parsing nested paren) but) (first lvl only))"

tp be parsed into:

["example", "(to (parsing nested paren) but)", "(first lvl only)"]

I was thinking about using regex but can't figure out how to properly use them without implementing this behaviour from scratch.

In the case of malformed inputs I would like to return an empty array, or an array ["error"]

Body:
RegEx is not recursive. You either count bracket level, or recurse.

An non-recursive parser loop I tested for the example you show is..

    string SplitFirstLevel(string s)
    {
        List<string> result = new List<string>();
        int p = 0, level = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '(')
            {
                level++;
                if (level == 1) p = i + 1;
                if (level == 2)
                {
                    result.Add('"' + s.Substring(p, i - p) + '"');
                    p = i;
                }
            }
            if (s[i] == ')')
                if (--level == 0)
                  result.Add('"' + s.Substring(p, i - p) + '"');
        }
        return "[" + String.Join(",", result) + "]";
    }

Note: after some more testing, I see your specification is unclear. How to delimit orphaned level 1 terms, that is terms without bracketing ?

For example, my parser translates

   (example (to (parsing nested paren) but) (first lvl only))
   to:
   ["example ","(to (parsing nested paren) but) ","(first lvl only)"]

and

   (example (to (parsing nested paren)) but (first lvl only))
   to:
   ["example ","(to (parsing nested paren)) but ","(first lvl only)"]

In either case, "example" gets a separate term, while "but" is grouped with the first term. In the first example this is logical, it is in the bracketing, but it may be unwanted behaviour in the second case, where "but" should be separated, like "example", which also has no bracketing (?)


答:
Java & C# both share this same syntax

The syntax probably stems from C/C++ which is the 'root' of Java & C#

Yes, you can also have zero initializers and end conditions for your for loop.

Whether or not it is bad practice really depends on how it is used. You can create quite cryptic code using this technique, however, it does not mean that when used correctly it is perfectly acceptable.

I doubt it!

Title: Whats possible in a for loop


问:
Sharing a photo to LinkedIn with URL Schemes
I'm trying to share an image from my iOS app to LinkedIn as a post - if the LinkedIn app was available/downloaded on the device. Is there a way without using the LinkedIn iOS SDK to share this content via url schemes like Instagram Stories? I could not find any solution addressing this and the documentation from LinkedIn is bare at best..

My IG Story code for reference:

```<code>guard let urlScheme = URL(string: "instagram-stories://share"),
UIApplication.shared.canOpenURL(urlScheme) else { return }

let pasteboardItems = [["com.instagram.sharedSticker.backgroundImage": pngImage]]
let pasteboardOptions: [UIPasteboard.OptionsKey: Any] = [.expirationDate: Date().addingTimeInterval(60 * 5)]

UIPasteboard.general.setItems(pasteboardItems, options: pasteboardOptions)
UIApplication.shared.open(urlScheme)
</code>```

答:
To share on LinkedIn, just insert the URL to the image you want to share using the URL format below...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official Microsoft Linkedin Share Documentation.

For example, here I am sharing the Google logo...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fbranding%2Fgooglelogo%2F2x%2Fgooglelogo_color_272x92dp.png
</code>```

The logo wasn't really sized for being an icon, but anyway, here are the results:

Hope this helps!

Body:
I'm trying to share an image from my iOS app to LinkedIn as a post - if the LinkedIn app was available/downloaded on the device. Is there a way without using the LinkedIn iOS SDK to share this content via url schemes like Instagram Stories? I could not find any solution addressing this and the documentation from LinkedIn is bare at best..

My IG Story code for reference:

guard let urlScheme = URL(string: "instagram-stories://share"),
UIApplication.shared.canOpenURL(urlScheme) else { return }

let pasteboardItems = [["com.instagram.sharedSticker.backgroundImage": pngImage]]
let pasteboardOptions: [UIPasteboard.OptionsKey: Any] = [.expirationDate: Date().addingTimeInterval(60 * 5)]

UIPasteboard.general.setItems(pasteboardItems, options: pasteboardOptions)
UIApplication.shared.open(urlScheme)

Body:
To share on LinkedIn, just insert the URL to the image you want to share using the URL format below...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official Microsoft Linkedin Share Documentation.

For example, here I am sharing the Google logo...

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fbranding%2Fgooglelogo%2F2x%2Fgooglelogo_color_272x92dp.png

The logo wasn't really sized for being an icon, but anyway, here are the results:

Hope this helps!


问:
find how many elements from the beginning of the array must be added to get a total of more than 10
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

```<code>let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);
</code>```

答:
You could find the index and add one.

This iteration stops if the comparison is true.

let array = [2, 3, 1, 0, 4, 5, 4],
    index = array.find((sum => value => (sum += value) > 10)(0));

console.log(index + 1);```

Body:
I have an array with numbers. Need to find how many elements from the beginning of the array must be added to get a total of more than 10. In the code I have to use reduce

    let arr = [2, 3, 1, 0, 4, 5, 4];

The console in this case must display the number 6.

My code didn't work:

let arr = [2, 3, 1, 0, 4, 5, 4];
let sumNumber = arr.reduce((sum, elem, index) => {

    let ourSum = 0;
    while (ourSum <= 10) {
        return sum + elem;
    }
    index++

}, 0)
console.log(sumNumber);


问:
Install libpcap
Can someone explain me how to install libpcap?  I downloaded libpcap-1.9.1 from official site (tcpdump). There are a lot of files and i cant understand what to do. i tried:

```<code>project(test)
set(CMAKE_CXX_STANDARD 14)
include_directories(libpcap-1.9.1)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/libpcap-1.9.1/cmake/Modules")
find_package(Packet REQUIRED)
add_executable(${PROJECT_NAME} main.cpp )
target_link_libraries(${PROJECT_NAME} ${PACKET_LIBRARY})
</code>```

But it doesnt work

答:
Just use add_subdirectory() with target_link_libraries():

```<code>project(test)

set(CMAKE_CXX_STANDARD 14)

include_directories(libpcap-1.9.1)

add_subdirectory(libpcap-1.9.1)

add_executable(${PROJECT_NAME} main.cpp )

target_link_libraries(${PROJECT_NAME} PRIVATE pcap)
</code>```

Title: Install libpcap

Body:
Can someone explain me how to install libpcap?  I downloaded libpcap-1.9.1 from official site (tcpdump). There are a lot of files and i cant understand what to do. i tried:

project(test)
set(CMAKE_CXX_STANDARD 14)
include_directories(libpcap-1.9.1)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/libpcap-1.9.1/cmake/Modules")
find_package(Packet REQUIRED)
add_executable(${PROJECT_NAME} main.cpp )
target_link_libraries(${PROJECT_NAME} ${PACKET_LIBRARY})

But it doesnt work

Body:
Just use add_subdirectory() with target_link_libraries():

project(test)

set(CMAKE_CXX_STANDARD 14)

include_directories(libpcap-1.9.1)

add_subdirectory(libpcap-1.9.1)

add_executable(${PROJECT_NAME} main.cpp )

target_link_libraries(${PROJECT_NAME} PRIVATE pcap)


问:
Mail from iSeries with attachment
Is there a way to send an email from an iSeries terminal, adding an attachment from the IFS? I know how to send a normal email using the SNDDST utility.</p>

答:
I have not looked in a while but there should be some unixy mail utilities on i5/OS that QSH could use. If not, it's supposedly a simple matter to port one. Look here for ideas: http://www.shelldorado.com/articles/mailattachments.html

But I like the JavaMail idea better. Just a quick google yields a site that has examples of JavaMail usage: http://www.javaworld.com/javaworld/jw-10-2001/jw-1026-javamail.html

With JavaMail you can also read mail if that could also be useful.

Update: You say you can already add attachments from the IFS. The command CATSPLF (part of QSH utilities) can retrieve spool files and write them to standard output. Which means you can transfer spool files to the IFS. But you have to know a lot about the job that created them.

Like:```
    catsplf ... > /my/files/path
```
I found this at http://www.mcpressonline.com/tips-techniques/cl/techtip-read-printer-output-with-qshell.html.
CATSPLF was introduced in V5R3.

Title: Mail from iSeries with attachment

Body:
I have not looked in a while but there should be some unixy mail utilities on i5/OS that QSH could use. If not, it's supposedly a simple matter to port one. Look here for ideas: http://www.shelldorado.com/articles/mailattachments.html

But I like the JavaMail idea better. Just a quick google yields a site that has examples of JavaMail usage: http://www.javaworld.com/javaworld/jw-10-2001/jw-1026-javamail.html

With JavaMail you can also read mail if that could also be useful.

Update: You say you can already add attachments from the IFS. The command CATSPLF (part of QSH utilities) can retrieve spool files and write them to standard output. Which means you can transfer spool files to the IFS. But you have to know a lot about the job that created them.

Like:

    catsplf ... > /my/files/path

I found this at http://www.mcpressonline.com/tips-techniques/cl/techtip-read-printer-output-with-qshell.html.
CATSPLF was introduced in V5R3.

OwnerDisplayName: Allen

LastEditorDisplayName: Allen


问:
Not able to create a SignUp page using Django
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

```<code>def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)
</code>```

forms.py:

```<code>class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']
</code>```

models.py:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'
</code>```

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.

答: If this isn't a form based on a model, don't inherit from forms.ModelForm, just use an ordinary forms.Form.

Body:
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)

forms.py:

class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.


问:
How do I declare and initialize an array in Java?
How do I declare and initialize an array in Java?</p>

答:
One another full example with a movies class:</p>
```<code>public class A {

    public static void main(String[] args) {

        class Movie {

            String movieName;
            String genre;
            String movieType;
            String year;
            String ageRating;
            String rating;

            public Movie(String [] str)
            {
                this.movieName = str[0];
                this.genre = str[1];
                this.movieType = str[2];
                this.year = str[3];
                this.ageRating = str[4];
                this.rating = str[5];
            }
        }

        String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};

        Movie mv = new Movie(movieDetailArr);

        System.out.println("Movie Name: "+ mv.movieName);
        System.out.println("Movie genre: "+ mv.genre);
        System.out.println("Movie type: "+ mv.movieType);
        System.out.println("Movie year: "+ mv.year);
        System.out.println("Movie age : "+ mv.ageRating);
        System.out.println("Movie  rating: "+ mv.rating);
    }
}
</code>```

Body:
One another full example with a movies class:

public class A {

    public static void main(String[] args) {

        class Movie {

            String movieName;
            String genre;
            String movieType;
            String year;
            String ageRating;
            String rating;

            public Movie(String [] str)
            {
                this.movieName = str[0];
                this.genre = str[1];
                this.movieType = str[2];
                this.year = str[3];
                this.ageRating = str[4];
                this.rating = str[5];
            }
        }

        String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};

        Movie mv = new Movie(movieDetailArr);

        System.out.println("Movie Name: "+ mv.movieName);
        System.out.println("Movie genre: "+ mv.genre);
        System.out.println("Movie type: "+ mv.movieType);
        System.out.println("Movie year: "+ mv.year);
        System.out.println("Movie age : "+ mv.ageRating);
        System.out.println("Movie  rating: "+ mv.rating);
    }
}


问:
error solving Balanced Brackets check from hacker rank using stack
while solving Balanced Brackets check  from hacker rank using stack, the error I am getting is :

```<code>Solution.cpp: In function ‘std::__cxx11::string isBalanced(std::__cxx11::string)’:
Solution.cpp:7:17: error: control reaches end of non-void function [-Werror=return-type]
     stack<char> c;
                 ^
cc1plus: some warnings being treated as errors
</code>```

But it works fine on CodeChef compiler.

```<code>string isBalanced(string s) {
    stack<char> c;

    for(int i=0;s[i]!='\0';i++)
    {
        if(s[0]=='}' || s[0]==')' || s[0]==']')
        return "NO";
        else if(s[i]=='{' || s[i]=='(' || s[i]=='[')
        {
            c.push(s[i]);
        }
        else if((c.top()=='{' && s[i]=='}') || (c.top()=='(' && s[i]==')') || (c.top()=='[' && s[i]==']')){
            c.pop();
        }
        else
        return "NO";
    }
    if (c.empty())
        return "YES";
    }
</code>```

答:
As the error message says, your function does not always return a value. You could fix that by returning "NO", in the case that your stack is not empty at the end of the function:

```<code>if (c.empty())
    return "YES";
return "NO";
</code>```

Note that the return value of "NO" will only be returned in the case that "YES" is not returned.

Body:
while solving Balanced Brackets check  from hacker rank using stack, the error I am getting is :

Solution.cpp: In function ‘std::__cxx11::string isBalanced(std::__cxx11::string)’:
Solution.cpp:7:17: error: control reaches end of non-void function [-Werror=return-type]
     stack<char> c;
                 ^
cc1plus: some warnings being treated as errors

But it works fine on CodeChef compiler.

string isBalanced(string s) {
    stack<char> c;

    for(int i=0;s[i]!='\0';i++)
    {
        if(s[0]=='}' || s[0]==')' || s[0]==']')
        return "NO";
        else if(s[i]=='{' || s[i]=='(' || s[i]=='[')
        {
            c.push(s[i]);
        }
        else if((c.top()=='{' && s[i]=='}') || (c.top()=='(' && s[i]==')') || (c.top()=='[' && s[i]==']')){
            c.pop();
        }
        else
        return "NO";
    }
    if (c.empty())
        return "YES";
    }

Body:
As the error message says, your function does not always return a value. You could fix that by returning "NO", in the case that your stack is not empty at the end of the function:

if (c.empty())
    return "YES";
return "NO";

Note that the return value of "NO" will only be returned in the case that "YES" is not returned.


问:
Control onclicklistener in autolink enabled textview
I am using a TextView for which I have set autolink="web" property in XML file. I have also implemented the onClickListener for this TextView. The problem is, when the text in TextView contains a hyperlink, and if I touch that link, the link opens in browser but simultaneously the onClickListener triggers too.  I don't want that.

What I want is, if I touch the hyperlink the clickListener should not fire. It should only fire if I touch the part of the text that is not hyperlinked. Any suggestion?

答:
Kotlin version:

Similar to older answers in Java. Simply:

In Layout Editor/XML, add the types of things you'd like to hyperlink via the autoLink property.

```<code><TextView
    ...
    android:autoLink="web|phone|email" />
</code>```

Add an onClickListener to your TextView in Kotlin code to handle clicks on the plain text part.  Check to make sure the person didn't click on a link by checking selectionStart and selectionEnd.

```<code>binding.messageText.setOnClickListener { view ->
    if (binding.messageText.selectionStart == -1 && binding.messageText.selectionEnd == -1) {
        // do whatever you want when they click on the plain text part
    }
}
</code>```

Body:
Kotlin version:

Similar to older answers in Java. Simply:

In Layout Editor/XML, add the types of things you'd like to hyperlink via the autoLink property.

<TextView
    ...
    android:autoLink="web|phone|email" />

Add an onClickListener to your TextView in Kotlin code to handle clicks on the plain text part.  Check to make sure the person didn't click on a link by checking selectionStart and selectionEnd.

binding.messageText.setOnClickListener { view ->
    if (binding.messageText.selectionStart == -1 && binding.messageText.selectionEnd == -1) {
        // do whatever you want when they click on the plain text part
    }
}


问:
Counting duplicate value only once in excel or VBA , will auto calculate my total of room type when i adding new room
this is my Room record. i need to put formula or VBA code to count my type of room.</p>

```<code>BedNum  RoomNum  RoomType         RoomType    totalcount
1001#1   1001     Studio           Studio         3
1001#2   1001     Studio           2br1cr         2
1001#3   1001     Studio           3br1cr         1
1002#1   1002     2br1cr
1002#2   1002     2br1cr
1003#1   1003     3br1cr
1003#2   1003     3br1cr
1004#1   1004     Studio
1004#2   1004     Studio
1005#1   1005     2br1cr
1005#2   1005     2br1cr
1006#1   1006     Studio
1006#2   1006     Studio
---------------------------------------------------------
above list is my Excel record , i wanna count in the rightside with formula or either VBA code ,
my RoomNumber will always increase and adding new room , what i want is total up the count of my roomtype.
</code>```

答:
As said in my hint you can use "database" technology to do this. I used the code below to achieve the following result

I started with the following layout

The sheet shResult is empty. I renamed the codenames accordingly!

Reading on codename

Reading on ADO

```<code>Sub ReadFromWorksheetADO()

    ' Goto Tools/Reference and
    ' add Microsoft ActiveX Data Objects
    Dim conn As New ADODB.Connection

    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES;"";"

    Dim query As String
    ' The name in the tab has to be shData
    query = "Select ID, Name From [shData$] GROUP BY Name,ID"

    Dim rs As New ADODB.Recordset
    rs.Open query, conn

    ' Here I use the codename of the second sheet shResult!!
    With shResult
        .Cells.ClearContents
        Dim i As Long
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i
        .Range("A2").CopyFromRecordset rs
    End With
    rs.Close

    ' Now I take the result of the first query and count
    query = "Select Name, count(ID) as CountOf From [shResult$] GROUP BY Name"
    rs.Open query, conn

    ' Here I use the codename of the first sheet shData
    With shData
        .Range("D2").CopyFromRecordset rs
    End With

End Sub
</code>```

PS1 I just saw that you changed your post but you just need to modify the code with the right fieldnames in order to get the following result

Modified code

```<code>Sub ReadFromWorksheetADO_B()

    ' Goto Tools/reference and
    ' add Microsoft ActiveX Dataa Objects
    Dim conn As New ADODB.Connection

    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES;"";"

    Dim query As String
    ' The name in the tab has to be shData
    query = "Select RoomNum, RoomType From [shData$] GROUP BY Roomtype,RoomNum"

    Dim rs As New ADODB.Recordset
    rs.Open query, conn

    ' Here I use the codename of the first sheet shResult!!
    With shResult
        .Cells.ClearContents
        Dim i As Long
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i
        .Range("A2").CopyFromRecordset rs
    End With
    rs.Close

    ' Now I take the result of the first query and count
    query = "Select RoomType, count(RoomNum) as CountOf From [shResult$] GROUP BY RoomType"
    rs.Open query, conn

    ' Here I use the codename of the first sheet
    With shData
        .Range("E2").CopyFromRecordset rs
    End With

End Sub
</code>```

PS2: One can combine the two queries above in one and one would save the extra sheet.

```<code>query = "Select RoomType, count(RoomNum) From (Select RoomNum, RoomType From [shData$] " & _
                "GROUP BY Roomtype,RoomNum) Group by RoomType"
</code>```

And the final code looks like that then

```<code>Sub ReadFromWorksheetADO_C()

    ' Goto Tools/reference and
    ' add Microsoft ActiveX Dataa Objects
    Dim conn As New ADODB.Connection

    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES;"";"

    Dim query As String
    ' The name in the tab has to be shData
    query = "Select RoomType, count(RoomNum) From (Select RoomNum, RoomType From [shData$] " & _
                        "GROUP BY Roomtype,RoomNum) Group by RoomType"

    Dim rs As New ADODB.Recordset
    rs.Open query, conn

    ' Here I use the codename of the first sheet
    With shData
        .Range("E2").CopyFromRecordset rs
    End With

End Sub
</code>```

Body:
this is my Room record. i need to put formula or VBA code to count my type of room.

BedNum  RoomNum  RoomType         RoomType    totalcount
1001#1   1001     Studio           Studio         3
1001#2   1001     Studio           2br1cr         2
1001#3   1001     Studio           3br1cr         1
1002#1   1002     2br1cr
1002#2   1002     2br1cr
1003#1   1003     3br1cr
1003#2   1003     3br1cr
1004#1   1004     Studio
1004#2   1004     Studio
1005#1   1005     2br1cr
1005#2   1005     2br1cr
1006#1   1006     Studio
1006#2   1006     Studio
---------------------------------------------------------
above list is my Excel record , i wanna count in the rightside with formula or either VBA code ,
my RoomNumber will always increase and adding new room , what i want is total up the count of my roomtype.

Body:
As said in my hint you can use "database" technology to do this. I used the code below to achieve the following result

I started with the following layout

The sheet shResult is empty. I renamed the codenames accordingly!

Reading on codename

Reading on ADO

Sub ReadFromWorksheetADO()

    ' Goto Tools/Reference and
    ' add Microsoft ActiveX Data Objects
    Dim conn As New ADODB.Connection

    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES;"";"

    Dim query As String
    ' The name in the tab has to be shData
    query = "Select ID, Name From [shData$] GROUP BY Name,ID"

    Dim rs As New ADODB.Recordset
    rs.Open query, conn

    ' Here I use the codename of the second sheet shResult!!
    With shResult
        .Cells.ClearContents
        Dim i As Long
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i
        .Range("A2").CopyFromRecordset rs
    End With
    rs.Close

    ' Now I take the result of the first query and count
    query = "Select Name, count(ID) as CountOf From [shResult$] GROUP BY Name"
    rs.Open query, conn

    ' Here I use the codename of the first sheet shData
    With shData
        .Range("D2").CopyFromRecordset rs
    End With

End Sub

PS1 I just saw that you changed your post but you just need to modify the code with the right fieldnames in order to get the following result

Modified code

Sub ReadFromWorksheetADO_B()

    ' Goto Tools/reference and
    ' add Microsoft ActiveX Dataa Objects
    Dim conn As New ADODB.Connection

    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES;"";"

    Dim query As String
    ' The name in the tab has to be shData
    query = "Select RoomNum, RoomType From [shData$] GROUP BY Roomtype,RoomNum"

    Dim rs As New ADODB.Recordset
    rs.Open query, conn

    ' Here I use the codename of the first sheet shResult!!
    With shResult
        .Cells.ClearContents
        Dim i As Long
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i
        .Range("A2").CopyFromRecordset rs
    End With
    rs.Close

    ' Now I take the result of the first query and count
    query = "Select RoomType, count(RoomNum) as CountOf From [shResult$] GROUP BY RoomType"
    rs.Open query, conn

    ' Here I use the codename of the first sheet
    With shData
        .Range("E2").CopyFromRecordset rs
    End With

End Sub

PS2: One can combine the two queries above in one and one would save the extra sheet.

query = "Select RoomType, count(RoomNum) From (Select RoomNum, RoomType From [shData$] " & _
                "GROUP BY Roomtype,RoomNum) Group by RoomType"

And the final code looks like that then

Sub ReadFromWorksheetADO_C()

    ' Goto Tools/reference and
    ' add Microsoft ActiveX Dataa Objects
    Dim conn As New ADODB.Connection

    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=YES;"";"

    Dim query As String
    ' The name in the tab has to be shData
    query = "Select RoomType, count(RoomNum) From (Select RoomNum, RoomType From [shData$] " & _
                        "GROUP BY Roomtype,RoomNum) Group by RoomType"

    Dim rs As New ADODB.Recordset
    rs.Open query, conn

    ' Here I use the codename of the first sheet
    With shData
        .Range("E2").CopyFromRecordset rs
    End With

End Sub