问:
Cucumber feature on form with Captcha
If you form has captcha (i'm using humanizer gem). How do you fill up form and send and get the expected result when writing cucumber feature.

```<code>Scenario: Sign Up with Valid Data
  Given I am not authenticated
  And I am on the sign in page
  When I follow "Sign up"
  And I fill in the following:
    | Name                   | Administrator            |
    | Email                  | admin@admin.com          |
    | Password               | 123456                   |
    | Password confirmation  | 123456                   |
  And I fill in the captcha correctly
  And I press "Sign Up"
  Then I should be on the new_company page
  And I should see "Hello Manoj"
</code>```

Now i can write a step definition matching /^I fill up catcha correctly$/ but what must be put there?

Be gentle, i'm new to cucumber and it's been frustrating so far. I'm not new to Rails or programming otherwise.

答:
You're right, Aditya. Putting environment dependent code in models is not good solution. But you can "stub" bypass_humanizer? when needed:

```<code># user.rb
class User
  include Humanizer

  require_human_on :create, :unless => :bypass_humanizer?

  protected

  def bypass_humanizer?
    false
  end
end

# step definitions for your scenarion
And /^I fill in the captcha correctly$/ do
  # from now any instance of User class will skip require_human_on validator
  User.any_instance.stubs(:bypass_humanizer?).returns(true)
end

# in Gemfile
group :development, :test do
  gem "mocha"
end
</code>```

Now you have a model with environment agnostic code and you can put it in the specific state any time you need (for testing, of course).

Title: Cucumber feature on form with Captcha

Body:
If you form has captcha (i'm using humanizer gem). How do you fill up form and send and get the expected result when writing cucumber feature.

Scenario: Sign Up with Valid Data
  Given I am not authenticated
  And I am on the sign in page
  When I follow "Sign up"
  And I fill in the following:
    | Name                   | Administrator            |
    | Email                  | admin@admin.com          |
    | Password               | 123456                   |
    | Password confirmation  | 123456                   |
  And I fill in the captcha correctly
  And I press "Sign Up"
  Then I should be on the new_company page
  And I should see "Hello Manoj"

Now i can write a step definition matching /^I fill up catcha correctly$/ but what must be put there?

Be gentle, i'm new to cucumber and it's been frustrating so far. I'm not new to Rails or programming otherwise.

Body:
You're right, Aditya. Putting environment dependent code in models is not good solution. But you can "stub" bypass_humanizer? when needed:

# user.rb
class User
  include Humanizer

  require_human_on :create, :unless => :bypass_humanizer?

  protected

  def bypass_humanizer?
    false
  end
end

# step definitions for your scenarion
And /^I fill in the captcha correctly$/ do
  # from now any instance of User class will skip require_human_on validator
  User.any_instance.stubs(:bypass_humanizer?).returns(true)
end

# in Gemfile
group :development, :test do
  gem "mocha"
end

Now you have a model with environment agnostic code and you can put it in the specific state any time you need (for testing, of course).


来源: stackexchange

问:
How to know which process is changing a file in linux
I'm using an automation tool to build a virtual machine. During the this automation a config file (/etc/myprogram/cofig.ini) is becoming empty.

This file's contents are required complete the automation, but I'm clueless which process is emptying the file.

I want to monitor a file and list the name of processes changed the contents of the file.

I'm using Ubuntu 16.04.

I saw some questions in Stackoverflow but did help. I tried to use audictl inotify and watchdog . Please let me know any better way to do this. Is there a way to do this using python.

答:
you can use lsof. this command is for find out what processes currently have the file open.
if process opening the file, writing to it, and then closing it you can use auditing.

```<code>/sbin/auditctl -w /etc/myprogram/cofig.ini -p war -k config.ini-file

-w watch etc/myprogram/cofig.ini
-p warx watch for write, attribute change, execute or read events
-k config.ini-file is a search key.
</code>```

wait till the file change then use

```<code>/sbin/ausearch -f /etc/myprogram/cofig.ini | more
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can use lsof. this command is for find out what processes currently have the file open.
if process opening the file, writing to it, and then closing it you can use auditing.

/sbin/auditctl -w /etc/myprogram/cofig.ini -p war -k config.ini-file

-w watch etc/myprogram/cofig.ini
-p warx watch for write, attribute change, execute or read events
-k config.ini-file is a search key.

wait till the file change then use

/sbin/ausearch -f /etc/myprogram/cofig.ini | more


问:
Comparing two arrays of objects, and update the value of the second one. Very slow
Below is my working code example, but the problem i'm having is when I have over 100k records this script takes a very long time to run and I was wondering if there was a faster way of doing this.

Note: I have two arrays of objects and I need to set the second array's object names based on the first one's. The IDs will match between the two and the order will be random.

```<code>const _ = require('lodash');

let res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

let res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

_.forEach(res1, function(data1) {
  _.forEach(res2, function(data2) {
    if (data1.id === data2.id) {
      data2.name = data1.name;
    }
  });
});

// res2 = [{id:2, name:'bill'},{id:4, name:'Jill'}];
</code>```

答:
Create a map by id of res1, and than iterate the 2nd array, and replace the name of each id you find the res1map.

const res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

const res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

const res1Map = _.keyBy(res1, 'id');

res2.forEach((o) => res1Map[o.id] && (o.name = res1Map[o.id].name));

console.log(res2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
Below is my working code example, but the problem i'm having is when I have over 100k records this script takes a very long time to run and I was wondering if there was a faster way of doing this.

Note: I have two arrays of objects and I need to set the second array's object names based on the first one's. The IDs will match between the two and the order will be random.

const _ = require('lodash');

let res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

let res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

_.forEach(res1, function(data1) {
  _.forEach(res2, function(data2) {
    if (data1.id === data2.id) {
      data2.name = data1.name;
    }
  });
});

// res2 = [{id:2, name:'bill'},{id:4, name:'Jill'}];

Body:
Create a map by id of res1, and than iterate the 2nd array, and replace the name of each id you find the res1map.

const res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

const res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

const res1Map = _.keyBy(res1, 'id');

res2.forEach((o) => res1Map[o.id] && (o.name = res1Map[o.id].name));

console.log(res2);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
ScriptManager adding script multiple times to page (duplicates)
This is the exact same question as this unanswered one from May.

(edit) Note: this unanswered post exactly describes the behavior - extra scripts being added in the  by ScriptManager.RegisterClientScriptBlock in a usercontrol, in an UpdatePanel, is causing duplicates. C# .NET 4.0. The page is structured like this:

```<code>MasterPage
   Page
      UserControl1 (ascx) - loaded in code by Page
         UpdatePanel
            UserControl2 (ascx) - loaded in code by UserControl1
</code>```

The first time the script is added as expected, in the body. The code, simply, in the UserControl2 OnInit:

```<code>ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "myscript", script, true);
</code>```

I've also tried referencing "this" instead of page, which doesn't really make sense since I don't want the same script keys duplicated on the page if the usercontrol is loaded multiple times on a page, but it didn't work anyway.

After a partial postback, the script is added again - but curiously in the  of the page, not the body, and interestingly, lacking the normal //<![CDATA[...//]]> wrapper that asp.net usually adds.

Another script which is added by UserControl1 is duplicated exactly the same way after a partial postback.

Does anyone know why this is happening?

答:
Though I can't find much discussion about this one way or the other it seems that ScriptManager is stateless. So adding a script with the same tag across partial postbacks will result in duplicates. In practice (for me) this is not desired behavior a lot of the time, since one would assume that any script you register more than once inside a UserControl with the same tag would be a duplicate and should not be re-registered. If you really wanted to register a new script (as a result of what happened after the partial postback, e.g.) I would think you should be required to give it a new tag for ScriptManager to register it again.

My solution is to create a custom ScriptManager for use in UserControls that has methods that will register a script only the first time the control is loaded and maintain state information with ViewState. That is, I keep a list of tags for scripts intended to be registered only the first time and persist it across postbacks, and only re-register scripts that aren't found in that list. Scripts which are just general support for the usercontrol and should only be registered once are tracked this way.

The reason I can't just use IsPostBack is that I load usercontrols dynamically using Page.LoadControl sometimes. It is not guaranteed that the control will be loaded the first time the whole page is loaded. That is, it could be loaded for the first time on a postback. So if I just used IsPostBack the scripts may never be registered.

ContentLicense: CC BY-SA 2.5

Body:
This is the exact same question as this unanswered one from May.

(edit) Note: this unanswered post exactly describes the behavior - extra scripts being added in the  by ScriptManager.RegisterClientScriptBlock in a usercontrol, in an UpdatePanel, is causing duplicates. C# .NET 4.0. The page is structured like this:

MasterPage
   Page
      UserControl1 (ascx) - loaded in code by Page
         UpdatePanel
            UserControl2 (ascx) - loaded in code by UserControl1

The first time the script is added as expected, in the body. The code, simply, in the UserControl2 OnInit:

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "myscript", script, true);

I've also tried referencing "this" instead of page, which doesn't really make sense since I don't want the same script keys duplicated on the page if the usercontrol is loaded multiple times on a page, but it didn't work anyway.

After a partial postback, the script is added again - but curiously in the  of the page, not the body, and interestingly, lacking the normal //<![CDATA[...//]]> wrapper that asp.net usually adds.

Another script which is added by UserControl1 is duplicated exactly the same way after a partial postback.

Does anyone know why this is happening?


问:
Setting hover for items in recyclerview
I have a listview in that I have recylerview of cardviews...when i select any of them then a floating layout should be there which has 3 buttons. I am using this library enter link description here.

I am using this library in a adapter and have set that adapter in the activity, but as soon i go to activity the app crashes with NullPointerException. the error arises is that when i inflate two xml files but i want to inflate the abc_card_view_video first then clicking on any of it the new file hover_card_view should inflate but the old file should be in background.

help me get out of it. Thanks

```<code>     public class LessonVideoAdapter extends RecyclerView.Adapter<LessonDataHolder> {

            private List<VideoList> slipList;
            private Context mContext;
            public BlurLayout samplelayout;

            public LessonVideoAdapter() {
                slipList = new ArrayList<>();
                slipList.add(new VideoList("Chapter 1", R.drawable.demo_one));
                slipList.add(new VideoList("Chapter 2", R.drawable.demo_two));
                slipList.add(new VideoList("Chapter 3", R.drawable.demo_one));

            }

            @Override
            public LessonDataHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                Context context = parent.getContext();
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.abc_card_view_video, parent, false);
return new LessonDataHolder(view);
  }

            @Override
            public void onBindViewHolder(LessonDataHolder holder, int position) {
                VideoList s = slipList.get(position);
                holder.bindSlip(s);

            }
            @Override
            public int getItemCount() {
                return slipList.size();
            }
        }

        class LessonDataHolder extends RecyclerView.ViewHolder {

            private TextView nameOfSlip;
            private ImageView slipImage;
            private Context context;
            public LessonDataHolder(View itemView) {
                super(itemView);

                context = itemView.getContext();
                nameOfSlip = (TextView) itemView.findViewById(R.id.demoText);
                slipImage = (ImageView) itemView.findViewById(R.id.imageViewDemoVideo);

            }

            public void bindSlip(VideoList videoList) {
                nameOfSlip.setText(videoList.stringSlipName);
                slipImage.setImageResource(videoList.stringImage);
            }
        }

        class VideoList {
            public String stringSlipName;
            public int stringImage;

            public VideoList(String stringSlipName, int stringImage) {
                this.stringImage = stringImage;
                this.stringSlipName = stringSlipName;
            }

        }
