问:
Flex 4.0/4.5 global error handling
I'm trying to use the new(ish) AS3 global error handling class. I am trying to use it within a Flex mxml application. I can't get it to work at all. Below is an entire program that shows the problem. I set this to use Flash Player 10.2 and compiled with the Flex 4.5 SDK.

I've tried using Flex SDK 4.0 and 4.5 but I get the error in either case. I must be missing something obvious here. This is a normal Flex SWF file that will be shown on a web page. Assuming I could import the UncaughtErrorEvent, I would then do something like this to setup the event handler:

```<code>    if(systemManager.loaderInfo.hasOwnProperty("uncaughtErrorEvents")) {
        IEventDispatcher(
            systemManager.loaderInfo["uncaughtErrorEvents"]).addEventListener(
               "uncaughtError", uncaughtErrorHandler);
    }
</code>```

this all seems horribly kludgy but I could live with that except that it doesn't work! I've scoured the web and cannot find any docs or examples that explain how to make this work in my context. Any advice?

Complete program:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" applicationComplete="onApplicationComplete();"
                   >
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                private function onApplicationComplete() : void {
                    systemManager.loaderInfo.uncaughtErrorEvents.addEventListener("uncaughtError", uncaughtErrorHandler);
                }
                private function uncaughtErrorHandler(event:Event) : void {
                    trace(event.toString());
                }
            ]]>
        </fx:Script>
        <s:Button x="153" y="64" label="Trigger Error" id="triggerButton" click="throw new Error('myError')"/>
    </s:Application>
</code>```

答:
Take from the API (which I recommend you look through next time):</p>

```<code><s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/halo"
                       applicationComplete="applicationCompleteHandler();">

    <fx:Script>
        <![CDATA[
            import flash.events.ErrorEvent;
            import flash.events.MouseEvent;
            import flash.events.UncaughtErrorEvent;

            private function applicationCompleteHandler():void
            {
                loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
            }

            private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
            {
                if (event.error is Error)
                {
                    var error:Error = event.error as Error;
                    // do something with the error
                }
                else if (event.error is ErrorEvent)
                {
                    var errorEvent:ErrorEvent = event.error as ErrorEvent;
                    // do something with the error
                }
                else
                {
                    // a non-Error, non-ErrorEvent type was thrown and uncaught
                }
            }

            private function clickHandler(event:MouseEvent):void
            {
                throw new Error("Gak!");
            }
        ]]>
    </fx:Script>

    <s:Button label="Cause Error" click="clickHandler(event);"/>
</s:WindowedApplication>
</code>```

Title: Flex 4.0/4.5 global error handling

Body:
I'm trying to use the new(ish) AS3 global error handling class. I am trying to use it within a Flex mxml application. I can't get it to work at all. Below is an entire program that shows the problem. I set this to use Flash Player 10.2 and compiled with the Flex 4.5 SDK.

I've tried using Flex SDK 4.0 and 4.5 but I get the error in either case. I must be missing something obvious here. This is a normal Flex SWF file that will be shown on a web page. Assuming I could import the UncaughtErrorEvent, I would then do something like this to setup the event handler:

    if(systemManager.loaderInfo.hasOwnProperty("uncaughtErrorEvents")) {
        IEventDispatcher(
            systemManager.loaderInfo["uncaughtErrorEvents"]).addEventListener(
               "uncaughtError", uncaughtErrorHandler);
    }

this all seems horribly kludgy but I could live with that except that it doesn't work! I've scoured the web and cannot find any docs or examples that explain how to make this work in my context. Any advice?

Complete program:

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" applicationComplete="onApplicationComplete();"
                   >
        <fx:Declarations>

        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                private function onApplicationComplete() : void {
                    systemManager.loaderInfo.uncaughtErrorEvents.addEventListener("uncaughtError", uncaughtErrorHandler);
                }
                private function uncaughtErrorHandler(event:Event) : void {
                    trace(event.toString());
                }
            ]]>
        </fx:Script>
        <s:Button x="153" y="64" label="Trigger Error" id="triggerButton" click="throw new Error('myError')"/>
    </s:Application>

Body:
Take from the API (which I recommend you look through next time):

<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/halo"
                       applicationComplete="applicationCompleteHandler();">

    <fx:Script>
        <![CDATA[
            import flash.events.ErrorEvent;
            import flash.events.MouseEvent;
            import flash.events.UncaughtErrorEvent;

            private function applicationCompleteHandler():void
            {
                loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
            }

            private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
            {
                if (event.error is Error)
                {
                    var error:Error = event.error as Error;
                    // do something with the error
                }
                else if (event.error is ErrorEvent)
                {
                    var errorEvent:ErrorEvent = event.error as ErrorEvent;
                    // do something with the error
                }
                else
                {
                    // a non-Error, non-ErrorEvent type was thrown and uncaught
                }
            }

            private function clickHandler(event:MouseEvent):void
            {
                throw new Error("Gak!");
            }
        ]]>
    </fx:Script>

    <s:Button label="Cause Error" click="clickHandler(event);"/>
</s:WindowedApplication>


来源: stackexchange

问:
Kotlin - if statement not working properly
I have this very simple code:

```<code>    var i = 1

    if(i  < 5)
     button.setOnClickListener{
        i++
     }
</code>```

but when i is equal to 5, it still enter into the if and i increases and I have no idea on why it do that.

答:
When i is less than 5 this code:

```<code>if(i  < 5)
 button.setOnClickListener{
    i++
 }
</code>```

sets the listener for button.

If later i changes its value to something >=5 the listener is still valid, so every time you click on the button i will be incremented.

So if you want to cancel the listener you can do:

```<code>if (i >= 5) button.setOnClickListener(null)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this very simple code:

    var i = 1

    if(i  < 5)
     button.setOnClickListener{
        i++
     }

but when i is equal to 5, it still enter into the if and i increases and I have no idea on why it do that.

Body:
When i is less than 5 this code:

if(i  < 5)
 button.setOnClickListener{
    i++
 }

sets the listener for button.

If later i changes its value to something >=5 the listener is still valid, so every time you click on the button i will be incremented.

So if you want to cancel the listener you can do:

if (i >= 5) button.setOnClickListener(null)


问:
Recreating a parallax zoom effect with SVG Image mask
I'm trying to recreate the effect found at the bottom of this page where the words "REFORM CO" Zoom in to reveal a background image with a headline.

I attempted to recreate this effect myself using skrollr but I've hit a wall. ideally I'd like the SVG to be smaller and centered in the mask and for the video to stay fixed until the mask disappears just like the REFORM CO example.

Here's my HTML and the link to my attempt: https://jsfiddle.net/uex526qs/1/

```<code><body>

<div class="knockout">

  <svg x="50%" y="100%" class="knockout-text-container"  height="100%" data-0="opacity:1;transform: scale(1);" data-50p="opacity:0;font-size: 10em;transform: scale(10);">

    <rect class="knockout-text-bg" width="100%" height="100%" fill="#fff" x="0" y="0" fill-opacity="1" mask="url(#knockout-text)"/>

    <mask id="knockout-text">
      <rect width="100%" height="100%" fill="#fff" x="0" y="0"  />

      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 97.73 97.73"><defs><style>.cls-1{fill:#000;}</style></defs><title>shape2</title><g id="Layer_2" data-name="Layer 2"><g id="Content"><path class="cls-1" d="M48.86,97.73A7.72,7.72,0,0,1,41.15,90V7.72a7.72,7.72,0,1,1,15.43,0V90A7.72,7.72,0,0,1,48.86,97.73Z"/><path class="cls-1" d="M90,56.58H7.72a7.72,7.72,0,1,1,0-15.43H90a7.72,7.72,0,1,1,0,15.43Z"/></g></g></svg>

    </mask>

  </svg>

</div>

<video autoplay muted loop id="myVideo">
<source src="http://thenewcode.com/assets/videos/ocean-small.mp4" type="video/mp4">
</video>

</body>
</code>```

Any help is appreciated

答:
You can make an element stay fixed relative to the browser window using position: fixed.

To make your mask scale relative to the element it is aplied to, use:

```<code><mask maskContentUnits="objectBoundingBox">
</code>```

then use coordinates in the range 0..1.  That's the reason my scale() values are so small. Your shape is roughly 100x100, so I needed to scale by an extra 0.01 to get them down into the 0..1 range.

The rest of your example was more-or-less correct.