</code>```

答:
You should write this code in the listner of on click of items    </p>

```<code> View view = inflater.inflate(R.layout.abc_card_view_video, parent, false);
    samplelayout = (BlurLayout) parent.findViewById(R.id.blur_layout);
                View hover = inflater.inflate(R.layout.hover_card_view, null);
                samplelayout.setHoverView(hover);
</code>```

Title: Setting hover for items in recyclerview

Body:
I have a listview in that I have recylerview of cardviews...when i select any of them then a floating layout should be there which has 3 buttons. I am using this library enter link description here.

I am using this library in a adapter and have set that adapter in the activity, but as soon i go to activity the app crashes with NullPointerException. the error arises is that when i inflate two xml files but i want to inflate the abc_card_view_video first then clicking on any of it the new file hover_card_view should inflate but the old file should be in background.

help me get out of it. Thanks

     public class LessonVideoAdapter extends RecyclerView.Adapter<LessonDataHolder> {

            private List<VideoList> slipList;
            private Context mContext;
            public BlurLayout samplelayout;

            public LessonVideoAdapter() {
                slipList = new ArrayList<>();
                slipList.add(new VideoList("Chapter 1", R.drawable.demo_one));
                slipList.add(new VideoList("Chapter 2", R.drawable.demo_two));
                slipList.add(new VideoList("Chapter 3", R.drawable.demo_one));

            }

            @Override
            public LessonDataHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                Context context = parent.getContext();
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.abc_card_view_video, parent, false);
return new LessonDataHolder(view);
  }

            @Override
            public void onBindViewHolder(LessonDataHolder holder, int position) {
                VideoList s = slipList.get(position);
                holder.bindSlip(s);

            }
            @Override
            public int getItemCount() {
                return slipList.size();
            }
        }

        class LessonDataHolder extends RecyclerView.ViewHolder {

            private TextView nameOfSlip;
            private ImageView slipImage;
            private Context context;
            public LessonDataHolder(View itemView) {
                super(itemView);

                context = itemView.getContext();
                nameOfSlip = (TextView) itemView.findViewById(R.id.demoText);
                slipImage = (ImageView) itemView.findViewById(R.id.imageViewDemoVideo);

            }

            public void bindSlip(VideoList videoList) {
                nameOfSlip.setText(videoList.stringSlipName);
                slipImage.setImageResource(videoList.stringImage);
            }
        }

        class VideoList {
            public String stringSlipName;
            public int stringImage;

            public VideoList(String stringSlipName, int stringImage) {
                this.stringImage = stringImage;
                this.stringSlipName = stringSlipName;
            }

        }

Body:
You should write this code in the listner of on click of items

 View view = inflater.inflate(R.layout.abc_card_view_video, parent, false);
    samplelayout = (BlurLayout) parent.findViewById(R.id.blur_layout);
                View hover = inflater.inflate(R.layout.hover_card_view, null);
                samplelayout.setHoverView(hover);


问:
How to populate the firebaseConfig in a Node.js file?
I am trying to make a Vehicle or Transport  Tracker application project using google map and android device. For this reason I am using Firebase for online database hosting, a custom hosting as server and an android application installed on device.

I am following this Tutorial / Documentation

However I have created

A new Firebase project

Created the Google Map API key

Uploaded all the files into web server from the map folder, the main GitHub project is here

But in this Tutorial / Documentation the Step 5 is confusing to me or I don't know what to do.

In the Step 5 the 4th no. instruction says that : Edit the js/index.js file and populate the firebaseConfig object with the Firebase authentication values.

Well, I have the index.js file under js folder but, how can I populate the firebaseConfig object with the Firebase authentication values to the index.js file in the server?

The index.js is in this link

答:
So step 5 is referring to the the service account JSON file you obtain from the Firebase console. The service account JSON file contains sensitive information such as an RSA private key. Because of the sensitive data within the file, as stated here:

Important: This file contains sensitive information, including your service account's private encryption key. Keep it confidential and never store it in a public repository.

With that said, the tutorial you're following doesn't explain what the firebaseConfig object should look like. However, if you examine the source of the index.js, it explicitly tells you what to do:

```<code>// TODO: See https://firebase.google.com/docs/web/setup for how to configure access to Firebase
const firebaseConfig = {};
</code>```

Visiting that URL linked above yields the following:

```<code>const config = {
  apiKey: "<API_KEY>",
  authDomain: "<PROJECT_ID>.firebaseapp.com",
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
  storageBucket: "<BUCKET>.appspot.com",
}
</code>```

That above is what your firebaseConfig object should look like. However, what's confusing me is why the tutorial is asking you to create a service account to begin with as you don't appear to be needing admin access from a privileged environment such as a server. On top of that, the JSON service account file it asks you download does not even contain the values needed for the firebaseConfig object.

With that said, follow the directions here to add firebase to your web project. Modify firebaseConfig in the index.js to use the credentials you obtain from above. You should be looking at a modal like this to obtain the correct config.

Body:
So step 5 is referring to the the service account JSON file you obtain from the Firebase console. The service account JSON file contains sensitive information such as an RSA private key. Because of the sensitive data within the file, as stated here:

Important: This file contains sensitive information, including your service account's private encryption key. Keep it confidential and never store it in a public repository.

With that said, the tutorial you're following doesn't explain what the firebaseConfig object should look like. However, if you examine the source of the index.js, it explicitly tells you what to do:

// TODO: See https://firebase.google.com/docs/web/setup for how to configure access to Firebase
const firebaseConfig = {};

Visiting that URL linked above yields the following:

const config = {
  apiKey: "<API_KEY>",
  authDomain: "<PROJECT_ID>.firebaseapp.com",
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
  storageBucket: "<BUCKET>.appspot.com",
}

That above is what your firebaseConfig object should look like. However, what's confusing me is why the tutorial is asking you to create a service account to begin with as you don't appear to be needing admin access from a privileged environment such as a server. On top of that, the JSON service account file it asks you download does not even contain the values needed for the firebaseConfig object.

With that said, follow the directions here to add firebase to your web project. Modify firebaseConfig in the index.js to use the credentials you obtain from above. You should be looking at a modal like this to obtain the correct config.


问:
Error - Variable type "X" is an abstract class - c++
I was trying to find the solution to my problem, but I don´t progress in any way, so I need you to help with this.

my abstract class is:

```<code>class Expression
{
public:
    Expression();
    virtual ~Expression();
    virtual double evaluate() const = 0; // calculates and returns the value of expression
    virtual void print() const = 0; // prints the mathematical expression as string
};
</code>```

my Subclass:

```<code>class Const : public Expression
{
public:
    Const(double valIn);

    double evaluate();

    void print() const;

private:
    double val;
};
</code>```

and the line I am having problems with is:

```<code>Const c(4);
</code>```

from the function:

```<code>void testConst()
{
    Const c(4);
    c.print();
    std::cout << " = " << c.evaluate() << std::endl;
}
</code>```

If I should post some more information, I will gladly edit the text. Thank you in advance

答:
Const::evaluate() has a different signature than Expression::evaluate() const. Change your second expression to be const, then it works.

With C++11 there is the new override keyword, where the compiler gives you a better error message, if you have no matching signature in the parent class.
http://en.cppreference.com/w/cpp/language/override

Body:
I was trying to find the solution to my problem, but I don´t progress in any way, so I need you to help with this.

my abstract class is:

class Expression
{
public:
    Expression();
    virtual ~Expression();
    virtual double evaluate() const = 0; // calculates and returns the value of expression
    virtual void print() const = 0; // prints the mathematical expression as string
};

my Subclass:

class Const : public Expression
{
public:
    Const(double valIn);

    double evaluate();

    void print() const;

private:
    double val;
};

and the line I am having problems with is:

Const c(4);

from the function:

void testConst()
{
    Const c(4);
    c.print();
    std::cout << " = " << c.evaluate() << std::endl;
}

If I should post some more information, I will gladly edit the text. Thank you in advance


问:
JS delete duplicated items from array without higher order functions
I know it's a stupid question, but I only learning programming 3 months now.

How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?

Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed

I got this so far, but I think It's a dead end...

```<code>const array = [1, 2, 3, 3, 1];