$(document).ready(function() {
  var s = skrollr.init();
  constants: {
    //fill the box for a "duration" of 150% of the viewport (pause for 150%)
    //adjust for shorter/longer pause
    knockout: '150p'
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  position: relative;
  margin: 0;
  height: 1500px;
}

.container {
  position: fixed;
}

video {
  width: 100%;
}

.overlay {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}</code>```

  <video autoplay muted loop id="myVideo">
    <source src="http://thenewcode.com/assets/videos/ocean-small.mp4" type="video/mp4">
  </video>

  <svg class="overlay" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice">
    <defs>
      <mask id="knockout" maskContentUnits="objectBoundingBox">
        <rect x="0" y="0" width="1" height="1" fill="white"/>
        <g fill="black"
           data-0="transform: translate(0.5px,0.5px) scale(0.0015) translate(-49px,-49px);"
           data-50p="transform: translate(0.5px,0.5px) scale(0.04) translate(-49px,-49px);">
          <path d="M48.86,97.73A7.72,7.72,0,0,1,41.15,90V7.72a7.72,7.72,0,1,1,15.43,0V90A7.72,7.72,0,0,1,48.86,97.73Z"/>
          <path class="cls-1" d="M90,56.58H7.72a7.72,7.72,0,1,1,0-15.43H90a7.72,7.72,0,1,1,0,15.43Z"/>
        </g>
      </mask>
    </defs>
    <rect x="0" y="0" width="100" height="100" fill="white" mask="url(#knockout)"/>
  </svg>

```

Body:
I'm trying to recreate the effect found at the bottom of this page where the words "REFORM CO" Zoom in to reveal a background image with a headline.

I attempted to recreate this effect myself using skrollr but I've hit a wall. ideally I'd like the SVG to be smaller and centered in the mask and for the video to stay fixed until the mask disappears just like the REFORM CO example.

Here's my HTML and the link to my attempt: https://jsfiddle.net/uex526qs/1/

  <svg x="50%" y="100%" class="knockout-text-container"  height="100%" data-0="opacity:1;transform: scale(1);" data-50p="opacity:0;font-size: 10em;transform: scale(10);">

    <rect class="knockout-text-bg" width="100%" height="100%" fill="#fff" x="0" y="0" fill-opacity="1" mask="url(#knockout-text)"/>

    <mask id="knockout-text">
      <rect width="100%" height="100%" fill="#fff" x="0" y="0"  />

      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 97.73 97.73"><defs></defs><title>shape2</title><g id="Layer_2" data-name="Layer 2"><g id="Content"><path class="cls-1" d="M48.86,97.73A7.72,7.72,0,0,1,41.15,90V7.72a7.72,7.72,0,1,1,15.43,0V90A7.72,7.72,0,0,1,48.86,97.73Z"/><path class="cls-1" d="M90,56.58H7.72a7.72,7.72,0,1,1,0-15.43H90a7.72,7.72,0,1,1,0,15.43Z"/></g></g></svg>

    </mask>

  </svg>

<video autoplay muted loop id="myVideo">
<source src="http://thenewcode.com/assets/videos/ocean-small.mp4" type="video/mp4">
</video>

Any help is appreciated

Body:
You can make an element stay fixed relative to the browser window using position: fixed.

To make your mask scale relative to the element it is aplied to, use:

<mask maskContentUnits="objectBoundingBox">

then use coordinates in the range 0..1.  That's the reason my scale() values are so small. Your shape is roughly 100x100, so I needed to scale by an extra 0.01 to get them down into the 0..1 range.

The rest of your example was more-or-less correct.

$(document).ready(function() {
  var s = skrollr.init();
  constants: {
    //fill the box for a "duration" of 150% of the viewport (pause for 150%)
    //adjust for shorter/longer pause
    knockout: '150p'
  }
})

html, body {
  position: relative;
  margin: 0;
  height: 1500px;
}

.container {
  position: fixed;
}

video {
  width: 100%;
}

.overlay {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/skrollr/0.6.30/skrollr.min.js"></script>

<div class="container">

  <video autoplay muted loop id="myVideo">
    <source src="http://thenewcode.com/assets/videos/ocean-small.mp4" type="video/mp4">
  </video>

  <svg class="overlay" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice">
    <defs>
      <mask id="knockout" maskContentUnits="objectBoundingBox">
        <rect x="0" y="0" width="1" height="1" fill="white"/>
        <g fill="black"
           data-0="transform: translate(0.5px,0.5px) scale(0.0015) translate(-49px,-49px);"
           data-50p="transform: translate(0.5px,0.5px) scale(0.04) translate(-49px,-49px);">
          <path d="M48.86,97.73A7.72,7.72,0,0,1,41.15,90V7.72a7.72,7.72,0,1,1,15.43,0V90A7.72,7.72,0,0,1,48.86,97.73Z"/>
          <path class="cls-1" d="M90,56.58H7.72a7.72,7.72,0,1,1,0-15.43H90a7.72,7.72,0,1,1,0,15.43Z"/>
        </g>
      </mask>
    </defs>
    <rect x="0" y="0" width="100" height="100" fill="white" mask="url(#knockout)"/>
  </svg>

</div>


问:
Cannot read property 'match' on undefined on pushing to heroku
Tried pushing a project to heroku - got the same error when using heroku-cli and when connecting to Github.

Error Log:

```<code>-----> Building dependencies

       Installing node modules (package.json + package-lock)

       npm ERR! Cannot read property 'match' of undefined

</code>```

Package.json

```<code>{
  "name": "myApp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.3",
    "react-social-icons": "^4.1.0",
    "react-spring": "^7.2.10"
  },
...
  "eslintConfig": {
    "extends": "react-app"
  },
  "engines": {
    "node": "10.13.0"
  },
...
  "devDependencies": {
    "react": "^16.7.0"
  }
}

</code>```

React wasn't initially in devDependencies - have that there as an attempt at fixing an earlier error.

Issue persists either way.

答:
I had this same issue, however none of the solutions mentioned above worked for me, I even tried to clean my remote repo, using heroku-repo plugin which by the way you can install using heroku plugins:install heroku-repo followed by heroku repo:reset -a appname to try luck with this one.

The solutions which worked for me was to disable the node_modules cache from heroku. Heroku maintains a cache directory that is persisted between builds. This cache is used to store caches for npm, yarn, and bower.

Try using the following steps.

heroku config:set NODE_MODULES_CACHE=false

now push again with - git push heroku master

Body:
Tried pushing a project to heroku - got the same error when using heroku-cli and when connecting to Github.

Error Log:

-----> Building dependencies

       Installing node modules (package.json + package-lock)

       npm ERR! Cannot read property 'match' of undefined

Package.json

{
  "name": "myApp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.3",
    "react-social-icons": "^4.1.0",
    "react-spring": "^7.2.10"
  },
...
  "eslintConfig": {
    "extends": "react-app"
  },
  "engines": {
    "node": "10.13.0"
  },
...
  "devDependencies": {
    "react": "^16.7.0"
  }
}

React wasn't initially in devDependencies - have that there as an attempt at fixing an earlier error.

Issue persists either way.


问:
Why don't I get an integer overflow when adding two chars?

Possible Duplicate:

  Addition of two chars produces int

Given the following C++ code:

```<code>unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;
</code>```

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.

答:
Neither C++ not C perform arithmetical computations withing "smaller" integer types like, char and short. These types almost always get promoted to int before any further computations begin. So, your expression is really evaluated as

```<code>unsigned char c = ((int) a + (int) b) / 2;
</code>```

P.S. On some exotic platform where the range of int does not cover the range of unsigned char, the type unsigned int will be used as target type for promotion.

Body:
Possible Duplicate:

  Addition of two chars produces int

Given the following C++ code:

unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.

Body:
Neither C++ not C perform arithmetical computations withing "smaller" integer types like, char and short. These types almost always get promoted to int before any further computations begin. So, your expression is really evaluated as

unsigned char c = ((int) a + (int) b) / 2;

P.S. On some exotic platform where the range of int does not cover the range of unsigned char, the type unsigned int will be used as target type for promotion.

ContentLicense: CC BY-SA 3.0


问:
RecyclerView click listener not triggered on row click
Edit
It seems like my @Override for onMentorClick(Mentor mentor) is never being accessed.

I have a recycler view that shows a list of people.
I need to be able to click on one of the people in the list and have a new activity open.

in my adapter, I have the following code:

```<code>private OnMentorClickListener listener;

public interface OnMentorClickListener {
        void onMentorClick(Mentor mentor);
    }

public void setOnMentorClickListener(OnMentorClickListener listener){
        this.listener = listener;
    }
</code>```

in my activity, I have the following code:

```<code>mentorAdapter.setOnMentorClickListener(new MentorAdapter.OnMentorClickListener(){
            @Override
            public void onMentorClick(Mentor mentor) {
                Intent intent = new Intent(MentorActivity.this, MentorAddEditActivity.class);

                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_ID, mentor.getMentor_id());
                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_NAME, mentor.getMentor_name());
                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_PHONE, mentor.getMentor_phone());
                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_EMAIL, mentor.getMentor_email());

                startActivityForResult(intent, EDIT_MENTOR_REQUEST);
            }
        });
</code>```

I have implemented listeners for other portions of my app the exact same way and they all work.
I've scoured my code and this setup seems to be identical to other sections of code.

I get no errors, but when I'm on my "Mentors" page and have all the mentors listed out, nothing happens when I click on one.
No errors, no crashes, no nothing.

I've also tried to just implement the OnMentorClickListener strait into the Activity class like the following:

```<code>public class MentorActivity extends AppCompatActivity implements MentorAdapter.OnMentorClickListener
</code>```

and overriding outside of OnCreate:

```<code>@Override
    public void onMentorClick(Mentor mentor) {
        Intent intent = new Intent(MentorActivity.this, MentorAddEditActivity.class);

        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_ID, mentor.getMentor_id());
        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_NAME, mentor.getMentor_name());
        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_PHONE, mentor.getMentor_phone());
        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_EMAIL, mentor.getMentor_email());

        startActivityForResult(intent, EDIT_MENTOR_REQUEST);
    }
</code>```

This does not work either.

Any thoughts on my I can't actually click the mentor in the RecyclerView?

Entire MentorAdapter for clarification.  This is as identical as possible to all of my other adapters with variable names changed for Mentor.

```<code>public class MentorAdapter extends RecyclerView.Adapter<MentorAdapter.MentorHolder> {
    private static final String TAG = AppRepository.class.getSimpleName();

    private OnMentorClickListener listener;

    private List<Mentor> mentorList = new ArrayList<>();

    class MentorHolder extends RecyclerView.ViewHolder{
        private TextView textViewMentorName;
        private TextView textViewMentorPhone;
        private TextView textViewMentorEmail;

        MentorHolder(@NonNull View itemView) {
            super(itemView);
            textViewMentorName = itemView.findViewById(R.id.textView_mentor_name);
            textViewMentorPhone = itemView.findViewById(R.id.textView_mentor_phone);
            textViewMentorEmail = itemView.findViewById(R.id.textView_mentor_email);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if(listener!=null&&position!=RecyclerView.NO_POSITION){
                        listener.onMentorClick(mentorList.get(position));
                    }
                }
            });
        }
    }

    @NonNull
    @Override
    public MentorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.mentor_item, parent, false);
        return new MentorHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MentorHolder holder, int position) {
        Mentor currentMentor = mentorList.get(position);
        holder.textViewMentorName.setText(currentMentor.getMentor_name());
        holder.textViewMentorEmail.setText(currentMentor.getMentor_email());
        holder.textViewMentorPhone.setText(currentMentor.getMentor_phone());

    }

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

    public void setMentorList(List<Mentor> mentors){
        this.mentorList = mentors;
        notifyDataSetChanged();
    }

    public Mentor getMentorAt(int position){return mentorList.get(position);}

    public interface OnMentorClickListener {
        void onMentorClick(Mentor mentor);
    }

    public void setOnMentorClickListener(OnMentorClickListener listener){
        this.listener = listener;
    }

}
</code>```

答:
Turns out that in my mentor_item.xml file used to create the layout for the Mentor RecyclerView, I had created an  across the entire card on the top layer that I wasn't doing anything with.

Once I removed that ImageButton from the xml file, the clicks were being registered and everything worked as intended.

Thank you for everyone's time.

Body:
Edit
It seems like my @Override for onMentorClick(Mentor mentor) is never being accessed.

I have a recycler view that shows a list of people.
I need to be able to click on one of the people in the list and have a new activity open.

in my adapter, I have the following code:

private OnMentorClickListener listener;

public interface OnMentorClickListener {
        void onMentorClick(Mentor mentor);
    }

public void setOnMentorClickListener(OnMentorClickListener listener){
        this.listener = listener;
    }

in my activity, I have the following code:

mentorAdapter.setOnMentorClickListener(new MentorAdapter.OnMentorClickListener(){
            @Override
            public void onMentorClick(Mentor mentor) {
                Intent intent = new Intent(MentorActivity.this, MentorAddEditActivity.class);

                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_ID, mentor.getMentor_id());
                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_NAME, mentor.getMentor_name());
                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_PHONE, mentor.getMentor_phone());
                intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_EMAIL, mentor.getMentor_email());

                startActivityForResult(intent, EDIT_MENTOR_REQUEST);
            }
        });

I have implemented listeners for other portions of my app the exact same way and they all work.
I've scoured my code and this setup seems to be identical to other sections of code.

I get no errors, but when I'm on my "Mentors" page and have all the mentors listed out, nothing happens when I click on one.
No errors, no crashes, no nothing.

I've also tried to just implement the OnMentorClickListener strait into the Activity class like the following:

public class MentorActivity extends AppCompatActivity implements MentorAdapter.OnMentorClickListener

and overriding outside of OnCreate:

@Override
    public void onMentorClick(Mentor mentor) {
        Intent intent = new Intent(MentorActivity.this, MentorAddEditActivity.class);

        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_ID, mentor.getMentor_id());
        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_NAME, mentor.getMentor_name());
        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_PHONE, mentor.getMentor_phone());
        intent.putExtra(MentorAddEditActivity.EXTRA_MENTOR_EMAIL, mentor.getMentor_email());

        startActivityForResult(intent, EDIT_MENTOR_REQUEST);
    }

This does not work either.

Any thoughts on my I can't actually click the mentor in the RecyclerView?

Entire MentorAdapter for clarification.  This is as identical as possible to all of my other adapters with variable names changed for Mentor.

public class MentorAdapter extends RecyclerView.Adapter<MentorAdapter.MentorHolder> {
    private static final String TAG = AppRepository.class.getSimpleName();

    private OnMentorClickListener listener;

    private List<Mentor> mentorList = new ArrayList<>();

    class MentorHolder extends RecyclerView.ViewHolder{
        private TextView textViewMentorName;
        private TextView textViewMentorPhone;
        private TextView textViewMentorEmail;

        MentorHolder(@NonNull View itemView) {
            super(itemView);
            textViewMentorName = itemView.findViewById(R.id.textView_mentor_name);
            textViewMentorPhone = itemView.findViewById(R.id.textView_mentor_phone);
            textViewMentorEmail = itemView.findViewById(R.id.textView_mentor_email);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if(listener!=null&&position!=RecyclerView.NO_POSITION){
                        listener.onMentorClick(mentorList.get(position));
                    }
                }
            });
        }
    }

    @NonNull
    @Override
    public MentorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.mentor_item, parent, false);
        return new MentorHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MentorHolder holder, int position) {
        Mentor currentMentor = mentorList.get(position);
        holder.textViewMentorName.setText(currentMentor.getMentor_name());
        holder.textViewMentorEmail.setText(currentMentor.getMentor_email());
        holder.textViewMentorPhone.setText(currentMentor.getMentor_phone());

    }

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

    public void setMentorList(List<Mentor> mentors){
        this.mentorList = mentors;
        notifyDataSetChanged();
    }

    public Mentor getMentorAt(int position){return mentorList.get(position);}

    public interface OnMentorClickListener {
        void onMentorClick(Mentor mentor);
    }

    public void setOnMentorClickListener(OnMentorClickListener listener){
        this.listener = listener;
    }

}


问:
Could not set unknown property 'nav_version' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler
I was trying to add Navigation dependencies to utilize the Navigation graph in my project and android studio threw this error.

This is my project Gradle file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
        nav_version = "2.3.0-alpha01" //extra property, used like variables
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

As you can see I added both a $nav_version dependency and the nav_version variable. But, android studio throws a "Could not set unknown property 'nav_version' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler" error. I wonder if it has something to do with the Gradle version or my Kotlin version. I tried to clean and re-build my project but it didn't work. I was wondering if anyone has encountered something similar.

答:
It should be part of app level build.gradle.

Something like

```<code>dependencies {
  def nav_version = "2.3.0-alpha01"

  // Kotlin
  implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
  implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

  // Dynamic Feature Module Support
  implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

  // Testing Navigation
  androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}
</code>```

& top/project level gradle

```<code>buildscript {
    repositories {
        google()
    }
    dependencies {
        def nav_version = "2.3.0-alpha01"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}
</code>```

Or place it like ${nav_version}

```<code>classpath "androidx.navigation:navigation-safe-args-gradle-plugin:${nav_version}"
</code>```

Or

```<code>buildScript {
  ext {
    nav_version = "2.3.0-alpha01"
    kotlin_version = "1.3.50"
  }

    dependencies {
            classpath 'com.android.tools.build:gradle:3.5.3'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}"
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files

            classpath "androidx.navigation:navigation-safe-args-gradle-plugin:${nav_version}"
    }
}
</code>```

Reference
https://developer.android.com/guide/navigation/navigation-getting-started

Body:
I was trying to add Navigation dependencies to utilize the Navigation graph in my project and android studio threw this error.

This is my project Gradle file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
        nav_version = "2.3.0-alpha01" //extra property, used like variables
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

As you can see I added both a $nav_version dependency and the nav_version variable. But, android studio throws a "Could not set unknown property 'nav_version' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler" error. I wonder if it has something to do with the Gradle version or my Kotlin version. I tried to clean and re-build my project but it didn't work. I was wondering if anyone has encountered something similar.

Body:
It should be part of app level build.gradle.

Something like

dependencies {
  def nav_version = "2.3.0-alpha01"

  // Kotlin
  implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
  implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

  // Dynamic Feature Module Support
  implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

  // Testing Navigation
  androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}

& top/project level gradle