const removeDuplicate = () => {
    let shortArray = [];
    let index = 0;
    for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array.length; j++) {
            if (i != j) {
                if (array[i] == array[j]) {
                    shortArray[index] += array[i]
                    console.log(array[i]);
                }
            }
        }
    }
    return shortArray;
}

console.log(removeDuplicate());
</code>```

return this:

```<code>1
3
3
1
[ NaN ]
</code>```

thanks!

答:
Use below function:</p>

```<code>    function RemoveDuplicate(array){
    let shortArray = [];
    let index = 0;
    for (let i = 0; i < array.length; i++) {
        let exist=false;
        for(let j=0;j<shortArray.length;j++){
            if(array[i]==shortArray[j]){
                exist=true;
                break;
            }

        }
        if(!exist){
            shortArray[shortArray.length]=array[i];
        }
    }
    return shortArray;
}
</code>```

Body:
I know it's a stupid question, but I only learning programming 3 months now.

How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?

Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed

I got this so far, but I think It's a dead end...

const array = [1, 2, 3, 3, 1];

const removeDuplicate = () => {
    let shortArray = [];
    let index = 0;
    for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array.length; j++) {
            if (i != j) {
                if (array[i] == array[j]) {
                    shortArray[index] += array[i]
                    console.log(array[i]);
                }
            }
        }
    }
    return shortArray;
}

console.log(removeDuplicate());

return this:

1
3
3
1
[ NaN ]

thanks!

Body:
Use below function:

    function RemoveDuplicate(array){
    let shortArray = [];
    let index = 0;
    for (let i = 0; i < array.length; i++) {
        let exist=false;
        for(let j=0;j<shortArray.length;j++){
            if(array[i]==shortArray[j]){
                exist=true;
                break;
            }

        }
        if(!exist){
            shortArray[shortArray.length]=array[i];
        }
    }
    return shortArray;
}


问:
initialize object type constructor oracle
i'm developing a database in oracle.
I've created a supertype, answer, and a subtype, closed_answer. I've added a field "type" to distinguish them, but i want that this field is initialized in a constructor, in order to don't insert this field when i'm inserting a tuple in that table. i've tried, but when i insert a tuple in the table closed_answer, i have to specify the type, but i shouldn't. Where am i wrong?

```<code>create type answertyp as object(

id integer,

text varchar2(50),

type varchar2(25),

constructor function answertyp(self in out nocopy answertyp, text varchar2) return self as result) not final;

create type body answertyp is

constructor function answertyp(self in out nocopy answertyp, text varchar2) return self as result is

begin

self.text := text;

self.type:= 'answer';

return;

end;

end;
/

create type closed_answertyp under closed_answer(

constructor function closed_answertyp(self in out nocopy closed_answertyp, text varchar2) return self as result
) final;

create type body closed_answertyp is

constructor function closed_answertyp (self in out nocopy closed_answertyp, text varchar2) return self as result is

begin

self.text := text;

self.type := 'closed_answer';

return;

end;

end;
</code>```

Now, if i try this query, it says that the number of argument is wrong. Any help? thanks

```<code>insert into answer select closed_answertyp(1, 'ten') from dual;
</code>```

答:
The arguments in the SQL statement don't match the the arguments in the constructors.

Either add id to the constructor:

```<code>constructor function closed_answertyp (self in out nocopy closed_answertyp, id integer, text varchar2) return self as result is
</code>```

Or remove the id from the SQL statement:

```<code>insert into answer select closed_answertyp('ten') from dual;
</code>```

Body:
i'm developing a database in oracle.
I've created a supertype, answer, and a subtype, closed_answer. I've added a field "type" to distinguish them, but i want that this field is initialized in a constructor, in order to don't insert this field when i'm inserting a tuple in that table. i've tried, but when i insert a tuple in the table closed_answer, i have to specify the type, but i shouldn't. Where am i wrong?

create type answertyp as object(

id integer,

text varchar2(50),

type varchar2(25),

constructor function answertyp(self in out nocopy answertyp, text varchar2) return self as result) not final;

create type body answertyp is

constructor function answertyp(self in out nocopy answertyp, text varchar2) return self as result is

begin

self.text := text;

self.type:= 'answer';

return;

end;

end;
/

create type closed_answertyp under closed_answer(

constructor function closed_answertyp(self in out nocopy closed_answertyp, text varchar2) return self as result
) final;

create type body closed_answertyp is

constructor function closed_answertyp (self in out nocopy closed_answertyp, text varchar2) return self as result is

begin

self.text := text;

self.type := 'closed_answer';

return;

end;

end;

Now, if i try this query, it says that the number of argument is wrong. Any help? thanks

insert into answer select closed_answertyp(1, 'ten') from dual;

Body:
The arguments in the SQL statement don't match the the arguments in the constructors.

Either add id to the constructor:

constructor function closed_answertyp (self in out nocopy closed_answertyp, id integer, text varchar2) return self as result is

Or remove the id from the SQL statement:

insert into answer select closed_answertyp('ten') from dual;


问:
Firebase Database with no result
I'm using Firebase Functions for my Alexa skill. This is working as expected, but my data in the database is special and sometime the query can't return any value.

My keys are from 0101 to 1231 (MMDD) and if I query after the highest key, I don't get any callback, because firebase hasn't any data.

How can I set the query, that I find in that case the first >= "0101"?

The currently call is

```<code>admin.database().ref("calendar/birthday")
.orderByKey().startAt(key).limitToFirst(1).once("child_added")
.then(function(snapshot) { ... })
</code>```

My database structure

```<code>"calendar" : {
  "birthday" : {
      "0111" : {
        ... -> 1st person
      },
      ...
      "0710" : {
        ... -> xth person
      },
      ...
      "1109" : {
        ... -> last person
      }
  }
}
</code>```

My Alexa skill should name the next birthday and it will only work until 09. November and after 01. January, because I don't know how to query the data. Or can I structure my data in a better way to find the next birthday?

答:
I think you're looking for: how do I know that there are no birthdays matching my query?

In that case you'll need to listen for the value event. If you attach that with a once(), it fires right away when you attach the query, no matter if there are results or not.

```<code>admin.database().ref("calendar/birthday")
  .orderByKey().startAt(key).limitToFirst(1).once("value")
  .then(function(snapshot) {
    if (!snapshot.exists()) {
      console.log("There are no birthdays on or after "+key);
    }
    else {
      snapshot.forEach(function(daySnapshot) {
        console.log("There is a birthday on "+daySnapshot.key);
      });
    }
  })
</code>```

The exists() detects that there were no results matching the query. The forEach() loop in the else is the result of using value with a query. When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Title: Firebase Database with no result

Body:
I'm using Firebase Functions for my Alexa skill. This is working as expected, but my data in the database is special and sometime the query can't return any value.

My keys are from 0101 to 1231 (MMDD) and if I query after the highest key, I don't get any callback, because firebase hasn't any data.

How can I set the query, that I find in that case the first >= "0101"?

The currently call is

admin.database().ref("calendar/birthday")
.orderByKey().startAt(key).limitToFirst(1).once("child_added")
.then(function(snapshot) { ... })

My database structure

"calendar" : {
  "birthday" : {
      "0111" : {
        ... -> 1st person
      },
      ...
      "0710" : {
        ... -> xth person
      },
      ...
      "1109" : {
        ... -> last person
      }
  }
}

My Alexa skill should name the next birthday and it will only work until 09. November and after 01. January, because I don't know how to query the data. Or can I structure my data in a better way to find the next birthday?

Body:
I think you're looking for: how do I know that there are no birthdays matching my query?

In that case you'll need to listen for the value event. If you attach that with a once(), it fires right away when you attach the query, no matter if there are results or not.

admin.database().ref("calendar/birthday")
  .orderByKey().startAt(key).limitToFirst(1).once("value")
  .then(function(snapshot) {
    if (!snapshot.exists()) {
      console.log("There are no birthdays on or after "+key);
    }
    else {
      snapshot.forEach(function(daySnapshot) {
        console.log("There is a birthday on "+daySnapshot.key);
      });
    }
  })

The exists() detects that there were no results matching the query. The forEach() loop in the else is the result of using value with a query. When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.


问:
Can't connect to python server from another machine
I am trying to learn about socket programming / networking and have a basic server up and running. Unfortunately I can only connect to it from the machine running the server. I connect from command prompt using telnet localhost 9999. This does not work from a different machine on the same network (as in a different pc which is not running the server). I have tried telnet "my local ip" 9999 to no avail and can't find a solution anywhere. Any help is appreciated. I am running python 3.6.1

Here is my code

```<code>import socket
import sys
from _thread import *
import webbrowser

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ""
port = 9999

try:
    s.bind((host,port))
except socket.error as e:
    print (str(e))

s.listen(5)

def threaded_client(conn):
    conn.send(str.encode("welcome, would you like to listen to a song? \n"))

while True:
    reply = ""
    data = conn.recv(2048)
    if data == b's':
        conn.send(str.encode("\n hi\n"))
        webbrowser.open('https://www.youtube.com/watch?v=DLzxrzFCyOs')
    if not data:
        break
    conn.sendall(str.encode(reply))
    print (data)
conn.close()

while True:
    conn, addr = s.accept()
    print("connected to:" +addr[0]+":"+str(addr[1]))
    start_new_thread(threaded_client,(conn,))
</code>```

when I try to connect this is the message I recieve C:\Users\Douglas Rouse>telnet 127.0.0.1 9999
Connecting To 127.0.0.1...Could not open connection to the host, on port 9999: Connect failed

答:
UPD:

I've just noticed that you try to connect using 127.0.0.1 as an IP address. That address always means "this computer", so you basically try to connect from a machine to itself, which fails, since the server is on a different machine.

You need to find out IP address of the server which is "visible" from the client machine. If they're in the same local network, I'd assume it's in one of the following common forms: 192.168.x.y, 10.0.0.x, 10.x.y.z.

Old answer:

If you use Windows, ensure that neither anti-virus software nor built-in firewall are interfering. Typically both of them block any non-standard communication.

The easiest way to check that is to switch both of them temporarily on both machines. If that helps, try switching them off on the server-side only (should also work). If that helps, add an exception for your application to anti-virus and firewall.

Body:
I am trying to learn about socket programming / networking and have a basic server up and running. Unfortunately I can only connect to it from the machine running the server. I connect from command prompt using telnet localhost 9999. This does not work from a different machine on the same network (as in a different pc which is not running the server). I have tried telnet "my local ip" 9999 to no avail and can't find a solution anywhere. Any help is appreciated. I am running python 3.6.1

Here is my code

import socket
import sys
from _thread import *
import webbrowser

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ""
port = 9999

try:
    s.bind((host,port))
except socket.error as e:
    print (str(e))

s.listen(5)

def threaded_client(conn):
    conn.send(str.encode("welcome, would you like to listen to a song? \n"))

while True:
    reply = ""
    data = conn.recv(2048)
    if data == b's':
        conn.send(str.encode("\n hi\n"))
        webbrowser.open('https://www.youtube.com/watch?v=DLzxrzFCyOs')
    if not data:
        break
    conn.sendall(str.encode(reply))
    print (data)
conn.close()

while True:
    conn, addr = s.accept()
    print("connected to:" +addr[0]+":"+str(addr[1]))
    start_new_thread(threaded_client,(conn,))

when I try to connect this is the message I recieve C:\Users\Douglas Rouse>telnet 127.0.0.1 9999
Connecting To 127.0.0.1...Could not open connection to the host, on port 9999: Connect failed


问:
Variable not defined error, and if statement doesn't execute
I'm trying to code horoscope that comes after the user input the birth month and day.

```<code>print("To figure out your horoscope, enter the following questions")
month = int(input("what month were you born(january,december,august: "))
days = int(input("what day were you born(2,4,12: "))
if month == 'december':

    astro_sign = 'Sagittarius are nice people' if (day < 22) else 'Capricon are adventurous'
print(astro_sign)
</code>```

However, every time I execute the code, it gives me an error:

```<code>print(astro_sign)
NameError: name 'astro_sign' is not defined
</code>```

Currently, I only put one month which is 12 and day is below 22, later on when one piece of this code works, I'm going to add more months. Can anyone please help me?

答:
That is because you are introducing/creating your astro_sign variable inside your conditional if month == '12':. So, every time you enter something that is not in fact '12', you will end up getting this error.

Simply, create your astro_sign before the conditional, so it is at least available in the event you don't enter your condition:

```<code>astro_sign = ''
if month == '12':
    # rest of code here