buildscript {
    repositories {
        google()
    }
    dependencies {
        def nav_version = "2.3.0-alpha01"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

Or place it like ${nav_version}

classpath "androidx.navigation:navigation-safe-args-gradle-plugin:${nav_version}"

Or

buildScript {
  ext {
    nav_version = "2.3.0-alpha01"
    kotlin_version = "1.3.50"
  }

    dependencies {
            classpath 'com.android.tools.build:gradle:3.5.3'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}"
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files

            classpath "androidx.navigation:navigation-safe-args-gradle-plugin:${nav_version}"
    }
}

Reference
https://developer.android.com/guide/navigation/navigation-getting-started


问:
In paxos, what happens if a proposer is down after its proposal is rejected?

In this figure, the proposal of X is rejected.

At the end of the timeline, S1 and S2 accept X while S3, S4 and S5 accept Y. Proposer X is now supposed to re-send the proposal with value Y.

But what happens if proposer X gets down at that time? How does S1 and S2 eventually learn the value Y?

Thanks in advance!

答:
In this figure, the proposal of X is rejected.

My reading of the diagram is that it is an ”accept request” that is rejected. Page 5 paragraph 1 of Paxos Made Simple describes this message type.

Proposer X is now supposed to re-send the proposal with value Y.

The diagram does not indicate that. Only if Y was seen in response to the blue initial propose messages would the blue proposer have to choose Y. Yet the blue proposer chose X as the value in its ”accept request”. If it is properly following Paxos it could not have ”seen Y” in response to it's initial proposal message. If it had seen it then it must have chosen it and so it wouldn’t have sent X.

In order to really know what is happening you would need to know what responses were seen by each proposer. We cannot see from the diagram what values, if any, were returned in response to the first three blue propose messages. We don’t see in the diagram whether X was previously accepted at any node or whether it was not. We don't know if the blue proposer was ”free to choose” it's own X or had to use an X that was already accepted at one or more nodes.

But what happens if proposer X gets down at that time?

If the blue proposer dies then this is not a problem. The green proposer has successfully fixed the value Y at a majority of the nodes.

How does S1 and S2 eventually learn the value Y?

The more interesting scenario is what happens if the green proposer dies. The green proposer may have sent it's accept request messages containing Y and immediately died. As three of the messages are successful the value Y has been fixed yet the original proposer may not be alive to see the accept response messages. For any further progress to be made a new proposer needs to send a new propose message. As three of the nodes will reply with Y the new proposer will chose Y as the value of it's accept request message. This will be sent to all nodes and if all messages get through, and no other proposer interrupts, then S1 and S2 will become consistent.

The essence of the algorithm is collaboration. If a proposer dies the next proposer will collaborate and chose the highest value previously proposed if any exists.


问:
:after element unexpected height behavior
Could somebody explain why :after element height depends on top property value?

```<code>.bar {
  width: 30px;
  height: 2px;
  background-color: white;
  position: absolute;
  justify-content: center;
  top: 0; bottom: 0; left: 0; right: 0;
  margin: auto;
}
/* Height of bar match to main element 2px */
.bar:before {
  content: '';
  width: 30px;
  height: 2px;
  top: -11px; /* It works */
  background-color: inherit;
  position: absolute;
}
/* Height of bar doesn't match to main element 2px */
.bar:after {
  content: '';
  width: 30px;
  height: 2px;
  top: 10px; /* It doesn't work */
  background-color: inherit;
  position: absolute;
}
</code>```

https://codepen.io/konrad9000/pen/wvBawEm

答: I probably know why this is happening. On smaller full HD monitors in windows display setting scale is default set to 125%. Therefore the width of the browser window is also zoomed.</p>

Body:
Could somebody explain why :after element height depends on top property value?

.bar {
  width: 30px;
  height: 2px;
  background-color: white;
  position: absolute;
  justify-content: center;
  top: 0; bottom: 0; left: 0; right: 0;
  margin: auto;
}
/* Height of bar match to main element 2px */
.bar:before {
  content: '';
  width: 30px;
  height: 2px;
  top: -11px; /* It works */
  background-color: inherit;
  position: absolute;
}
/* Height of bar doesn't match to main element 2px */
.bar:after {
  content: '';
  width: 30px;
  height: 2px;
  top: 10px; /* It doesn't work */
  background-color: inherit;
  position: absolute;
}

https://codepen.io/konrad9000/pen/wvBawEm


问:
Python coding for SQLite is not populating the Database
I found a tutorial online that will let a user input a movie in the command line and it will search IMDB and return all the information. That is working.

So I decided I wanted to be able to import the movie data into a SQLite database. The database is being generated with the table but is not getting the information and I am not getting an error. Here is what I have.

Here is the SQLite code:

```<code>import sqlite3
from sqlite3 import Error
def sql_connection():
    try:
        con=sqlite3.connect('movies.db')
        return con
    except Error:
        print(Error)

def sql_table(con):
    cursorObj=con.cursor()
    cursorObj.execute("CREATE TABLE movies(id integer PRIMARY KEY,\
    tite text, year integer, full cast text, rating integer, plot \
    text )")

    con.commit()
con=sql_connection()
sql_table(con)

def sql_insert(con,entities):
    cursorObj=con.cursor()
    cursorObj.execute('INSERT INTO movies(id, title, year of \
    release, full cast, rating, cast) VALUES(?,?,?,?,?,?)',entities)\
    con.commit()
sql_insert(con,entities)
con.close()
</code>```

答:
I see mistakes:

Typo: tite instead of title in:

```<code>cursorObj.execute("CREATE TABLE movies(id integer PRIMARY KEY,\
tite text, year integer, full cast text, rating integer, plot \
text )")
</code>```

In the second statement, you are attempting to update field year of release, that doesn't exist (you named it year earlier).

```<code>cursorObj.execute('INSERT INTO movies(id, title, year of \
release, full cast, rating, cast) VALUES(?,?,?,?,?,?)',entities)\
con.commit()
</code>```

If you are going to use column names containing spaces, you'll need back ticks or square brackets, something that I would avoid. So instead of full cast I would use the underscore character (_) to avoid spaces: full_cast. But in your create statement you called the field cast so the insert is not going to work.

Body:
I found a tutorial online that will let a user input a movie in the command line and it will search IMDB and return all the information. That is working.

So I decided I wanted to be able to import the movie data into a SQLite database. The database is being generated with the table but is not getting the information and I am not getting an error. Here is what I have.

Here is the SQLite code:

import sqlite3
from sqlite3 import Error
def sql_connection():
    try:
        con=sqlite3.connect('movies.db')
        return con
    except Error:
        print(Error)

def sql_table(con):
    cursorObj=con.cursor()
    cursorObj.execute("CREATE TABLE movies(id integer PRIMARY KEY,\
    tite text, year integer, full cast text, rating integer, plot \
    text )")

    con.commit()
con=sql_connection()
sql_table(con)

def sql_insert(con,entities):
    cursorObj=con.cursor()
    cursorObj.execute('INSERT INTO movies(id, title, year of \
    release, full cast, rating, cast) VALUES(?,?,?,?,?,?)',entities)\
    con.commit()
sql_insert(con,entities)
con.close()

Body:
I see mistakes:

Typo: tite instead of title in:

cursorObj.execute("CREATE TABLE movies(id integer PRIMARY KEY,\
tite text, year integer, full cast text, rating integer, plot \
text )")

In the second statement, you are attempting to update field year of release, that doesn't exist (you named it year earlier).

cursorObj.execute('INSERT INTO movies(id, title, year of \
release, full cast, rating, cast) VALUES(?,?,?,?,?,?)',entities)\
con.commit()

If you are going to use column names containing spaces, you'll need back ticks or square brackets, something that I would avoid. So instead of full cast I would use the underscore character (_) to avoid spaces: full_cast. But in your create statement you called the field cast so the insert is not going to work.


问:
C# Linq nested selects not returning everything
I'm trying to select information from multiple tables via Linq. The query works if I take out the last Api query from apis in Database.PluginApis where apis.PluginId == tenantPlugin.PluginId. If I put the query back in, it results in an error System.Collections.Generic.KeyNotFoundException: The given key 'Name' was not present in the dictionary. Anyone able to see what I am doing wrong?

```<code>var results = (from tenantPlugin in Database.TenantPlugins
                           where tenantPlugin.TenantId == tenantId

                           select new TenantPlugin
                           {
                               PluginId = tenantPlugin.PluginId,
                               IsEnabled = tenantPlugin.IsEnabled,
                               TenantId = tenantPlugin.TenantId,
                               TenantPluginId = tenantPlugin.TenantPluginId,
                               Plugin = (from plugin in Database.Plugins
                                         where plugin.PluginId == tenantPlugin.PluginId
                                         select new Plugin
                                         {
                                             PluginId = plugin.PluginId,
                                             Name = plugin.Name,
                                             Description = plugin.Description,
                                             ImagePath = plugin.ImagePath,
                                             IsActive = plugin.IsActive,
                                             Apis = (from apis in Database.PluginApis
                                                         where apis.PluginId == tenantPlugin.PluginId
                                                     select new PluginApi
                                                     {
                                                         Name = apis.Name
                                                     }).ToList<PluginApi>()
                                         }).FirstOrDefault<Plugin>()
                           });

            return results.ToList();
</code>```

答:
It's seems you have a perfect case to use Include() method. Try:

```<code>var results = Database.TenantPlugins
              .Include(t => t.Plugin.Select(p => p.Apis))
              .Where(t => t.TenantId == tenantId);
</code>```

Body:
I'm trying to select information from multiple tables via Linq. The query works if I take out the last Api query from apis in Database.PluginApis where apis.PluginId == tenantPlugin.PluginId. If I put the query back in, it results in an error System.Collections.Generic.KeyNotFoundException: The given key 'Name' was not present in the dictionary. Anyone able to see what I am doing wrong?

var results = (from tenantPlugin in Database.TenantPlugins
                           where tenantPlugin.TenantId == tenantId

                           select new TenantPlugin
                           {
                               PluginId = tenantPlugin.PluginId,
                               IsEnabled = tenantPlugin.IsEnabled,
                               TenantId = tenantPlugin.TenantId,
                               TenantPluginId = tenantPlugin.TenantPluginId,
                               Plugin = (from plugin in Database.Plugins
                                         where plugin.PluginId == tenantPlugin.PluginId
                                         select new Plugin
                                         {
                                             PluginId = plugin.PluginId,
                                             Name = plugin.Name,
                                             Description = plugin.Description,
                                             ImagePath = plugin.ImagePath,
                                             IsActive = plugin.IsActive,
                                             Apis = (from apis in Database.PluginApis
                                                         where apis.PluginId == tenantPlugin.PluginId
                                                     select new PluginApi
                                                     {
                                                         Name = apis.Name
                                                     }).ToList<PluginApi>()
                                         }).FirstOrDefault<Plugin>()
                           });

            return results.ToList();

Body:
It's seems you have a perfect case to use Include() method. Try:

var results = Database.TenantPlugins
              .Include(t => t.Plugin.Select(p => p.Apis))
              .Where(t => t.TenantId == tenantId);


问:
Compare two list with same length and remove by specific value
I have two lists with the same length, both have 9 items

```<code>listA = ["spain","italy","germany","brazil","france","argentina","peru","bolivia","giappone"]
listB = [0,0,1,1,1,0,1,1,0]
</code>```

I'd like to get listA without value '1' from listB:

```<code>listA = ["spain", "italy","argentina","giappone"]
</code>```

Thanks.

答:
You can use zip.

```<code>listA = ["spain","italy","germany","brazil","france","argentina","peru","bolivia","giappone"]
listB = [0,0,1,1,1,0,1,1,0]
out=[x for x,y in zip(listA,listB) if y==0]
</code>```

Body:
I have two lists with the same length, both have 9 items

listA = ["spain","italy","germany","brazil","france","argentina","peru","bolivia","giappone"]
listB = [0,0,1,1,1,0,1,1,0]

I'd like to get listA without value '1' from listB:

listA = ["spain", "italy","argentina","giappone"]

Thanks.

Body:
You can use zip.

listA = ["spain","italy","germany","brazil","france","argentina","peru","bolivia","giappone"]
listB = [0,0,1,1,1,0,1,1,0]
out=[x for x,y in zip(listA,listB) if y==0]


答:
This is quite a good use case for itertools.compress. With the difference that we need to invert the binary values of the selectors, otherwise it would be the perfect use case :)

```<code>from itertools import compress

list(compress(listA, map(lambda x: 1-x, listB)))
# ['spain', 'italy', 'argentina', 'giappone']
</code>```

Or for a simpler approach in this case you can use zip:

```<code>[x for x,y in zip(listA,listB) if not y]
# ['spain', 'italy', 'argentina', 'giappone']
</code>```

Title: Compare two list with same length and remove by specific value

Body:
This is quite a good use case for itertools.compress. With the difference that we need to invert the binary values of the selectors, otherwise it would be the perfect use case :)

from itertools import compress

list(compress(listA, map(lambda x: 1-x, listB)))
# ['spain', 'italy', 'argentina', 'giappone']

Or for a simpler approach in this case you can use zip:

[x for x,y in zip(listA,listB) if not y]
# ['spain', 'italy', 'argentina', 'giappone']


问:
Define unique variable name
How to create a dynamic ArrayCollecton instance that use unque naming: ac1, ac2..ac999 whether user click a button. Without having to use hardcode variable name.</p>

答:
Another possibly better way is use a dictonary to hold the instances by key name.

```<code>var _htArrayMap:Dictionary = new Dictionary();
_htArrayMap["ary1"] = [1,2,3,4];
</code>```

you can use a string variable as the key.

Dictionaries in as3 are incredibly powerful, and efficent.

Title: Define unique variable name

Body:
Another possibly better way is use a dictonary to hold the instances by key name.

var _htArrayMap:Dictionary = new Dictionary();
_htArrayMap["ary1"] = [1,2,3,4];

you can use a string variable as the key.

Dictionaries in as3 are incredibly powerful, and efficent.


问:
React Hook useEffect has a missing dependency: 'context'. Either include it or remove the dependency array
My goal is to make an API request when user types something on input. I'm getting the data successfully. However the component is rerendering twice and giving me this warning. If I include 'context' I'm getting an infinite loop. Here's my code:

Component.js:

```<code>
const SearchBox = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const { handleSearch, searchResults } = useContext(MovieContext);

  console.log(searchResults);

  useEffect(() => {
    let timer;
    timer = setTimeout(() => {
      handleSearch(searchTerm);
    }, 500);

    return () => clearTimeout(timer);
  }, [searchTerm]);

  const renderResults = () => {
    if (searchResults.length > 0) {
      searchResults.map(result => {
        return (
          <div key={result.Title}>
            <img src={result.Poster} alt={result.Title} />;
          </div>
        );
      });
    }
    return;
  };

  return (
    <>
      <label>
        <b>Search</b>
      </label>
      <input
        className="input"
        value={searchTerm}
        onChange={e => setSearchTerm(e.target.value)}
      />
      <div className="dropdown is-active">
        <div className="dropdown-menu">
          <div className="dropdown-content results">{renderResults()}</div>
        </div>
      </div>
    </>
  );
};

</code>```

On top of this context.searchResults is undefined, although I set the initial value as an empty array. I wanted to know what causing this. What am I doing wrong? Here is my context code below:

Context.js:

```<code>const Context = React.createContext("");

export class MovieStore extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: [],
      handleSearch: this.handleSearch
    };
  }

  handleSearch = async term => {
    try {
      if (term !== "") {
        const response = await axios.get("http://www.omdbapi.com/", {
          params: {
            apikey: apikey,
            s: term
          }
        });
        this.setState({ searchResults: response.data.Search });
      }
    } catch (error) {
      console.log(error);
    }
  };

  render() {
    return (
      <Context.Provider value={this.state}>
        {this.props.children}
      </Context.Provider>
    );
  }
}
</code>```

答:
Exactly the same thing about an infinite loop is mentioned in React docs here. So the cause of infinite loop is that, in context render function, you create new value every time render is called.

```<code>  render() {
    return (
      <Context.Provider
        // ! value object creates every time render is called - it's bad
        value={{ ...this.state, handleSearch: this.handleSearch }}
      >
        {this.props.children}
      </Context.Provider>
    );
  }
</code>```

It causes every consumer to rerender when context state updates. So, if you put context in dependencies array of useEffect, eventually, it'll cause an infinite loop, because context value is always different. Here's what happens:

Context makes a search query.

Context state updates with the new data, which causes all consumers to rerender.

In context consumer useEffect sees that context value has been
updated and it calls setTimeout which will call for another search
in context provider in 500ms.

Consumer calls context to make another search query and we've got an infinite loop!

The solution is to keep context value the same object, while only updating its properties. It can be done by putting all the necessary properties inside of context state. Like that:

```<code>export class MovieStore extends Component {
  handleSearch = async term => {
    try {
      if (term !== "") {
        const response = await axios.get("http://www.omdbapi.com/", {
          params: {
            apikey: "15bfc1e3",
            s: term
          }
        });
        this.setState({ searchResults: response.data.Search });
      }
    } catch (error) {
      console.log(error);
    }
  };

  state = {
    searchResults: [],
    handleSearch: this.handleSearch // <~ put method directly to the state
  };

  render() {
    return (
      <Context.Provider value={this.state}> // <~ Just returning state here
        {this.props.children}
      </Context.Provider>
    );
  }
}
</code>```

Hope it helps <3

Body:
My goal is to make an API request when user types something on input. I'm getting the data successfully. However the component is rerendering twice and giving me this warning. If I include 'context' I'm getting an infinite loop. Here's my code:

Component.js:

const SearchBox = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const { handleSearch, searchResults } = useContext(MovieContext);

  console.log(searchResults);

  useEffect(() => {
    let timer;
    timer = setTimeout(() => {
      handleSearch(searchTerm);
    }, 500);

    return () => clearTimeout(timer);
  }, [searchTerm]);

  const renderResults = () => {
    if (searchResults.length > 0) {
      searchResults.map(result => {
        return (

            ;

        );
      });
    }
    return;
  };

  return (
    <>

        Search

      <input
        className="input"
        value={searchTerm}
        onChange={e => setSearchTerm(e.target.value)}
      />

{renderResults()}

    </>
  );
};

On top of this context.searchResults is undefined, although I set the initial value as an empty array. I wanted to know what causing this. What am I doing wrong? Here is my context code below:

Context.js:

const Context = React.createContext("");

export class MovieStore extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: [],
      handleSearch: this.handleSearch
    };
  }

  handleSearch = async term => {
    try {
      if (term !== "") {
        const response = await axios.get("http://www.omdbapi.com/", {
          params: {
            apikey: apikey,
            s: term
          }
        });
        this.setState({ searchResults: response.data.Search });
      }
    } catch (error) {
      console.log(error);
    }
  };

  render() {
    return (
      <Context.Provider value={this.state}>
        {this.props.children}
      </Context.Provider>
    );
  }
}

Body:
Exactly the same thing about an infinite loop is mentioned in React docs here. So the cause of infinite loop is that, in context render function, you create new value every time render is called.

  render() {
    return (
      <Context.Provider
        // ! value object creates every time render is called - it's bad
        value={{ ...this.state, handleSearch: this.handleSearch }}
      >
        {this.props.children}
      </Context.Provider>
    );
  }

It causes every consumer to rerender when context state updates. So, if you put context in dependencies array of useEffect, eventually, it'll cause an infinite loop, because context value is always different. Here's what happens:

Context makes a search query.

Context state updates with the new data, which causes all consumers to rerender.

In context consumer useEffect sees that context value has been
updated and it calls setTimeout which will call for another search
in context provider in 500ms.

Consumer calls context to make another search query and we've got an infinite loop!

The solution is to keep context value the same object, while only updating its properties. It can be done by putting all the necessary properties inside of context state. Like that:

export class MovieStore extends Component {
  handleSearch = async term => {
    try {
      if (term !== "") {
        const response = await axios.get("http://www.omdbapi.com/", {
          params: {
            apikey: "15bfc1e3",
            s: term
          }
        });
        this.setState({ searchResults: response.data.Search });
      }
    } catch (error) {
      console.log(error);
    }
  };

  state = {
    searchResults: [],
    handleSearch: this.handleSearch // <~ put method directly to the state
  };

  render() {
    return (
      <Context.Provider value={this.state}> // <~ Just returning state here
        {this.props.children}
      </Context.Provider>
    );
  }
}

Hope it helps <3


问:
Permission Required for deleteAfterRead on Camel S3 Component
I'm using the Camel S3 component to read objects uploaded to a particular S3 bucket. The objects are read successfully.

However, using "deleteAfterRead=true"  fails with a 403 (no permission)

I have granted all the permissions in the "write" category, on the bucket, but I still get the error.

Right now these are the permissions. Any idea what I'm doing wrong?

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:DeleteObject",
                "s3:ListBucketMultipartUploads",
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::my-camel-bucket"
        },

        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::*/*"
        }
    ]
}
</code>```

答:
I found the answer: for the s3:DeleteObject Action, I needed to specify the resource with a * at the end. So, arn:aws:s3:::my-camel-bucket/* instead of simply arn:aws:s3:::my-camel-bucket

However, for the ListBucket, I needed just the bucket name. So, what I have working now is this:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:ListBucketMultipartUploads",
        "s3:ListBucket"
      ],
      "Resource": "arn:aws:s3:::my-camel-bucket"
    },
    {
      "Sid": "VisualEditor1",
      "Effect": "Allow",
      "Action": "s3:DeleteObject",
      "Resource": "arn:aws:s3:::my-camel-bucket/*"
    },
    {
      "Sid": "VisualEditor2",
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::*/*"
    }
  ]
}
</code>```

Body:
I'm using the Camel S3 component to read objects uploaded to a particular S3 bucket. The objects are read successfully.

However, using "deleteAfterRead=true"  fails with a 403 (no permission)

I have granted all the permissions in the "write" category, on the bucket, but I still get the error.

Right now these are the permissions. Any idea what I'm doing wrong?

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:DeleteObject",
                "s3:ListBucketMultipartUploads",
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::my-camel-bucket"
        },

        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::*/*"
        }
    ]
}

Body:
I found the answer: for the s3:DeleteObject Action, I needed to specify the resource with a * at the end. So, arn:aws:s3:::my-camel-bucket/* instead of simply arn:aws:s3:::my-camel-bucket

However, for the ListBucket, I needed just the bucket name. So, what I have working now is this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:ListBucketMultipartUploads",
        "s3:ListBucket"
      ],
      "Resource": "arn:aws:s3:::my-camel-bucket"
    },
    {
      "Sid": "VisualEditor1",
      "Effect": "Allow",
      "Action": "s3:DeleteObject",
      "Resource": "arn:aws:s3:::my-camel-bucket/*"
    },
    {
      "Sid": "VisualEditor2",
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::*/*"
    }
  ]
}


问:
Using subprocess.call with variables and single quotes
I'm trying to use the terminal command find path -print0 | xargs -0 stat -f '%m %N' in a Python project. Obviously I need to supply the path so I've been splitting up the expression inside an array as suggested elsewhere. Currently I have subprocess.call(['find', path, '| xargs -0 stat -f "%m %N"']).

The code runs but everything after path is ignored. In fact it throws an error find: | xargs -0 stat -f "%m %N": No such file or directory so clearly I don't understand the way the command is being made up.

Any help would be great

EDIT:

Actually I think supplying the argument from a variable might be better. So i tried command = 'find ' + src_dir + ' -print0 | xargs -0 stat -f \'%m %N\''

Looks OK with print but again when plugged into subprocess.call(osx_command) I get [Errno 2] No such file or directory:

答:
Try adding shell=True

subprocess.call(['find', path, '| xargs -0 stat -f "%m %N"'], shell=True)

shell=True means executing programs through the shell, all user input passed to the program is interpreted according to the syntax and semantic rules of the invoked shell.


问:
Automatically extracting multiple data frames from the list in R
I have a list with 52 elements. Half of the list elements are data frames with 6 columns and different number of rows. The remaining half of the elements are just lists each containing character and integer elements. I want to get all data frames from the list using custom made functions. Ideally, I want to extract all the data frames from the list as separate objects with unique names. I tried to automate it without any success using loops and if/else functions. The thing is, I need to automate this process as I will produce more lists containing 50 to 60 elements. Any suggestion would be most appreciated.</p>

答:
with l as your list:

```<code>classes.in.list=lapply(l,class)          # find classes in your list
idx=which(classes.in.list=="data.frame") # find indices of data.frames
mydfs=l[idx]                             # subset your list
data.table::rbindlist(mydfs,idcol=T)     # fast rbind with ID column (install data.table library)
</code>```

Body:
with l as your list:

classes.in.list=lapply(l,class)          # find classes in your list
idx=which(classes.in.list=="data.frame") # find indices of data.frames
mydfs=l[idx]                             # subset your list
data.table::rbindlist(mydfs,idcol=T)     # fast rbind with ID column (install data.table library)


问:
Mysql Node.js query fails but works in workbench
I'm getting the callback error 'Incorrect parameters in the call to native function \'json_object\' for the below query in node.js but the same query works when I try it out in the mysql workbench?</p>

```<code>SELECT t1.typeId AS typeId,
UNIX_TIMESTAMP(t1.hour) AS hour,
t2.userInfo AS userInfo
FROM UserCommits t1
INNER JOIN (   SELECT  t1.id AS id,
JSON_OBJECT("id", t1.id,
"name", t1.name,
"birthUnix", UNIX_TIMESTAMP(t1.birthDate),
"gender", t1.gender,
"image", t2.secure_url,
"connectionInfo", t3.connectionInfo) AS userInfo
FROM Users t1
LEFT JOIN (
SELECT userId,
secure_url
FROM UserProfileImages
WHERE id IN (
SELECT MAX(id)
FROM UserProfileImages
GROUP BY userId
)
) t2
ON t1.id = t2.userId
LEFT JOIN (
SELECT connectionId,
JSON_OBJECT(
"id", id,
"createdUnix", UNIX_TIMESTAMP(createdDt)
) AS connectionInfo
FROM UserConnections
WHERE userId = 98
) t3
ON t1.id = t3.connectionId
) t2
ON t1.userId = t2.id
WHERE t1.locationId = 41
</code>```

答:
Found the issue..

To insert a JSON_Object from a subquery into another JSON_Object there mysql checks that there is a 1 to 1 relationship.  I fixed the issue by updating the subquery to include a Group By statement on the join column.

```<code>(
    SELECT connectionId,
           JSON_OBJECT(
               "id", id,
               "createdUnix", UNIX_TIMESTAMP(createdDt)
           ) AS connectionInfo
    FROM UserConnections
    WHERE id IN (
        SELECT MAX(id)
        FROM UserConnections
        WHERE userId = ${ownerId}
        GROUP BY connectionId
    )
           )
</code>```

Body:
I'm getting the callback error 'Incorrect parameters in the call to native function \'json_object\' for the below query in node.js but the same query works when I try it out in the mysql workbench?

SELECT t1.typeId AS typeId,
UNIX_TIMESTAMP(t1.hour) AS hour,
t2.userInfo AS userInfo
FROM UserCommits t1
INNER JOIN (   SELECT  t1.id AS id,
JSON_OBJECT("id", t1.id,
"name", t1.name,
"birthUnix", UNIX_TIMESTAMP(t1.birthDate),
"gender", t1.gender,
"image", t2.secure_url,
"connectionInfo", t3.connectionInfo) AS userInfo
FROM Users t1
LEFT JOIN (
SELECT userId,
secure_url
FROM UserProfileImages
WHERE id IN (
SELECT MAX(id)
FROM UserProfileImages
GROUP BY userId
)
) t2
ON t1.id = t2.userId
LEFT JOIN (
SELECT connectionId,
JSON_OBJECT(
"id", id,
"createdUnix", UNIX_TIMESTAMP(createdDt)
) AS connectionInfo
FROM UserConnections
WHERE userId = 98
) t3
ON t1.id = t3.connectionId
) t2
ON t1.userId = t2.id
WHERE t1.locationId = 41

Body:
Found the issue..

To insert a JSON_Object from a subquery into another JSON_Object there mysql checks that there is a 1 to 1 relationship.  I fixed the issue by updating the subquery to include a Group By statement on the join column.

(
    SELECT connectionId,
           JSON_OBJECT(
               "id", id,
               "createdUnix", UNIX_TIMESTAMP(createdDt)
           ) AS connectionInfo
    FROM UserConnections
    WHERE id IN (
        SELECT MAX(id)
        FROM UserConnections
        WHERE userId = ${ownerId}
        GROUP BY connectionId
    )
           )


问:
AWS Beanstalk to RDS issues with DataNucleus
I am trying to run a JSP file deployed to Amazon's Beanstalk, which uses DataNucleus to connect to RDS, and am getting the following error:

```
javax.jdo.JDOFatalDataStoreException: No suitable driver found for jdbc:mysql://mydbblahblah.rds.amazonaws.com:3306/mydb?autoReconnect=true

root cause

java.sql.SQLException: No suitable driver found for jdbc:mysql://bmydbblahblah.rds.amazonaws.com:3306/mydb?autoReconnect=true
    java.sql.DriverManager.getConnection(DriverManager.java:640)
    java.sql.DriverManager.getConnection(DriverManager.java:200)