</code>```

Furthermore, you will never actually enter that condition with your current code, because you are casting your input for month as an int here:

```<code>month = int(input("month: "))
</code>```

However, your condition is explicitly checking for a string per your single quotes: '12'.

So, instead of:

```<code>if month == '12':
</code>```

You in fact should do:

```<code>if month == 12:
</code>```

Remove the single quotes, so you are comparing int to int.

Body:
I'm trying to code horoscope that comes after the user input the birth month and day.

print("To figure out your horoscope, enter the following questions")
month = int(input("what month were you born(january,december,august: "))
days = int(input("what day were you born(2,4,12: "))
if month == 'december':

    astro_sign = 'Sagittarius are nice people' if (day < 22) else 'Capricon are adventurous'
print(astro_sign)

However, every time I execute the code, it gives me an error:

print(astro_sign)
NameError: name 'astro_sign' is not defined

Currently, I only put one month which is 12 and day is below 22, later on when one piece of this code works, I'm going to add more months. Can anyone please help me?

Body:
That is because you are introducing/creating your astro_sign variable inside your conditional if month == '12':. So, every time you enter something that is not in fact '12', you will end up getting this error.

Simply, create your astro_sign before the conditional, so it is at least available in the event you don't enter your condition:

astro_sign = ''
if month == '12':
    # rest of code here

Furthermore, you will never actually enter that condition with your current code, because you are casting your input for month as an int here:

month = int(input("month: "))

However, your condition is explicitly checking for a string per your single quotes: '12'.

So, instead of:

if month == '12':

You in fact should do:

if month == 12:

Remove the single quotes, so you are comparing int to int.


问:
C# How can I control the output pins of an USB LPT cable
I have an USB LPT cable (Picture) and I want to control its output pins.

I am not familiar with USB connection coding. I searched, but I can't find anything useful for USB LPT coding.

Can anyone share simple code for controlling the output pins.

答:
There are many code examples for this kind of scenario. You didn't mention your OS, so I assume a flavor of Windows, but for Linux it's similar.

Look at the great site CodeProject for Windows sample code and adjust it to your needs.


问:
Optimizing a python Code
I'm trying to optimize this code (Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square). I'm new to coding and I'm having a hard time with this concept

```<code>  def list_squared(m, n):
    # your code
     import math
     MyList = []
     for i in range(m,n):
         A=[]
         for k in range(1,i+1):
             if i%k == 0:
                A.append(k**2)
         if round(math.sqrt(sum(A))) == math.sqrt(sum(A)):
                  B =[]
                  B.append(i)
                  B.append(sum(A))
                 MyList.append(B)
      return MyList
</code>```

答: First thing that i note you can optimize is range(1,i+1). You can set initially res=1 and start the range from 2 avoiding the first cycle. The important optimization is in the end: you can stop after i/2 because there are not integer divisors after it but remember to include the dispair case (for example 3/2 = 1.5 is not a valid input for range) so wrap the result of division around ceil function. In conclusion a simple optimization is range(2, ceil(i/2)+1) with res=1

Title: Optimizing a python Code

Body:
I'm trying to optimize this code (Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square). I'm new to coding and I'm having a hard time with this concept

  def list_squared(m, n):
    # your code
     import math
     MyList = []
     for i in range(m,n):
         A=[]
         for k in range(1,i+1):
             if i%k == 0:
                A.append(k**2)
         if round(math.sqrt(sum(A))) == math.sqrt(sum(A)):
                  B =[]
                  B.append(i)
                  B.append(sum(A))
                 MyList.append(B)
      return MyList


问:
iOS 10.3: NSStrikethroughStyleAttributeName is not rendered if applied to a sub range of NSMutableAttributedString
A strikethrough (single, double, ...) added as attribute to an instance of NSMutableAttributedString is not rendered if the apply range is not the whole string range.

This happens using addAttribute(_ name: String, value: Any, range: NSRange),  insert(_ attrString: NSAttributedString, at loc: Int), append(_ attrString: NSAttributedString), ...

Broken by Apple in early iOS 10.3 betas, and not fixed in 10.3 final.

Credit:
https://openradar.appspot.com/31034683

答:
Its a bug known to Xcode 8.3 (8E3004b) / iOS 10.3, with this workaround NO extra line of code is need, just add [NSBaselineOffsetAttributeName:0] when declaring NSMutableAttributedString()

```<code>let attrStr = NSMutableAttributedString(string: YOUR_STRING_HERE, attributes: [NSBaselineOffsetAttributeName : 0])

// Now if you add the strike-through attribute to a range, it will work
attrStr.addAttributes([
    NSFontAttributeName: UIFont.boldSystemFont(ofSize: 24),
    NSStrikethroughStyleAttributeName: 1
], range: NSRange)
</code>```

Body:
Its a bug known to Xcode 8.3 (8E3004b) / iOS 10.3, with this workaround NO extra line of code is need, just add [NSBaselineOffsetAttributeName:0] when declaring NSMutableAttributedString()

let attrStr = NSMutableAttributedString(string: YOUR_STRING_HERE, attributes: [NSBaselineOffsetAttributeName : 0])

// Now if you add the strike-through attribute to a range, it will work
attrStr.addAttributes([
    NSFontAttributeName: UIFont.boldSystemFont(ofSize: 24),
    NSStrikethroughStyleAttributeName: 1
], range: NSRange)


问:
Windows Form UserControl design time properties
I am struggling with a UserControl. I have a UserControl that represent a Pager and it has a Presenter object property exposed in this way:

```<code>[Browsable(false)]
[DesignSerializationAttribute(DesignSerializationAttribute.Hidden)]
public object Presenter { get; set; }
</code>```

The code itself works as I can drag and drop a control into a Windows From without having Visual Studio initializing this property.
Now, because in the Load event of this control I call a method of the Presenter that at run-time is null ... I have introduced this additional code:

```<code>public override void OnLoad(...)
{
   if (this.DesignMode)
   {
      base.OnLoad(e);
      return;
   }
   presenter.OnViewReady();
}
</code>```

Now, every time I open a Window that contains this UserControl, Visual Studio modifies the Windows designer code. So, as soon as I open it, VS ask me if I want to save it ... and of course, if I add a control to the Window, it doesn't keep the changes ... As soon as I remove the UserControl Pager the problem disappears ...
How should I tackle that in the proper way? I just don't want that the presenter property is initialized at design time as it is injected at runtime ...

答:
You're probably getting an exception when VS tries to generate the designer code.

Attach a second copy of VS to the designer, turn on Break On Exceptions, and see what's going on.

Body:
I am struggling with a UserControl. I have a UserControl that represent a Pager and it has a Presenter object property exposed in this way:

[Browsable(false)]
[DesignSerializationAttribute(DesignSerializationAttribute.Hidden)]
public object Presenter { get; set; }

The code itself works as I can drag and drop a control into a Windows From without having Visual Studio initializing this property.
Now, because in the Load event of this control I call a method of the Presenter that at run-time is null ... I have introduced this additional code:

public override void OnLoad(...)
{
   if (this.DesignMode)
   {
      base.OnLoad(e);
      return;
   }
   presenter.OnViewReady();
}

Now, every time I open a Window that contains this UserControl, Visual Studio modifies the Windows designer code. So, as soon as I open it, VS ask me if I want to save it ... and of course, if I add a control to the Window, it doesn't keep the changes ... As soon as I remove the UserControl Pager the problem disappears ...
How should I tackle that in the proper way? I just don't want that the presenter property is initialized at design time as it is injected at runtime ...


问:
Not uploading pictures to Firebase storage
I want to upload pictures to storage. Every time I launch my emulator I get no errors and everything works perfectly except that when I select the pictures in my emulator and upload them it does not show in the Firebase Storage section even after I refresh. Here is my code:</p>

```<code>    package com.safariagaming;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.safariagaming.mtc_project.R;

public class Account_Page extends AppCompatActivity {

    private Button mSelectImage;

    private StorageReference mStorage;

    private static final int GALLERY_INTENT = 2;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account__page);

        mSelectImage = (Button) findViewById(R.id.selectImage_BUTTON);

        mStorage = FirebaseStorage.getInstance().getReference(); //.child at end ifyou want to add an child to it

        mProgressDialog = new ProgressDialog(this);

        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(Intent.ACTION_PICK);

                intent.setType("image/*");

                startActivityForResult(intent, GALLERY_INTENT);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){

            mProgressDialog.setMessage("Uploading...");

            Uri uri = data.getData();

            StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());

            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Toast.makeText(Account_Page.this, "Upload Done", Toast.LENGTH_LONG).show();

                mProgressDialog.dismiss();
                }//you can also add onFaliure listener
            });

        }

    }
}
</code>```

答:
Put files to storage as a stream instead of an Uri

Remove the Uri part and put the following instead:

```<code>InputStream inputStream = this.getContentResolver().openInputStream(data.getData());
</code>```

and change the putFile(uri) with putFile(inputStream)

And also consider changing uri.getLastPathSegment() part with a reasonable file name such as your_name.png(Note that even if your photo is not in png format that will work based on my experience)

This should work

Body:
I want to upload pictures to storage. Every time I launch my emulator I get no errors and everything works perfectly except that when I select the pictures in my emulator and upload them it does not show in the Firebase Storage section even after I refresh. Here is my code:

    package com.safariagaming;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.safariagaming.mtc_project.R;

public class Account_Page extends AppCompatActivity {

    private Button mSelectImage;

    private StorageReference mStorage;

    private static final int GALLERY_INTENT = 2;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account__page);

        mSelectImage = (Button) findViewById(R.id.selectImage_BUTTON);

        mStorage = FirebaseStorage.getInstance().getReference(); //.child at end ifyou want to add an child to it

        mProgressDialog = new ProgressDialog(this);

        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(Intent.ACTION_PICK);

                intent.setType("image/*");

                startActivityForResult(intent, GALLERY_INTENT);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){

            mProgressDialog.setMessage("Uploading...");

            Uri uri = data.getData();

            StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());

            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Toast.makeText(Account_Page.this, "Upload Done", Toast.LENGTH_LONG).show();

                mProgressDialog.dismiss();
                }//you can also add onFaliure listener
            });

        }

    }
}

Body:
Put files to storage as a stream instead of an Uri

Remove the Uri part and put the following instead:

InputStream inputStream = this.getContentResolver().openInputStream(data.getData());

and change the putFile(uri) with putFile(inputStream)

And also consider changing uri.getLastPathSegment() part with a reasonable file name such as your_name.png(Note that even if your photo is not in png format that will work based on my experience)

This should work


问:
Convert categorical strings to integers in Matlab
I have a vector  that has labels with a char i would like to conver these to integers.
Example:

```<code>Y | Y^
--+--
A | 1
A | 1
B | 2
C | 3
B | 2
B | 2
A | 1
C | 2
</code>```

I have Y and i would like to convert to Y^. Any function or suggestions? Thanks!

答:
As grp2idx requires the Statistics and Machine Learning Toolbox I'd recommend a little simpler solution:

```<code>y = Y - 64

%// or alternatively (thanks to EBH)
y = Y - 'A' + 1
</code>```

A char is nothing else than an 8-bit integer mapping ASCII-Code, where capital letters start with 65.

Body:
I have a vector  that has labels with a char i would like to conver these to integers.
Example:

Y | Y^
--+--
A | 1
A | 1
B | 2
C | 3
B | 2
B | 2
A | 1
C | 2

I have Y and i would like to convert to Y^. Any function or suggestions? Thanks!

Body:
As grp2idx requires the Statistics and Machine Learning Toolbox I'd recommend a little simpler solution:

y = Y - 64

%// or alternatively (thanks to EBH)
y = Y - 'A' + 1

A char is nothing else than an 8-bit integer mapping ASCII-Code, where capital letters start with 65.


问:
Android Studio Emulator and "Process finished with exit code -1073741511 (0xC0000139)"
I'm trying to emulate my application using Android Studio Emulator (i'm developing by Android Studio) but I receive this error message:

Emulator: Process finished with exit code -1073741511 (0xC0000139)

Do what can I do?

Problem image:

答: increase the ram of the AVD virtual emulator you made and also update the API</p>

ContentLicense: CC BY-SA 4.0


问:
Wordpress: get all posts of a custom type
I have this strange issue. I want to fetch all posts that are of a custom type, here's my snippet.

```<code>$query = new WP_Query(array(
    'post_type' => 'custom',
    'post_status' => 'publish'
));

while ($query->have_posts()) {
    $query->the_post();
    $post_id = get_the_ID();
    echo $post_id;
    echo "<br>";
}

wp_reset_query();
</code>```

This only gets me 6 of them, while I have more than 50 records matching that criteria in the database. Can anyone tell me where I have gone wrong?

Many thanks!

答:
It is advisable to use an integer instead of '-1' For example:</p>

```<code>'posts_per_page' => 999999,
</code>```

Body:
I have this strange issue. I want to fetch all posts that are of a custom type, here's my snippet.

$query = new WP_Query(array(
    'post_type' => 'custom',
    'post_status' => 'publish'
));

while ($query->have_posts()) {
    $query->the_post();
    $post_id = get_the_ID();
    echo $post_id;
    echo "
";
}

wp_reset_query();

This only gets me 6 of them, while I have more than 50 records matching that criteria in the database. Can anyone tell me where I have gone wrong?

Many thanks!

Body:
It is advisable to use an integer instead of '-1' For example:

'posts_per_page' => 999999,


问:
Angular 4 OAuth Security Localstorage
i'm getting started with angular 4. Now i try an authentication with oauth.
If the credentials are right, the server sends the token to the client.
Now i save it to the localstorage:
    localStorage.setItem('currentUser', data.access_token);

The authguard checks

```<code> if (localStorage.getItem('currentUser')) {
</code>```

Is this secure? Or are there further steps necessary?

答:
This is the right way but you have to do it the following way.

Get token when sessions starts / Login

Use token to secure routes

Use token for REST API / HTTP Methods

Delete token when session ended / Log out

Your approach is correct, the steps are just to mention everything, explicitly.

Title: Angular 4 OAuth Security Localstorage

Body:
i'm getting started with angular 4. Now i try an authentication with oauth.
If the credentials are right, the server sends the token to the client.
Now i save it to the localstorage:
    localStorage.setItem('currentUser', data.access_token);

The authguard checks

 if (localStorage.getItem('currentUser')) {

Is this secure? Or are there further steps necessary?


问:
Making a char function parameter const?
Consider this function declaration:

```<code>int IndexOf(const char *, char);
</code>```

where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const? I always try to use const on pointer parameters but when something is called by value, I normally leave the const away.

What are your thoughts?

答: I'd say const would add absolutely nothing to your code.

Title: Making a char function parameter const?

Body:
Consider this function declaration:

int IndexOf(const char *, char);

where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const? I always try to use const on pointer parameters but when something is called by value, I normally leave the const away.

What are your thoughts?


问:
Read & split multiple column text file into arrays
For a project I'm working on a fairly big animal dataset with up to 14 parameters of data. I was able to read it in and display it as strings using this:

```<code>public static void readIn(String file) throws IOException {

    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("/t");
        String data = columns[columns.length-1];
        System.out.println(data);
    }
}
</code>```

and displaying something like this:

```<code>04:00:01    0.11    0.04    -0.1    1047470 977.91  91.75
04:00:01    0.32    -0.03   -0.07   1047505 977.34  92.91
04:00:01    0.49    -0.03   -0.08   1047493 978.66  92.17
</code>```

But I'm currently having trouble trying to split each column into separate arrays so that I can process the data (e.g. calculating means). Any idea of how I can do this? Any help would be much appreciated.

Edit: thanks, I've found out a solution that works and also lets me choose which channel it reads specifically. I've also decided to store the data as arrays within the class, here's what I have now:

```<code>public static void readChannel(String file, int channel) throws IOException
{
    List<Double> dataArr = new ArrayList<>();
    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("\t");

        for (int i = channel; i < columns.length; i+=(columns.length-channel)) {
            dataArr.add(Double.parseDouble(columns[i]));
            dataArr.toArray();
        }
    }
}
</code>```

答:
You can store all rows in an ArrayList and then create arrays for each column and store values in them. Sample code: </p>

```<code>Scanner scanner = new Scanner(new File(file));
ArrayList<String> animalData = new ArrayList<String>();
while (scanner.hasNext()) {
    String[] columns = scanner.nextLine().split("/t");
    String data = columns[columns.length-1];
    animalData.add(data);
    System.out.println(data);
}