```

Now I have the MySQL connector files in the classpath (it is at WebContent/WEB-INF/lib/mysql-connector-java-5.1.15-bin.jar, so this should work.

I have also confirmed that if I remove the library from there, I get the "com.mysql.jdbc.Driver not found on CLASSPATH" error.

Here is what my datanucleus.properties file looks like this:

```
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory

javax.jdo.option.ConnectionDriverName=com.mysql.jdbc.Driver
javax.jdo.option.ConnectionURL=jdbc:mysql://bmydbblahblah.rds.amazonaws.com:3306/mydb
#javax.jdo.option.ConnectionURL=jdbc:mysql://localhost:3306/mydb?autoReconnect=true
javax.jdo.option.ConnectionUserName=user
javax.jdo.option.ConnectionPassword=pwnothere
```

All of this works on my local Tomcat connecting to RDS. It only fails when running on Beanstalk.

Any ideas what might be causing this issue?

Thanks

答: So we downgraded to DataNucleus 2.0 without any other changes, and the issue disappeared. Sad, but it worked. I cannot recommend newer versions of DataNucleus with MySQL.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to run a JSP file deployed to Amazon's Beanstalk, which uses DataNucleus to connect to RDS, and am getting the following error:

javax.jdo.JDOFatalDataStoreException: No suitable driver found for jdbc:mysql://mydbblahblah.rds.amazonaws.com:3306/mydb?autoReconnect=true

root cause

java.sql.SQLException: No suitable driver found for jdbc:mysql://bmydbblahblah.rds.amazonaws.com:3306/mydb?autoReconnect=true
    java.sql.DriverManager.getConnection(DriverManager.java:640)
    java.sql.DriverManager.getConnection(DriverManager.java:200)

Now I have the MySQL connector files in the classpath (it is at WebContent/WEB-INF/lib/mysql-connector-java-5.1.15-bin.jar, so this should work.

I have also confirmed that if I remove the library from there, I get the "com.mysql.jdbc.Driver not found on CLASSPATH" error.

Here is what my datanucleus.properties file looks like this:

javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory

javax.jdo.option.ConnectionDriverName=com.mysql.jdbc.Driver
javax.jdo.option.ConnectionURL=jdbc:mysql://bmydbblahblah.rds.amazonaws.com:3306/mydb
#javax.jdo.option.ConnectionURL=jdbc:mysql://localhost:3306/mydb?autoReconnect=true
javax.jdo.option.ConnectionUserName=user
javax.jdo.option.ConnectionPassword=pwnothere

All of this works on my local Tomcat connecting to RDS. It only fails when running on Beanstalk.

Any ideas what might be causing this issue?

Thanks


问:
Converting a number into the format minutes:seconds.hundreths in bash script?
I am implementing the top command. I need to calculate the Time+ field just like the top command.
As of right now, I am getting the utime and stime then I put the system to sleep and then getting it these values again. I add the 4 quantities and divide the total by 100 which gives me a number. Here is the code for reference:

```<code>oldutime=$(awk '{print $14}' /proc/$word/stat )
oldstime=$(awk '{print $15}' /proc/$word/stat )

newutime=$(awk '{print $14}' /proc/$word/stat )
newstime=$(awk '{print $15}' /proc/$word/stat )

total_time=`expr $oldutime + $oldstime + $newutime + $newstime`

timee=$((total_time / 100))
</code>```

After this I need to format this number so that it looks like the output of TIME+ field (minutes: seconds.hunderehts) in the top program and I need help doing that. I was looking at the date command but couldn't figure it out.

EDIT:

Desired for format: 0:00.24 (minutes:seconds.hunderdths)
Output: 360

答:
The following scriptlet can be used to format time in milliseconds:

Code assume total_time is calculated - either per OP question, or modified for comments (using $((...))) instead of expr.

```<code># Calculate total time in tick
total_time=...
ticks_per_sec=$(getconf CLK_TCK)
# Seconds times 100
s100=$((total_time*100/ticks_per_sec))
printf '%d:%02d.%02d\n' $((s100/100/60)) $((s100/100%60)) $((s100%100))
</code>```

Body:
I am implementing the top command. I need to calculate the Time+ field just like the top command.
As of right now, I am getting the utime and stime then I put the system to sleep and then getting it these values again. I add the 4 quantities and divide the total by 100 which gives me a number. Here is the code for reference:

oldutime=$(awk '{print $14}' /proc/$word/stat )
oldstime=$(awk '{print $15}' /proc/$word/stat )

newutime=$(awk '{print $14}' /proc/$word/stat )
newstime=$(awk '{print $15}' /proc/$word/stat )

total_time=`expr $oldutime + $oldstime + $newutime + $newstime`

timee=$((total_time / 100))

After this I need to format this number so that it looks like the output of TIME+ field (minutes: seconds.hunderehts) in the top program and I need help doing that. I was looking at the date command but couldn't figure it out.

EDIT:

Desired for format: 0:00.24 (minutes:seconds.hunderdths)
Output: 360

Body:
The following scriptlet can be used to format time in milliseconds:

Code assume total_time is calculated - either per OP question, or modified for comments (using $((...))) instead of expr.

# Calculate total time in tick
total_time=...
ticks_per_sec=$(getconf CLK_TCK)
# Seconds times 100
s100=$((total_time*100/ticks_per_sec))
printf '%d:%02d.%02d\n' $((s100/100/60)) $((s100/100%60)) $((s100%100))


问:
Count how many rows have the same value
How do I write an SQL query to count the total number of a specific num value in the num column of a table?

Assuming we have the following data.

NAME
NUM

SAM
1

BOB
1

JAKE
2

JOHN
4

Take the following query:

SELECT WHERE num = 1;
```

This would return these two rows.

NAME
NUM

SAM
1

BOB
1

答:
Use this query this will give your output:</p>

```<code>select
  t.name
  ,( select
       count (*) as num_value
     from Table
      where num =t.num) cnt
from Table t;
</code>```

Title: Count how many rows have the same value

Body:
How do I write an SQL query to count the total number of a specific num value in the num column of a table?

Assuming we have the following data.

NAME
NUM

SAM
1

BOB
1

JAKE
2

JOHN
4

Take the following query:

SELECT WHERE num = 1;

This would return these two rows.

NAME
NUM

SAM
1

BOB
1

Body:
Use this query this will give your output:

select
  t.name
  ,( select
       count (*) as num_value
     from Table
      where num =t.num) cnt
from Table t;


问:
'Basic' attribute type should not be a container;For both properties-based access both setter and getter should be present
I'm new to Spring boot.
I try to implement the login and registration function using Spring Security and Hibernate.

First, I use Hibernate to generate the persistence mapping Entity Class from the database. And I need to implement UserDetails interface in the UserEntity class, but the problem happened.

I can't implement the methods in UserDetails.

Error occurs when I try to implement getAuthorities.
Here is the error information.

'Basic' attribute type should not be a container.
Inspection info: This inspection checks for the following JPA specification errors:

Attribute types checking(collection,entity,embeddable,etc.)

For property-based access both setter and getter should be present
Inspection info:This inspection checks for the following JPA specification errors:

More than one attribute configured for method/field

Attribute cannot be used in Embeddable object(JPA 1.0)

Persistent attribute metadata should be specified on field or property getter

For property-based access both setter and getter should be present

Here is my code.

```<code>package com.example.demo;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Entity
@Table(name = "user", schema = "demo", catalog = "")
public class UserEntity implements UserDetails {
    private String username;
    private String password;
    private String role;
    private String nickname;
    private String phone;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(){
        String[] authorities=role.split(",");
        List<SimpleGrantedAuthority> authorityList=new ArrayList<>();
        for(String string:authorities)
            authorityList.add(new SimpleGrantedAuthority(string));
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Id
    @Column(name = "username", nullable = false, length = 16)
    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "password", nullable = true, length = 32)
    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "nickname", nullable = true, length = 32)
    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    @Basic
    @Column(name = "phone", nullable = true, length = 11)
    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UserEntity that = (UserEntity) o;
        return Objects.equals(username, that.username) &&
                Objects.equals(password, that.password) &&
                Objects.equals(nickname, that.nickname) &&
                Objects.equals(phone, that.phone);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, password, nickname, phone);
    }
}
</code>```

And I have created a totally the same class as the UserEntity, with implementing UserDetails, and the problem disappeared. Maybe that's a little stupid but I've tried many times. I can't solve it. Please help.

答: Try @OneToMany or @Transient instead of @Basic annotations.

Body:
I'm new to Spring boot.
I try to implement the login and registration function using Spring Security and Hibernate.

First, I use Hibernate to generate the persistence mapping Entity Class from the database. And I need to implement UserDetails interface in the UserEntity class, but the problem happened.

I can't implement the methods in UserDetails.

Error occurs when I try to implement getAuthorities.
Here is the error information.

'Basic' attribute type should not be a container.
Inspection info: This inspection checks for the following JPA specification errors:

Attribute types checking(collection,entity,embeddable,etc.)

For property-based access both setter and getter should be present
Inspection info:This inspection checks for the following JPA specification errors:

More than one attribute configured for method/field

Attribute cannot be used in Embeddable object(JPA 1.0)

Persistent attribute metadata should be specified on field or property getter

For property-based access both setter and getter should be present

Here is my code.