int size = animalData.size();
String[] arr1 = new String[size]; String[] arr2 = new String[size];
String[] arr3 = new String[size]; String[] arr4 = new String[size];
for(int i=0;i<size;i++)
{
    String[] temp = animalData.get(i).split("\t");
    arr1[i] = temp[0];
    arr2[i] = temp[1];
    arr3[i] = temp[2];
    arr4[i] = temp[3];
}
</code>```

Body:
For a project I'm working on a fairly big animal dataset with up to 14 parameters of data. I was able to read it in and display it as strings using this:

public static void readIn(String file) throws IOException {

    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("/t");
        String data = columns[columns.length-1];
        System.out.println(data);
    }
}

and displaying something like this:

04:00:01    0.11    0.04    -0.1    1047470 977.91  91.75
04:00:01    0.32    -0.03   -0.07   1047505 977.34  92.91
04:00:01    0.49    -0.03   -0.08   1047493 978.66  92.17

But I'm currently having trouble trying to split each column into separate arrays so that I can process the data (e.g. calculating means). Any idea of how I can do this? Any help would be much appreciated.

Edit: thanks, I've found out a solution that works and also lets me choose which channel it reads specifically. I've also decided to store the data as arrays within the class, here's what I have now:

public static void readChannel(String file, int channel) throws IOException
{
    List<Double> dataArr = new ArrayList<>();
    Scanner scanner = new Scanner(new File(file));
    while (scanner.hasNext()) {
        String[] columns = scanner.nextLine().split("\t");

        for (int i = channel; i < columns.length; i+=(columns.length-channel)) {
            dataArr.add(Double.parseDouble(columns[i]));
            dataArr.toArray();
        }
    }
}

Body:
You can store all rows in an ArrayList and then create arrays for each column and store values in them. Sample code:

Scanner scanner = new Scanner(new File(file));
ArrayList<String> animalData = new ArrayList<String>();
while (scanner.hasNext()) {
    String[] columns = scanner.nextLine().split("/t");
    String data = columns[columns.length-1];
    animalData.add(data);
    System.out.println(data);
}

int size = animalData.size();
String[] arr1 = new String[size]; String[] arr2 = new String[size];
String[] arr3 = new String[size]; String[] arr4 = new String[size];
for(int i=0;i<size;i++)
{
    String[] temp = animalData.get(i).split("\t");
    arr1[i] = temp[0];
    arr2[i] = temp[1];
    arr3[i] = temp[2];
    arr4[i] = temp[3];
}


问:
Comparing two arrays of objects, and update the value of the second one. Very slow
Below is my working code example, but the problem i'm having is when I have over 100k records this script takes a very long time to run and I was wondering if there was a faster way of doing this.

Note: I have two arrays of objects and I need to set the second array's object names based on the first one's. The IDs will match between the two and the order will be random.

```<code>const _ = require('lodash');

let res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

let res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

_.forEach(res1, function(data1) {
  _.forEach(res2, function(data2) {
    if (data1.id === data2.id) {
      data2.name = data1.name;
    }
  });
});

// res2 = [{id:2, name:'bill'},{id:4, name:'Jill'}];
</code>```

答:
A simple solution using forEach and find:

let res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

let res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

res2.forEach((item) => {
  item.name = res1.find((person) => person.id === item.id).name
});

console.log(res2);```

Body:
Below is my working code example, but the problem i'm having is when I have over 100k records this script takes a very long time to run and I was wondering if there was a faster way of doing this.

Note: I have two arrays of objects and I need to set the second array's object names based on the first one's. The IDs will match between the two and the order will be random.

const _ = require('lodash');

let res1 = [
  {id:1, name:'Sandra'},
  {id:2, name:'Bill'},
  {id:3, name:'Peter'},
  {id:4, name:'Jill'}
];

let res2 = [
  {id:2, name:'John'},
  {id:4, name:'Bobby'}
];

_.forEach(res1, function(data1) {
  _.forEach(res2, function(data2) {
    if (data1.id === data2.id) {
      data2.name = data1.name;
    }
  });
});

// res2 = [{id:2, name:'bill'},{id:4, name:'Jill'}];


问:
Laravel droplist from the database
I am newbie in laravel and I like to have a droplist with the values from the database table. How can I do it, actually I have an error: "Undefined variable: claims" (I think data is not passing) - I think it's because of few reasons: because of View function or different reasons.

If you have a droplist code and you can explain your code with details - please, share it with me!

Example of a droplist I like to have(taking the values from the db):

Definitions of my values and variables:

```<code>mainpage - my html page

Drop - my table with the name "claim_type" in the db

$claims - variable with info from the table "claim_type" from the database
</code>```

Yea, I declared my table with function

```<code>protected $table = 'claim_type';
</code>```

Here is my Controller with the name MainController:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Main;
use App\Drop;

class MainController extends Controller
{
    public function index()
    {
        $claims = Drop::all();
        return View::make('mainpage')->with('users', $claims);
    }
</code>```

And my html:

```<code>@extends('layout.mainlayout')

@section('content')
<form method="POST" action="{{ url('/') }}/querty">
{{ csrf_field()}}
<div>
         <h2>Force form:</h2>
    <p> You can add you information here, Sir:</p>
    <p> Name:
        <input type="text" name="name" />
    </p>
    <p> Email:
        <input type="text" name="email" />
    </p>
    <div>
    <form method="POST" action="{{ url('/') }}/add">
    @foreach($claims as $claim)
    <option value="$claim->id">{{$claim->type}}</option>
    @endforeach
    </form>
    </div>
    <p> Where:
        <input type="text" name="where" />
    </p>
    <p> Description:
        <input type="text" name="description" />
    </p>
    <button type="submit" class="btn btn-default">Explose it!</button>

</div>
</form>
@endsection
</code>```

My route:

```<code>Route::post('/mainpage', 'MainController@index');
</code>```

Actually, saw a lot of articles, please explain me how it works.

Thank you!

I hope this post will help also for the different coders

Tested methods from different users:

```<code>class MainController extends Controller
{
    public function index()
    {
        $claims = Drop::all();
        dd($claims);
        return View::make('mainpage')->with(claims);
    }
</code>```

In Views (tested methods):

```<code>@foreach($claims as $claim)
        <option value="$claim->id">{{$claims->type}}</option>
    @endforeach
</code>```

答:
On index method in controller yo have two errors

$claims = Drop::all()->get();// use this get()

return View::make('mainpage')->with('users', claims);// you don`t need $

And where did you get this users

And in view you need foreach

```<code> @foreach($claims as $claim)
    <option value="$claim->id">{{$claims->type}}</option>
@endforeach
</code>```

And also i think that your model don`t see your table in db because of naming convention. Model name is plural of your db table name. If you have table claimTypes model is claimType

Title: Laravel droplist from the database

Body:
I am newbie in laravel and I like to have a droplist with the values from the database table. How can I do it, actually I have an error: "Undefined variable: claims" (I think data is not passing) - I think it's because of few reasons: because of View function or different reasons.

If you have a droplist code and you can explain your code with details - please, share it with me!

Example of a droplist I like to have(taking the values from the db):

Definitions of my values and variables:

mainpage - my html page

Drop - my table with the name "claim_type" in the db

$claims - variable with info from the table "claim_type" from the database

Yea, I declared my table with function

protected $table = 'claim_type';

Here is my Controller with the name MainController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Main;
use App\Drop;

class MainController extends Controller
{
    public function index()
    {
        $claims = Drop::all();
        return View::make('mainpage')->with('users', $claims);
    }

And my html:

@extends('layout.mainlayout')

@section('content')
<form method="POST" action="{{ url('/') }}/querty">
{{ csrf_field()}}

Force form:

 You can add you information here, Sir:

 Name:
        <input type="text" name="name" />

 Email:
        <input type="text" name="email" />

    <form method="POST" action="{{ url('/') }}/add">
    @foreach($claims as $claim)
    <option value="$claim->id">{{$claim->type}}</option>
    @endforeach
    </form>

 Where:
        <input type="text" name="where" />

 Description:
        <input type="text" name="description" />

    <button type="submit" class="btn btn-default">Explose it!</button>

</form>
@endsection

My route:

Route::post('/mainpage', 'MainController@index');

Actually, saw a lot of articles, please explain me how it works.

Thank you!

I hope this post will help also for the different coders

Tested methods from different users:

class MainController extends Controller
{
    public function index()
    {
        $claims = Drop::all();
        dd($claims);
        return View::make('mainpage')->with(claims);
    }

In Views (tested methods):

@foreach($claims as $claim)
        <option value="$claim->id">{{$claims->type}}</option>
    @endforeach

Body:
On index method in controller yo have two errors

$claims = Drop::all()->get();// use this get()

return View::make('mainpage')->with('users', claims);// you don`t need $

And where did you get this users

And in view you need foreach

 @foreach($claims as $claim)
    <option value="$claim->id">{{$claims->type}}</option>
@endforeach

And also i think that your model don`t see your table in db because of naming convention. Model name is plural of your db table name. If you have table claimTypes model is claimType


问:
dplyr: Filter within years prior to marked time period
I want have a list of year-country specific dummies and I want to also mark years two years prior to those years that are marked.

The data looks like this

```<code>library(tidyverse)

df <- tribble(
  ~year, ~country, ~occurrence,
  #--|--|----
  2003, "USA", 1,
  2004, "USA", 0,
  2005, "USA", 0,
  2006, "USA", 0,
  2007, "USA", 0,
  2008, "USA", 0,
  2009, "USA", 0,
  2010, "USA", 0,
  2011, "USA", 1,
  2012, "USA", 0,
  2013, "USA", 0,
  2005, "FRA", 0,
  2006, "FRA", 0,
  2007, "FRA", 1,
  2008, "FRA", 1,
  2009, "FRA", 0,
  2010, "FRA", 0,
  2011, "FRA", 0,
  2012, "FRA", 0,
  2013, "FRA", 0,
  2014, "FRA", 0,
  2015, "FRA", 1
)
</code>```

So for "USA" I also want to put a 1 into column occurence for the years 2009 and 2010 and for FRA the years 2005, 2006, 2013 and 2014.

I thought about doing something like this:

```<code>df %>%
  group_by(country) %>%
  mutate(occurence = ifelse("not sure what to put here"),
                            1,
                            0))
</code>```

But I'm not sure how to tell R only to filter for the years I want.

答:
After grouping by 'country', we can take up to 2 lead of 'occurrence' and get the max of each row with pmax to get the expected output in 'occurrence'

```<code>df %>%
  group_by(country) %>%
  mutate(occurrence = pmax(occurrence, lead(occurrence, default = 0),
                     lead(occurrence, default=0, n=2)))
</code>```

Or this can be achieved with data.table with similar methodology

```<code>library(data.table)
setDT(df)[,  occurrence := do.call(pmax, shift(occurrence, n = 0:2,
     type = "lead", fill = 0)), country]
df
#    year country occurrence
# 1: 2003     USA          1
# 2: 2004     USA          0
# 3: 2005     USA          0
# 4: 2006     USA          0
# 5: 2007     USA          0
# 6: 2008     USA          0
# 7: 2009     USA          1
# 8: 2010     USA          1
# 9: 2011     USA          1
#10: 2012     USA          0
#11: 2013     USA          0
#12: 2005     FRA          1
#13: 2006     FRA          1
#14: 2007     FRA          1
#15: 2008     FRA          1
#16: 2009     FRA          0
#17: 2010     FRA          0
#18: 2011     FRA          0
#19: 2012     FRA          0
#20: 2013     FRA          1
#21: 2014     FRA          1
#22: 2015     FRA          1
</code>```

Body:
I want have a list of year-country specific dummies and I want to also mark years two years prior to those years that are marked.

The data looks like this

library(tidyverse)

df <- tribble(
  ~year, ~country, ~occurrence,
  #--|--|----
  2003, "USA", 1,
  2004, "USA", 0,
  2005, "USA", 0,
  2006, "USA", 0,
  2007, "USA", 0,
  2008, "USA", 0,
  2009, "USA", 0,
  2010, "USA", 0,
  2011, "USA", 1,
  2012, "USA", 0,
  2013, "USA", 0,
  2005, "FRA", 0,
  2006, "FRA", 0,
  2007, "FRA", 1,
  2008, "FRA", 1,
  2009, "FRA", 0,
  2010, "FRA", 0,
  2011, "FRA", 0,
  2012, "FRA", 0,
  2013, "FRA", 0,
  2014, "FRA", 0,
  2015, "FRA", 1
)

So for "USA" I also want to put a 1 into column occurence for the years 2009 and 2010 and for FRA the years 2005, 2006, 2013 and 2014.

I thought about doing something like this:

df %>%
  group_by(country) %>%
  mutate(occurence = ifelse("not sure what to put here"),
                            1,
                            0))

But I'm not sure how to tell R only to filter for the years I want.

Body:
After grouping by 'country', we can take up to 2 lead of 'occurrence' and get the max of each row with pmax to get the expected output in 'occurrence'

df %>%
  group_by(country) %>%
  mutate(occurrence = pmax(occurrence, lead(occurrence, default = 0),
                     lead(occurrence, default=0, n=2)))

Or this can be achieved with data.table with similar methodology

library(data.table)
setDT(df)[,  occurrence := do.call(pmax, shift(occurrence, n = 0:2,
     type = "lead", fill = 0)), country]
df
#    year country occurrence
# 1: 2003     USA          1
# 2: 2004     USA          0
# 3: 2005     USA          0
# 4: 2006     USA          0
# 5: 2007     USA          0
# 6: 2008     USA          0
# 7: 2009     USA          1
# 8: 2010     USA          1
# 9: 2011     USA          1
#10: 2012     USA          0
#11: 2013     USA          0
#12: 2005     FRA          1
#13: 2006     FRA          1
#14: 2007     FRA          1
#15: 2008     FRA          1
#16: 2009     FRA          0
#17: 2010     FRA          0
#18: 2011     FRA          0
#19: 2012     FRA          0
#20: 2013     FRA          1
#21: 2014     FRA          1
#22: 2015     FRA          1


问:
Access Control via built-in fingerprint sensor on Android
I understand how to authenticate users via Fingerprint Authentication using Android SDK. But it only tells if the fingerprint matches one of the enrolled fingerprints or not - i.e. a boolean.

I want to make it so that it gives me the fingerprint image as well, so I can extract the information against that fingerprint, i.e. userId, name, etc stored in the database.

For example:
I have 3 users: Admin, Teacher, Student.
I should be able to use the built-in fingerprint reader to be able to determine if the user is identified as an Admin, Teacher or Student, and give the app access rights accordingly.

The app will be deployed to only ONE device that is accessible to all users, so the application should be responsible to control the limit of number of fingerprints that can be registered.

Is it possible with the built-in fingerprint reader of the device?

答:
I want to make it so that it gives me the fingerprint image as well

That is not supported by Android's fingerprint APIs, for privacy reasons.

I should be able to use the built-in fingerprint reader to be able to determine if the user is identified as an Admin, Teacher or Student, and give the app access rights accordingly.

Each of those individuals should have a separate device account. Then each of them has a separate copy of your app, in effect. So long as each of those accounts get configured in your app with the proper role, the identification process is handled for you by the OS.