package com.example.demo;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Entity
@Table(name = "user", schema = "demo", catalog = "")
public class UserEntity implements UserDetails {
    private String username;
    private String password;
    private String role;
    private String nickname;
    private String phone;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(){
        String[] authorities=role.split(",");
        List<SimpleGrantedAuthority> authorityList=new ArrayList<>();
        for(String string:authorities)
            authorityList.add(new SimpleGrantedAuthority(string));
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Id
    @Column(name = "username", nullable = false, length = 16)
    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "password", nullable = true, length = 32)
    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "nickname", nullable = true, length = 32)
    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    @Basic
    @Column(name = "phone", nullable = true, length = 11)
    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UserEntity that = (UserEntity) o;
        return Objects.equals(username, that.username) &&
                Objects.equals(password, that.password) &&
                Objects.equals(nickname, that.nickname) &&
                Objects.equals(phone, that.phone);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, password, nickname, phone);
    }
}

And I have created a totally the same class as the UserEntity, with implementing UserDetails, and the problem disappeared. Maybe that's a little stupid but I've tried many times. I can't solve it. Please help.


问:
input tooltop plugin
I am looking for a plugin that displays something like tooltip that I can put html inside.

Something like a datepicker were I have a little image that allows me to open a helper that will assist fill the input.

Do you know such plugin?

答:
jQuery Tooltip Plugin has worked well for me, including with forms:</p>

```<code>$('#myImage').tooltip({
    delay: 0,
    showURL: false,
    bodyHandler: function() {
        return $("<form><!-- Add form contents here --></form>");
    }
});
</code>```

Title: input tooltop plugin

Body:
jQuery Tooltip Plugin has worked well for me, including with forms:

$('#myImage').tooltip({
    delay: 0,
    showURL: false,
    bodyHandler: function() {
        return $("<form><!-- Add form contents here --></form>");
    }
});


问:
Side Menu matching full screen
CSS

```<code>.sidenav {
    height: 100%;
    position: relative;
    overflow-y: scroll;
    background: #000000;
    width: 15%;
}
</code>```

Setting the height to 100% makes the menu to cover the full screen properly, but if the content in my page is more and i need to scroll down, the side menu looks awkward as its height is the same as the screen size of my computer.

I want the height of the scrollbar to take up the whole screens height even when i scroll down. How can i achieve that

答:
You can try this............

* {
  margin: 0;
  padding: 0;
}

body {
  padding: 30px 30px 30px 230px;
}

.sideNavbar {
  height: 100vh;
  width: 150px;
  background: #0004;
  overflow-x: hidden;
  overflow-y: scroll;
  padding: 20px 30px;
  position: fixed;
  top: 0;
  left: 0;
}

.sideNavbar .sidemenu {
  margin: 0;
  padding: 0;
  list-style: none;
}

.sideNavbar .sidemenu li {
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sideNavbar">
  <ul class="sidemenu">
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
    <li>Menu Item</li>
  </ul>
</div>

<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Magnam nisi ad dignissimos aspernatur molestiae dhic libero pariatur assumenda sit. Soluta eveniet, quos, porro, aliquam commodi quae am assumenda iure, nesciunt aut, animi re ad eum, provident, molestias ullam accusamus ea suscipit cum!</p>
<br>
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque nam necessitatibus ipsum, consequatur corporis culpa, ducimus cum dignissimos ut quae nihil domodi dolorum est. Magni amet praesentium sint voluptates odio, ullam optio quia nobis inventore recusandae laudantium quo, sit repudiandae aliquid! Consequuntur, culpa! Invens suscipit est! Cumque dolorem enim, deluta temporibus cupiditate cum.
</p>
<br>
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque nam necessitatibus ipsum, consequatur corporis culpa, ducimus cum dignissimos ut quae nihil domodi dolorum est. Magni amet praesentium sint voluptates odio, ullam optio quia nobis inventore recusandae laudantium quo, sit repudiandae aliquid! Consequuntur, culpa! Invens suscipit est! Cumque dolorem enim, deluta temporibus cupiditate cum.
</p></code>```

Title: Side Menu matching full screen

Body:
CSS

.sidenav {
    height: 100%;
    position: relative;
    overflow-y: scroll;
    background: #000000;
    width: 15%;
}

Setting the height to 100% makes the menu to cover the full screen properly, but if the content in my page is more and i need to scroll down, the side menu looks awkward as its height is the same as the screen size of my computer.

I want the height of the scrollbar to take up the whole screens height even when i scroll down. How can i achieve that

Body:
You can try this............

* {
  margin: 0;
  padding: 0;
}

body {
  padding: 30px 30px 30px 230px;
}

.sideNavbar {
  height: 100vh;
  width: 150px;
  background: #0004;
  overflow-x: hidden;
  overflow-y: scroll;
  padding: 20px 30px;
  position: fixed;
  top: 0;
  left: 0;
}

.sideNavbar .sidemenu {
  margin: 0;
  padding: 0;
  list-style: none;
}

.sideNavbar .sidemenu li {
  margin-bottom: 10px;
}

<div class="sideNavbar">
  <ul class="sidemenu">
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
    <li><a href="#">Menu Item</a></li>
  </ul>
</div>

<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Magnam nisi ad dignissimos aspernatur molestiae dhic libero pariatur assumenda sit. Soluta eveniet, quos, porro, aliquam commodi quae am assumenda iure, nesciunt aut, animi re ad eum, provident, molestias ullam accusamus ea suscipit cum!</p>
<br>
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque nam necessitatibus ipsum, consequatur corporis culpa, ducimus cum dignissimos ut quae nihil domodi dolorum est. Magni amet praesentium sint voluptates odio, ullam optio quia nobis inventore recusandae laudantium quo, sit repudiandae aliquid! Consequuntur, culpa! Invens suscipit est! Cumque dolorem enim, deluta temporibus cupiditate cum.
</p>
<br>
<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque nam necessitatibus ipsum, consequatur corporis culpa, ducimus cum dignissimos ut quae nihil domodi dolorum est. Magni amet praesentium sint voluptates odio, ullam optio quia nobis inventore recusandae laudantium quo, sit repudiandae aliquid! Consequuntur, culpa! Invens suscipit est! Cumque dolorem enim, deluta temporibus cupiditate cum.
</p>


问:
Spring boot Rest API Request Body (POST)
Request Body has one parameter such as int data. Where as if i pass extra parameter which is not there in the class it does not throw an error.
Why its able to consume the data which is not part of request body.</p>

答:
By default spring will recognize only the declared request params remaining parameters will be ignored. If you want to restrict it. you can do like this

```<code>Add HttpServletRequest request in the method parameter
String params = request.getQueryString();
</code>```

in the method body validate the params.

But In my opinion a more pragmatic approach may be to ignore the invalid params.

Body:
By default spring will recognize only the declared request params remaining parameters will be ignored. If you want to restrict it. you can do like this

Add HttpServletRequest request in the method parameter
String params = request.getQueryString();

in the method body validate the params.

But In my opinion a more pragmatic approach may be to ignore the invalid params.


问:
Multiple web frameworks in single AWS instance?
This is an infrastructure design question. Is it better to:

Run multiple web frameworks on a single AWS instance?

Run each framework in separate AWS instances?

Here are the web frameworks used:

Backend: Django + PostgreSQL

Frontend: NodeJS

Forum: Ruby on Rails + PostgreSQL

Option 1 pros:

No need to worry about AWS instance type (just use a powerful one)

Easy to maintain when everything is in one place, only 1 instance

Option 2 pros:

Better allocation of AWS resources depending on load (backend / frontend / forum). Easier to scale?

I am not sure what's the better option. Would love to hear your experience and opinion on this. Thanks.

答:
There are a ton of people putting all of this inside a single AMI, spinning them up behind an ELB and running it in production.

Is it advised? Not really.

The issue with this is pretty much what you stated, each has variable resource requirements (besides NodeJS) and you will be overloading EC2 instances quickly with any type of load; when they aren't seeing load you will be burning $$$ by having a powerful enough instance (for the expected load) running 24/7.

In terms of a close but slightly better option, putting each of these frameworks inside their own Docker container allows them to run alongside each other on the same instance but in a segregated way. Once they are in Docker, you might as well run them in ECS or EKS on Fargate.

In terms of the "AWS Best Practice" route, and wearing my Solution Architect hat, I would recommend this:

NodeJS is put into S3, with CloudFront in front of it.

Python(Django) is moved to Lambda or Lambda EDGE.

PostgreSQL is moved to RDS, or better yet - DynamoDB.

The advantage to this is cost and scalability. S3 scales infinitely and is highly available and dirt cheap. Lambda is event-based so you are into "pay per usage" rather than "pay per hour". RDS is a $ sink but it takes care of backups and makes running a DB a simple task. DynamoDB is a "pay per usage" service and would make your entire stack significantly cheaper if you can pull it off.


答:
```<code>listA = ["spain", "italy", "germany", "brazil",
         "france", "argentina", "peru", "bolivia", "giappone"]
listB = [0, 0, 1, 1, 1, 0, 1, 1, 0]
i = -1
for item in listB:
    i += 1
    if item == 0:
        print(listA[i])
</code>```

Body:
I have two lists with the same length, both have 9 items

listA = ["spain","italy","germany","brazil","france","argentina","peru","bolivia","giappone"]
listB = [0,0,1,1,1,0,1,1,0]

I'd like to get listA without value '1' from listB:

listA = ["spain", "italy","argentina","giappone"]

Thanks.