问:
Keycodes / onclick enter, show Multiple innerHTML names
When I move the 4 arrows on the keyboard, the green hover color moves over each button. I want when I press "Enter" to write the number that corresponds to each box. For example now I have "columns" and it writes 0,1,2,3,4,5,6. I want to write One Two Three etc .. Of course I use Handebars, Backcone, Lodash so I do not want to change anything in HTML (Handlebars.compile) Thank you very much ..

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;

case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
 rowButtons = rowButtons == $rows.click;

 document.getElementById('screen').innerHTML = columns;

break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');
}
});

// Click function on handlebars
// Affect href ie.  (It doesn't work on enter(13)
var ListView = BacListViewkbone.View.extend({
events: {
'click a': 'onClick'
},
render: function() {
var rawHTML = _template({ items: myList });
this.$el.html(rawHTML);
this.$items = this.$el.find('a');
return this;
},

onClick: function(e) {
var id = $(e.currentTarget).attr('patterns');
dispatcher.trigger(dispatcher.EventKeys.PATTERNS_SELECTED, myList[id]);
}
});
function init(options) {
dispatcher.register(evs);
new ListView(options).render();
}

return {
init: init
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}</code>```

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

href="#" patterns="twelve" id="twelve" onClick="twelve()">Twelve

Numbers
```

答:
You mean like this?

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');

  }
});

$(window).keydown(function(e){
  if(e.which == 13){
    //get id of the selected li>a element
    var elementId = document.getElementsByClassName('selected')[0].children[0].id;
    document.getElementById('screen').innerHTML = elementId;
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}</code>```

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Twelve

Numbers
```
</div>
</div>
</p>
<p>I've removed</p>
```case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
rowButtons = rowButtons == $rows.click;

document.getElementById('screen').innerHTML = columns;
break;
```
<p>and added</p>
```$(window).keydown(function(e){
    if(e.which == 13){
        //get id of the selected li>a element
        var elementId = document.getElementsByClassName('selected')[0].children[0].id;
        document.getElementById('screen').innerHTML = elementId;
    }
})
```

After your window.keypress function for a dedicated Enter button event listener, also removed all the onClick functions under the assumptions that you thought of using them to get these values but ended up seeing how much work that logic will be so instead I look at the li element with the selected class and use it's child a tag's ID since it is already a name value of the numeric value instead of having to create an array of values for a lookup.

Body:
When I move the 4 arrows on the keyboard, the green hover color moves over each button. I want when I press "Enter" to write the number that corresponds to each box. For example now I have "columns" and it writes 0,1,2,3,4,5,6. I want to write One Two Three etc .. Of course I use Handebars, Backcone, Lodash so I do not want to change anything in HTML (Handlebars.compile) Thank you very much ..

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;

case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
 rowButtons = rowButtons == $rows.click;

 document.getElementById('screen').innerHTML = columns;

break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');
}
});

// Click function on handlebars
// Affect href ie.  (It doesn't work on enter(13)
var ListView = BacListViewkbone.View.extend({
events: {
'click a': 'onClick'
},
render: function() {
var rawHTML = _template({ items: myList });
this.$el.html(rawHTML);
this.$items = this.$el.find('a');
return this;
},

onClick: function(e) {
var id = $(e.currentTarget).attr('patterns');
dispatcher.trigger(dispatcher.EventKeys.PATTERNS_SELECTED, myList[id]);
}
});
function init(options) {
dispatcher.register(evs);
new ListView(options).render();
}

return {
init: init
}

li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Twelve

Numbers

Body:
You mean like this?

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');

  }
});

$(window).keydown(function(e){
  if(e.which == 13){
    //get id of the selected li>a element
    var elementId = document.getElementsByClassName('selected')[0].children[0].id;
    document.getElementById('screen').innerHTML = elementId;
  }
})

li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="allRows">
<div class="multiple">
<li><a href="#" patterns="one" id="one">One</a></li>
<li><a href="#" patterns="two" id="two">Two</a></li>
<li><a href="#" patterns="three" id="three">Three</a></li>
<li><a href="#" patterns="four" id="four">Four</a></li>
<li><a href="#" patterns="five" id="five">Five</a></li>
<li><a href="#" patterns="six" id="six">Six</a></li>
</div>
<div class="multiple">
<li><a href="#" patterns="seven" id="seven">Seven</a></li>
<li><a href="#" patterns="eight" id="eight">Eight</a></li>
<li><a href="#" patterns="nine" id="nine">Nine</a></li>
<li><a href="#" patterns="ten" id="ten">Ten</a></li>
<li><a href="#" patterns="eleven" id="eleven">Eleven</a></li>
<li><a href="#" patterns="twelve" id="twelve">Twelve</a></li></div>
</ul>

<div id="screen">Numbers</div>

I've removed

case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
rowButtons = rowButtons == $rows.click;

document.getElementById('screen').innerHTML = columns;
break;

and added

$(window).keydown(function(e){
    if(e.which == 13){
        //get id of the selected li>a element
        var elementId = document.getElementsByClassName('selected')[0].children[0].id;
        document.getElementById('screen').innerHTML = elementId;
    }
})

After your window.keypress function for a dedicated Enter button event listener, also removed all the onClick functions under the assumptions that you thought of using them to get these values but ended up seeing how much work that logic will be so instead I look at the li element with the selected class and use it's child a tag's ID since it is already a name value of the numeric value instead of having to create an array of values for a lookup.


来源: stackexchange

问:
CameraX can't initialize
I try to use CameraView. And I'm a beginner in Android. I read some articles and information on class but I am not able to make it works.
I have the following errors :

Caused by: java.lang.IllegalStateException: CameraX is not initialized properly. Either CameraX.initialize() needs to have been called or the CameraXConfig.Provider interface must be implemented by your Application class

Here is my code :

activity_main.xml

```<code>   <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:theme="@style/AppTheme">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.camera.view.CameraView
    android:id="@+id/view_camera"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

MainActivity.java:

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.camera2.Camera2Config;
import androidx.camera.core.CameraX;
import androidx.camera.core.CameraXConfig;
import androidx.camera.core.impl.CameraFactory;
import androidx.camera.core.impl.PreviewConfig;
import androidx.camera.view.CameraView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements CameraXConfig.Provider {

    private CameraView view_camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view_camera = findViewById(R.id.view_camera);
        view_camera.bindToLifecycle(this);
    }

    @NonNull
    @Override
    public CameraXConfig getCameraXConfig() {
        return Camera2Config.defaultConfig();
    }
}
</code>```

And the manifest :

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

The gradle file for app:

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.1"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 26
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    def camerax_version = "1.0.0-alpha10"// Add the CameraX core dependency implementation
    implementation "androidx.camera:camera-core:${camerax_version}"// Add the CameraX Camera2 API interop support dependency
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation "androidx.camera:camera-view:1.0.0-alpha06"
    // If you want to use the CameraX Extensions library
    implementation "androidx.camera:camera-extensions:1.0.0-alpha06"
    // If you want to use the CameraX Lifecycle library
    implementation "androidx.camera:camera-lifecycle:1.0.0-alpha03"
}
</code>```

Thanks for your help.

答:
My camera-camera2 and camera-lifecycle libraries were using version 1.0.2 while the camera-view library was using 1.1.0-beta01.

Changing them all to use 1.1.0-beta01 fixed it.

I'm guessing something in the upgrade from 1.0.2 to 1.1.0-beta01 causes an initialization error.

ContentLicense: CC BY-SA 4.0

Title: CameraX can't initialize

Body:
I try to use CameraView. And I'm a beginner in Android. I read some articles and information on class but I am not able to make it works.
I have the following errors :

Caused by: java.lang.IllegalStateException: CameraX is not initialized properly. Either CameraX.initialize() needs to have been called or the CameraXConfig.Provider interface must be implemented by your Application class

Here is my code :

activity_main.xml

   <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:theme="@style/AppTheme">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.camera.view.CameraView
    android:id="@+id/view_camera"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

MainActivity.java:

    package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.camera2.Camera2Config;
import androidx.camera.core.CameraX;
import androidx.camera.core.CameraXConfig;
import androidx.camera.core.impl.CameraFactory;
import androidx.camera.core.impl.PreviewConfig;
import androidx.camera.view.CameraView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements CameraXConfig.Provider {

    private CameraView view_camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view_camera = findViewById(R.id.view_camera);
        view_camera.bindToLifecycle(this);
    }

    @NonNull
    @Override
    public CameraXConfig getCameraXConfig() {
        return Camera2Config.defaultConfig();
    }
}

And the manifest :

<?xml version="1.0" encoding="utf-8"?>

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

The gradle file for app:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.1"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 26
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    def camerax_version = "1.0.0-alpha10"// Add the CameraX core dependency implementation
    implementation "androidx.camera:camera-core:${camerax_version}"// Add the CameraX Camera2 API interop support dependency
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation "androidx.camera:camera-view:1.0.0-alpha06"
    // If you want to use the CameraX Extensions library
    implementation "androidx.camera:camera-extensions:1.0.0-alpha06"
    // If you want to use the CameraX Lifecycle library
    implementation "androidx.camera:camera-lifecycle:1.0.0-alpha03"
}

Thanks for your help.


问:
How can I get a user's name from their email?
I'm trying to get a user's name from their email and we are all on the same business domain. I saw a post here detailing how to do it if you want to pull from the contacts list. The problem is when I try it myself, it knows that there is contact for me, but it returns all of the values as null. If I use another contact email, then it pulls the info just fine.

The link says that there should be another way to do it but you need admin privileges. I can get that, but all of the links to the usermanager documentation are broken. Also, searching usermanager doesn't come up with anything on Google's developer site.

```<code>var email = Session.getActiveUser().getEmail();
Browser.msgBox(email)

var self = ContactsApp.getContact(email);
var name = self.getFullName();
</code>```

答:
If parsing from the text, you can use like below,

```<code>var email = "john.doe@email.com";
var name   = email.substring(0, email.lastIndexOf("@"));
console.log( name );   // john.doe
</code>```

Hopefully help

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get a user's name from their email and we are all on the same business domain. I saw a post here detailing how to do it if you want to pull from the contacts list. The problem is when I try it myself, it knows that there is contact for me, but it returns all of the values as null. If I use another contact email, then it pulls the info just fine.

The link says that there should be another way to do it but you need admin privileges. I can get that, but all of the links to the usermanager documentation are broken. Also, searching usermanager doesn't come up with anything on Google's developer site.

var email = Session.getActiveUser().getEmail();
Browser.msgBox(email)

var self = ContactsApp.getContact(email);
var name = self.getFullName();

Body:
If parsing from the text, you can use like below,

var email = "john.doe@email.com";
var name   = email.substring(0, email.lastIndexOf("@"));
console.log( name );   // john.doe

Hopefully help


问:
Uncaught TypeError: emit is not a function in vue3
when I write this code in vue 3 setup code block to get the input value follow this answer, this is part of the code:

```<code>import { defineComponent } from "vue";
import { defineProps, defineEmits } from 'vue'

export default defineComponent({
  setup() {
    const props = defineProps({
      modelValue: String
    })
    const emit = defineEmits(['update:modelValue'])
    function updateValue(value: any) {
      emit('update:modelValue', value)
    }
}
</code>```

the app show error when running:

```<code>option.js:17388 Uncaught TypeError: emit is not a function
    at Proxy.updateValue (option.js:17388:13)
    at onInput._cache.<computed>._cache.<computed> (option.js:17428:78)
    at callWithErrorHandling (option.js:7359:22)
    at callWithAsyncErrorHandling (option.js:7368:21)
    at HTMLInputElement.invoker (option.js:15384:90)
</code>```

I have defined the emit, why still tell me emit is not a function? This is my full code of the vue3 component:

```<code><template>
  <div id="app">
    <div id="wrap">
      <label>
        {{ username }}
      </label>
      <ul class="nav nav-tabs">
        <li>
          <input
          :value="props"
          placeholder="username"
          v-on:input="updateValue($event.target.value)"/>
          <input v-model="password" placeholder="password" />
          <button @click="login">Login</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { defineProps, defineEmits } from 'vue'

export default defineComponent({
  setup() {
    const props = defineProps({
      modelValue: String
    })
    const emit = defineEmits(['update:modelValue'])
    function updateValue(value: any) {
      emit('update:modelValue', value)
    }

    const login = () => {
      debugger
      alert(props.modelValue);
    };
    debugger

    return {
      login,
      updateValue,
      props
    };

  },
  components: {},
});
</script>

<style lang="scss" scoped>
</style>
</code>```

I want to get the user input username from the template input.Seems did not work this way. what should I do to fix this problem? I have tried to upgrade the @vue/compiler-sfc to 3.2.31, still did not fix this problem.

答:
As you saied This expression is not callable error.try this:

```<code>import { defineComponent } from "vue";

export default defineComponent({
   props:{
   modelValue: String
  },
  setup(props,ctx) {

    function updateValue(value: any) {
      ctx.emit('update:modelValue', value)
    }
}
</code>```

Body:
when I write this code in vue 3 setup code block to get the input value follow this answer, this is part of the code:

import { defineComponent } from "vue";
import { defineProps, defineEmits } from 'vue'

export default defineComponent({
  setup() {
    const props = defineProps({
      modelValue: String
    })
    const emit = defineEmits(['update:modelValue'])
    function updateValue(value: any) {
      emit('update:modelValue', value)
    }
}

the app show error when running:

option.js:17388 Uncaught TypeError: emit is not a function
    at Proxy.updateValue (option.js:17388:13)
    at onInput._cache.<computed>._cache.<computed> (option.js:17428:78)
    at callWithErrorHandling (option.js:7359:22)
    at callWithAsyncErrorHandling (option.js:7368:21)
    at HTMLInputElement.invoker (option.js:15384:90)

I have defined the emit, why still tell me emit is not a function? This is my full code of the vue3 component:

<template>

        {{ username }}

          <input
          :value="props"
          placeholder="username"
          v-on:input="updateValue($event.target.value)"/>
          <input v-model="password" placeholder="password" />
          <button @click="login">Login</button>

</template>

I want to get the user input username from the template input.Seems did not work this way. what should I do to fix this problem? I have tried to upgrade the @vue/compiler-sfc to 3.2.31, still did not fix this problem.

Body:
As you saied This expression is not callable error.try this:

import { defineComponent } from "vue";

export default defineComponent({
   props:{
   modelValue: String
  },
  setup(props,ctx) {

    function updateValue(value: any) {
      ctx.emit('update:modelValue', value)
    }
}


问:
Putting two functions in the same "onclick"
I'm trying to display a group of users in a table, and I'm using a library called "ReactTable", and I have an "approve" button, when the user clicks on the "approve" button two things should happen:

The first will be a dispatch of the approveUser function

The second thing, a message will appear that "acceptance has been completed".

The problem is that I want to put two functions in the same button and the same "onClick", and when I did that the site was no longer working,

How can I solve the problem?

```<code>function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}

const useStyles = makeStyles({
  button1: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#43a047",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#43a047",
    },
  },
  button2: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#e53935",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#e53935",
    },
  },
});

function ContactsList(props) {
  const classes = useStyles();
  const dispatch = useDispatch();
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true);
  };

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }

    setOpen(false);
  };

  useEffect(() => {
    dispatch(getUsersRequests());
  }, [dispatch]);

  const usersRequestsState = useSelector(
    (state) => state.usersRequestsApp["usersRequests"]
  );

  console.log(
    "requests inside Contacts List: ",
    usersRequestsState["usersRequests"]
  );

  const columns = useMemo(
    () => [
      {
        Header: "",
        // this is function or property
        accessor: "avatar",
        Cell: ({ row }) => {
          return (
            <Avatar
              className="mx-8"
              alt={row.original.name}
              src={row.original.avatar}
              style={{ height: "7rem", width: "7rem" }}
            />
          );
        },
        className: "justify-center",
        width: 64,
        sortable: false,
      },
      {
        Header: "First Name",
        accessor: "firstName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Last Name",
        accessor: "lastName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Email",
        accessor: "email",
        sortable: true,
      },
      {
        Header: "Phone Number",
        accessor: "phoneNumber",
        sortable: true,
      },
      {
        Header: "actions",
        accessor: "",
        sortable: true,
        id: "action",
        // width: 100,
        Cell: ({ row }) => (
          <div className="flex items-center">
            <ButtonGroup
              style={{
                maxWidth: "206px",
                maxHeight: "40px",
                minWidth: "206px",
                minHeight: "40px",
              }}
              aria-label="outlined primary button group"
            >
              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick;
                  dispatch(approveUser(row.original.id));
                }}
                className={classes.button1}
              >
                approve
              </Button>

              <Snackbar
                open={open}
                autoHideDuration={6000}
                onClose={handleClose}
              >
                <Alert onClose={handleClose} severity="success">
                  acceptance has been completed!
                </Alert>
              </Snackbar>

              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  dispatch(rejectUser(row.original.id));
                }}
                className={classes.button2}
              >
                reject
              </Button>
            </ButtonGroup>
          </div>
        ),
      },
    ],
    []
  );

  const dataResponse = useMemo(() => usersRequestsState["data"]);

  console.log("dataResponse: ", dataResponse);

  return (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1, transition: { delay: 0.2 } }}
    >
      <ContactsTable columns={columns} data={dataResponse} />
    </motion.div>
  );
}

export default ContactsList;
</code>```

答:
When you call the function you need to use ()

```<code>   onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick();
                  dispatch(approveUser(row.original.id));
                }}
</code>```

Body:
I'm trying to display a group of users in a table, and I'm using a library called "ReactTable", and I have an "approve" button, when the user clicks on the "approve" button two things should happen:

The first will be a dispatch of the approveUser function

The second thing, a message will appear that "acceptance has been completed".

The problem is that I want to put two functions in the same button and the same "onClick", and when I did that the site was no longer working,

How can I solve the problem?

function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}

const useStyles = makeStyles({
  button1: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#43a047",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#43a047",
    },
  },
  button2: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#e53935",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#e53935",
    },
  },
});

function ContactsList(props) {
  const classes = useStyles();
  const dispatch = useDispatch();
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true);
  };

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }

    setOpen(false);
  };

  useEffect(() => {
    dispatch(getUsersRequests());
  }, [dispatch]);

  const usersRequestsState = useSelector(
    (state) => state.usersRequestsApp["usersRequests"]
  );

  console.log(
    "requests inside Contacts List: ",
    usersRequestsState["usersRequests"]
  );

  const columns = useMemo(
    () => [
      {
        Header: "",
        // this is function or property
        accessor: "avatar",
        Cell: ({ row }) => {
          return (
            <Avatar
              className="mx-8"
              alt={row.original.name}
              src={row.original.avatar}
              style={{ height: "7rem", width: "7rem" }}
            />
          );
        },
        className: "justify-center",
        width: 64,
        sortable: false,
      },
      {
        Header: "First Name",
        accessor: "firstName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Last Name",
        accessor: "lastName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Email",
        accessor: "email",
        sortable: true,
      },
      {
        Header: "Phone Number",
        accessor: "phoneNumber",
        sortable: true,
      },
      {
        Header: "actions",
        accessor: "",
        sortable: true,
        id: "action",
        // width: 100,
        Cell: ({ row }) => (

            <ButtonGroup
              style={{
                maxWidth: "206px",
                maxHeight: "40px",
                minWidth: "206px",
                minHeight: "40px",
              }}
              aria-label="outlined primary button group"
            >
              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick;
                  dispatch(approveUser(row.original.id));
                }}
                className={classes.button1}
              >
                approve
              </Button>

              <Snackbar
                open={open}
                autoHideDuration={6000}
                onClose={handleClose}
              >
                <Alert onClose={handleClose} severity="success">
                  acceptance has been completed!
                </Alert>
              </Snackbar>

              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  dispatch(rejectUser(row.original.id));
                }}
                className={classes.button2}
              >
                reject
              </Button>
            </ButtonGroup>

        ),
      },
    ],
    []
  );

  const dataResponse = useMemo(() => usersRequestsState["data"]);

  console.log("dataResponse: ", dataResponse);

  return (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1, transition: { delay: 0.2 } }}
    >
      <ContactsTable columns={columns} data={dataResponse} />
    </motion.div>
  );
}

export default ContactsList;

Body:
When you call the function you need to use ()

   onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick();
                  dispatch(approveUser(row.original.id));
                }}


问:
assigning values of array into variables in ruby
I am trying to assign the each value of an array into different variables. But I am getting error as "Expecting end."

```<code>strs = ["flower","flow","flight"]
strs.each_with_index do |x, i|
"b#{i}" = x
end
</code>```

what is going wrong here ?

答:
What you're doing is like saying

```<code>"howdy" = 1
</code>```

You can't say that. That expression attempts to assign into a string literal. You can't do that. A string literal is not an lvalue (a thing that can go on the left side of an equal sign).

If you are trying to say "make a variable called howdy and assign this value to it", you can't do that because local variables cannot be created on the fly. See How to dynamically create a local variable?.

However, the real core of your issue is that you should not even want to do what you're doing. You already have an array, a wonderful thing that allows you to reference each entry by number. "flower" in your code is already strs[0], and so on. The whole point of the array is that it lets you do that. There is thus no need for individual variables with number names; the array is the variable with number names.

Body:
I am trying to assign the each value of an array into different variables. But I am getting error as "Expecting end."

strs = ["flower","flow","flight"]
strs.each_with_index do |x, i|
"b#{i}" = x
end

what is going wrong here ?

Body:
What you're doing is like saying

"howdy" = 1

You can't say that. That expression attempts to assign into a string literal. You can't do that. A string literal is not an lvalue (a thing that can go on the left side of an equal sign).

If you are trying to say "make a variable called howdy and assign this value to it", you can't do that because local variables cannot be created on the fly. See How to dynamically create a local variable?.

However, the real core of your issue is that you should not even want to do what you're doing. You already have an array, a wonderful thing that allows you to reference each entry by number. "flower" in your code is already strs[0], and so on. The whole point of the array is that it lets you do that. There is thus no need for individual variables with number names; the array is the variable with number names.


问:
BeautifulSoup append() causes subsequent find() to fail
Sometimes after appending a new element to a document, find() will fail. Specifically, if an append is made to the element being appended. The error happens if the 2nd element is appended to the first before the first is appended to the document. Here is an example of failure:

```<code>from bs4 import BeautifulSoup, NavigableString

import traceback
template = """
<html>
  <body>
    <table>
    </table>
    <p class="overview">
      Test
    </p>
  </body>
</html>
"""
doc = BeautifulSoup(template, 'html.parser')

for row_count in range(2):
  row = doc.new_tag('tr', id=f'row_{row_count}')
  doc.find('table').append(row)

print(doc.find(id='row_0'), '\n')
cell = doc.new_tag('td',class_='item')
x = NavigableString('hi')
cell.contents.append(x)
doc.find(id='row_0').append(cell)
print(doc.find(id='row_1'), '\n')
print(doc.prettify())
</code>```

My output for that is:

```<code><tr id="row_0"></tr>

None

<html>
 <body>
  <table>
   <tr id="row_0">
    <td class_="item">
     hi
    </td>
   </tr>
   <tr id="row_1">
   </tr>
  </table>
  <p class="overview">
   Test
  </p>
 </body>
</html>
</code>```

It appears the solution is to ensure that appends are only made to elements that have already been appended to the document.

I am using bs4 version '4.8.2'

答:
The solution is to call the append() function of the element, not of the contents of the element.</p>
```<code>cell.append(x)
</code>```

Body:
Sometimes after appending a new element to a document, find() will fail. Specifically, if an append is made to the element being appended. The error happens if the 2nd element is appended to the first before the first is appended to the document. Here is an example of failure:

from bs4 import BeautifulSoup, NavigableString

import traceback
template = """

      Test

"""
doc = BeautifulSoup(template, 'html.parser')

for row_count in range(2):
  row = doc.new_tag('tr', id=f'row_{row_count}')
  doc.find('table').append(row)

print(doc.find(id='row_0'), '\n')
cell = doc.new_tag('td',class_='item')
x = NavigableString('hi')
cell.contents.append(x)
doc.find(id='row_0').append(cell)
print(doc.find(id='row_1'), '\n')
print(doc.prettify())

My output for that is:

None

     hi

   Test

It appears the solution is to ensure that appends are only made to elements that have already been appended to the document.

I am using bs4 version '4.8.2'

Body:
The solution is to call the append() function of the element, not of the contents of the element.

cell.append(x)


问:
What mistake am I making here?
I am running below queries on hive, 1 is running fine but other one fails, could you please me with why 2nd one is failing.
Basically i am doing a word query in hive.

Query #1 (doesn't work)

select
    word, count(1)
from
    (select
         explode(split(s,' ')) AS word
     from
         lines)
group by
    word
```
<p>Query #2: (works fine)</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    word, count(1)
FROM
    (SELECT
         explode(split(s, ' ')) AS word
     FROM
         lines) q
GROUP BY
    word
</code>```

答:
The first query is missing a sub-query name. The second one has it (as q).

```<code>SELECT ... FROM (subquery) name ...
</code>```

See the language manual for more information.

Title: What mistake am I making here?

Body:
I am running below queries on hive, 1 is running fine but other one fails, could you please me with why 2nd one is failing.
Basically i am doing a word query in hive.

Query #1 (doesn't work)

select
    word, count(1)
from
    (select
         explode(split(s,' ')) AS word
     from
         lines)
group by
    word

Query #2: (works fine)

SELECT
    word, count(1)
FROM
    (SELECT
         explode(split(s, ' ')) AS word
     FROM
         lines) q
GROUP BY
    word

Body:
The first query is missing a sub-query name. The second one has it (as q).

SELECT ... FROM (subquery) name ...

See the language manual for more information.


问:
Firebase: Error (auth/admin-restricted-operation)
I am doing firebase authentication using reactjs but I am unable to do it. its throwing an error, error message->  Firebase: Error (auth/admin-restricted-operation).
how am I restricted ? how come its an admin-restricted-operation...
I have gone through many solution but it didn't really help....
I even created a new project on firebase but the problem still persist...

file: firebaseConfig.js

```<code>import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth'

const firebaseConfig = {
    apiKey: "xxxxx",
    authDomain: "xxxxx",
    projectId: "xxxxx",
    storageBucket: "xxxxx",
    messagingSenderId: "xxxxx",
    appId: "xxxxx",
    measurementId: "xxxxx"
};

const app = initializeApp(firebaseConfig)
export default app
export const auth = getAuth(app)
</code>```

file: signUp.js

```<code>import React, {useState} from 'react'
import { createUserWithEmailAndPassword } from 'firebase/auth'
import { auth } from '../../firebaseConfig'

//css module import
import signupCard from './SignUp.module.css'

export const SignUp = props =>{

    //State....
    const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: '',
        emailRef: '',
        passwordRef: '',
        passwordConfirmationRef: ''
    })

    const signupHandler = async (event) =>{
        event.preventDefault()

        if(credentials.emailRef === '' && credentials.passwordRef === ''){
            console.log('empty fields!!')
        }else{
            try{
                const user = await createUserWithEmailAndPassword(auth, credentials.emailRef, credentials.passwordRef)
                console.log(user)
            }catch(error){
                console.log(error)
            }
        }

    }

    const backHandler = () => {
        props.backButtonDetails(true)
    }

    return(
        <React.Fragment>
            <div className = {signupCard.signupContainer}>

                <form onSubmit={signupHandler}>
                    <div className = {signupCard.signupFormFirst} >
                    <button onClick={backHandler} > back </button>
                        <span className = {signupCard.branding1}>SnowChild</span>
                        <hr className = {signupCard.hrTag}/>
                        <input type = 'text' className = {signupCard.fname} placeholder = 'firstname' id = 'Fname' onChange = {(event) => setCredentials({fnameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.sname} placeholder = 'surname' id = 'Sname' onChange = {(event) => setCredentials({snameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.phone} placeholder = 'phone' id = 'contact' onChange = {(event) => setCredentials({phoneRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.city} placeholder = 'city' id = 'Where' onChange = {(event) => setCredentials({cityRef: event.target.value})} />
                        <span className = {signupCard.dateString} >Date of birth</span>
                        <input type = 'date' className = {signupCard.dob} id = 'birthdate' onChange = {(event) => setCredentials({dobRef: event.target.value})}/>
                        <hr className = {signupCard.hrTag}  style = {{margin: '20px 0 10px 0'}}/>
                    </div>
                    <div className = {signupCard.signupFormSecond}>
                        <hr className = {signupCard.hrTag} />
                        <input type = 'email' placeholder = 'Email' className = {signupCard.UNF} id = 'email' onChange = {(event) => setCredentials({emailRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'Password' className = {signupCard.PWD} id = 'password' onChange = {(event) => setCredentials({passwordRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'confirmPassword' className = {signupCard.PWD} id = 'passwordConfirmation' onChange = {(event) => setCredentials({passwordConfirmationRef: event.target.value})}/>
                        <hr className = {signupCard.hrTag} style = {{marginTop: '10px'}}/>
                        <button type = 'submit' className={signupCard.signupButton}> Sign up </button>
                    </div>
                </form>
            </div>
            </React.Fragment>
    )
}
</code>```

what am I doing wrong ??

error

答:
It could be related to the 3 things below in my opinion.

It was suggested that Firebase rules are not setup correctly in this similar post Admin operation restricted answer by

The biggest suggestion from all the other threads and research I've done for you, and probably the wrong answer is found here signing anonymously with firebase

Another answer has to do with the Firebase versioning and code used found here in Dandotwaves answer

This is the code from that post by Dandotwave:

```<code>import { firebase } from "@firebase/app";

import { initializeApp } from "firebase/app";

import { getAuth, onAuthStateChanged } from "firebase/auth";

const firebaseConfig =  {
  apiKey: "xxx",
  authDomain: "xxx",
  projectId: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx",
  appId: "xxx",
};

const app = initializeApp(firebaseConfig);
const auth = getAuth();
</code>```

You are using

```<code>const app = initializeApp(firebaseConfig)
export default app
export const auth = getAuth(app)
</code>```

Body:
I am doing firebase authentication using reactjs but I am unable to do it. its throwing an error, error message->  Firebase: Error (auth/admin-restricted-operation).
how am I restricted ? how come its an admin-restricted-operation...
I have gone through many solution but it didn't really help....
I even created a new project on firebase but the problem still persist...

file: firebaseConfig.js

import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth'

const firebaseConfig = {
    apiKey: "xxxxx",
    authDomain: "xxxxx",
    projectId: "xxxxx",
    storageBucket: "xxxxx",
    messagingSenderId: "xxxxx",
    appId: "xxxxx",
    measurementId: "xxxxx"
};

const app = initializeApp(firebaseConfig)
export default app
export const auth = getAuth(app)

file: signUp.js

import React, {useState} from 'react'
import { createUserWithEmailAndPassword } from 'firebase/auth'
import { auth } from '../../firebaseConfig'

//css module import
import signupCard from './SignUp.module.css'

export const SignUp = props =>{

    //State....
    const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: '',
        emailRef: '',
        passwordRef: '',
        passwordConfirmationRef: ''
    })

    const signupHandler = async (event) =>{
        event.preventDefault()

        if(credentials.emailRef === '' && credentials.passwordRef === ''){
            console.log('empty fields!!')
        }else{
            try{
                const user = await createUserWithEmailAndPassword(auth, credentials.emailRef, credentials.passwordRef)
                console.log(user)
            }catch(error){
                console.log(error)
            }
        }

    }

    const backHandler = () => {
        props.backButtonDetails(true)
    }

    return(
        <React.Fragment>

                <form onSubmit={signupHandler}>

                    <button onClick={backHandler} > back </button>
                        SnowChild

                        <input type = 'text' className = {signupCard.fname} placeholder = 'firstname' id = 'Fname' onChange = {(event) => setCredentials({fnameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.sname} placeholder = 'surname' id = 'Sname' onChange = {(event) => setCredentials({snameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.phone} placeholder = 'phone' id = 'contact' onChange = {(event) => setCredentials({phoneRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.city} placeholder = 'city' id = 'Where' onChange = {(event) => setCredentials({cityRef: event.target.value})} />
                        Date of birth
                        <input type = 'date' className = {signupCard.dob} id = 'birthdate' onChange = {(event) => setCredentials({dobRef: event.target.value})}/>

                        <input type = 'email' placeholder = 'Email' className = {signupCard.UNF} id = 'email' onChange = {(event) => setCredentials({emailRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'Password' className = {signupCard.PWD} id = 'password' onChange = {(event) => setCredentials({passwordRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'confirmPassword' className = {signupCard.PWD} id = 'passwordConfirmation' onChange = {(event) => setCredentials({passwordConfirmationRef: event.target.value})}/>

                        <button type = 'submit' className={signupCard.signupButton}> Sign up </button>

                </form>

            </React.Fragment>
    )
}

what am I doing wrong ??

error

Body:
It could be related to the 3 things below in my opinion.

It was suggested that Firebase rules are not setup correctly in this similar post Admin operation restricted answer by

The biggest suggestion from all the other threads and research I've done for you, and probably the wrong answer is found here signing anonymously with firebase

Another answer has to do with the Firebase versioning and code used found here in Dandotwaves answer

This is the code from that post by Dandotwave:

import { firebase } from "@firebase/app";

import { initializeApp } from "firebase/app";

import { getAuth, onAuthStateChanged } from "firebase/auth";

const firebaseConfig =  {
  apiKey: "xxx",
  authDomain: "xxx",
  projectId: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx",
  appId: "xxx",
};

const app = initializeApp(firebaseConfig);
const auth = getAuth();

You are using

const app = initializeApp(firebaseConfig)
export default app
export const auth = getAuth(app)


问:
How to write rest api for the node js tedious?
I am unable to get the sql data in the express API? It is continuously loading and getting a blank screen,but getting sql data response in the console fine.

My index.js code :

```<code>var Connection = require("tedious").Connection;
var Request = require("tedious").Request;
var Types = require("tedious").Types;
const express = require("express");
const app = express();
const port = 3001;
var cors = require("cors");

app.get("/", function(req, res) {
    var config = {
        server:
            "***",
        authentication: {
            type: "default",
            options: {
                userName: "****",
                password: "****",
            },
        },
        options: {
            encrypt: true,
            database: "****",
        },
    };

    const connection = new Connection(config);

    connection.on("connect", (err, result) => {
        if (err) {
            console.log("Connection Failed");
            throw err;
        }
        executeStatement();
    });

    connection.connect();

    function executeStatement() {
        const request = new Request(
            "SELECT * FROM Platform",
            (err, rowCount, rows) => {
                if (err) {
                    console.log(err);
                }
            }
        );

        request.on("row", (columns) => {
            columns.forEach((column, rowCount, response) => {
                if (column.value === null) {
                    console.log("NULL");
                } else {
                    console.log(column.metadata.colName + " = " + column.value);
                }

                return res.send(response);
            });
        });

        connection.execSql(request);
    }
});

app.use(cors());

app.listen(port, function(err) {
    if (err) console.log("Error in server setup");
    console.log("Server listening on Port", port);
});
</code>```

Getting error as “ERR_HTTP_HEADERS_SENT”

events.js:352

throw er; // Unhandled 'error' event
^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\express\lib\response.js:776:10)
at ServerResponse.json (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\express\lib\response.js:264:10)
at ServerResponse.send (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\express\lib\response.js:158:21)
at C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\index.js:94:20
at Array.forEach (<anonymous>)
at Request.<anonymous> (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\index.js:88:15)
at Request.emit (events.js:375:28)
at Request.emit (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\tedious\lib\request.js:150:18)
at Parser.<anonymous> (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\tedious\lib\connection.js:1322:21)
Emitted 'error' event on Readable instance at:
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
    code: 'ERR_HTTP_HEADERS_SENT'
}
```

Please do help in resolving this error.

答:
I am unable to verify this. The reason you're getting that error is the you are trying to send the requestjs request more than once. You have it within you Array.forEach() loop. It appears all you will need to do is move, return res.send(response);, outside the loop.

Below the res.send() is moved after the call to the database. I assume that connection.execSql(request); returns a Promise which will need to be resolved before you send the Expressjs result. Hopefully this will provide the general approach needed.

var Connection = require("tedious").Connection;
var Request = require("tedious").Request;
var Types = require("tedious").Types;
const express = require("express");
const app = express();
const port = 3001;
var cors = require("cors");

app.get("/", function(req, res) {
    var config = {
        server:
            "***",
        authentication: {
            type: "default",
            options: {
                userName: "****",
                password: "****",
            },
        },
        options: {
            encrypt: true,
            database: "****",
        },
    };

    const connection = new Connection(config);

    connection.on("connect", (err, result) => {
        if (err) {
            console.log("Connection Failed");
            throw err;
        }
        executeStatement();
    });

    connection.connect();

    function executeStatement() {
        const request = new Request(
            "SELECT * FROM Platform",
            (err, rowCount, rows) => {
                if (err) {
                    console.log(err);
                }
            }
        );

        let outputData = ''; // Added to collect the data in the `Array.forEach()`

        request.on("row", (columns) => {
            columns.forEach((column, rowCount, response) => {
                if (column.value === null) {
                    console.log("NULL");
                } else {
                    console.log(column.metadata.colName + " = " + column.value);
                }

                outputData += response;
            });
        });

        connection.execSql(request); // This probably returns a promise which will need to resolved before you return the data.

        return res.send(outputData);
    }
});

app.use(cors());

app.listen(port, function(err) {
    if (err) console.log("Error in server setup");
    console.log("Server listening on Port", port);
});
```

Body:
I am unable to get the sql data in the express API? It is continuously loading and getting a blank screen,but getting sql data response in the console fine.

My index.js code :

var Connection = require("tedious").Connection;
var Request = require("tedious").Request;
var Types = require("tedious").Types;
const express = require("express");
const app = express();
const port = 3001;
var cors = require("cors");

app.get("/", function(req, res) {
    var config = {
        server:
            "***",
        authentication: {
            type: "default",
            options: {
                userName: "****",
                password: "****",
            },
        },
        options: {
            encrypt: true,
            database: "****",
        },
    };

    const connection = new Connection(config);

    connection.on("connect", (err, result) => {
        if (err) {
            console.log("Connection Failed");
            throw err;
        }
        executeStatement();
    });

    connection.connect();

    function executeStatement() {
        const request = new Request(
            "SELECT * FROM Platform",
            (err, rowCount, rows) => {
                if (err) {
                    console.log(err);
                }
            }
        );

        request.on("row", (columns) => {
            columns.forEach((column, rowCount, response) => {
                if (column.value === null) {
                    console.log("NULL");
                } else {
                    console.log(column.metadata.colName + " = " + column.value);
                }

                return res.send(response);
            });
        });

        connection.execSql(request);
    }
});

app.use(cors());

app.listen(port, function(err) {
    if (err) console.log("Error in server setup");
    console.log("Server listening on Port", port);
});

Getting error as “ERR_HTTP_HEADERS_SENT”

events.js:352

throw er; // Unhandled 'error' event
^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\express\lib\response.js:776:10)
at ServerResponse.json (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\express\lib\response.js:264:10)
at ServerResponse.send (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\express\lib\response.js:158:21)
at C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\index.js:94:20
at Array.forEach (<anonymous>)
at Request.<anonymous> (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\index.js:88:15)
at Request.emit (events.js:375:28)
at Request.emit (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\tedious\lib\request.js:150:18)
at Parser.<anonymous> (C:\Users\fashila.barveen\Desktop\CMS_EXT_TOOL\server\cms_tool_backend\node_modules\tedious\lib\connection.js:1322:21)
Emitted 'error' event on Readable instance at:
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
    code: 'ERR_HTTP_HEADERS_SENT'
}

Please do help in resolving this error.


问:
How does the probability argument work in the sample() function in R
I am trying to understand how the weighing works (probability argument) in the sample() function in R.

```<code># seed
set.seed(123)

# some numbers
x = c(1:100)

# some probabilties
p = seq(from = 0, to = 1, length.out = 100)

# sample size
n = 10000

# sample 10000 times from x with probability p
x1 <- sample(x, size = n, replace = TRUE, prob = p)

# plot
hist(x1)
plot(density(x1))
</code>```

Now is this approximately what the probability argument does?

```<code># adding weights manually
weight = rep(x, n * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE)

# plot
hist(x2)
plot(density(x2))
</code>```

The plots look very similar so it seems that might be the case.

EDIT

I think I made a mistake when I added the weights manually, i.e. I used n*p but I think I should have used x*p. Then the results do change a bit:

```<code># adding weights manually
weight = rep(x, x * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE)
</code>```

答:
The results you are getting are expected because by defining p as a sequence of evenly spaced numbers, the greater the value of x the greater its probability of being sampled. This is a weighted sampling procedure, like you say.

See the following two cases.

In the first case the probability of sampling element 2 is 4 times greater, and the results show approximately this.

set.seed(2022)

# sample size
n <- 10000

v <- 1:2
x <- sample(v, n, replace = TRUE, prob = c(1, 4)/5)
proportions(table(x))
#> x
#>      1      2
#> 0.1976 0.8024
barplot(table(x))
```
<p><img src="https://i.imgur.com/l5qRSJq.png" alt="" /></p>
<p>In the case below, the probability of sampling a <code>10</code> is over 600 times greater than the probability of sampling any other number in the vector <code>1:100</code>.</p>
<pre class="lang-r prettyprint-override"><code>s <- 1:100
p <- rep(1, 100)
p[10] <- 400
p <- p/sum(p)
y <- sample(s, n, replace = TRUE, prob = p)
proportions(table(y))
hist(y)
</code>```

Created on 2022-02-13 by the reprex package (v2.0.1)

Body:
I am trying to understand how the weighing works (probability argument) in the sample() function in R.

# seed
set.seed(123)

# some numbers
x = c(1:100)

# some probabilties
p = seq(from = 0, to = 1, length.out = 100)

# sample size
n = 10000

# sample 10000 times from x with probability p
x1 <- sample(x, size = n, replace = TRUE, prob = p)

# plot
hist(x1)
plot(density(x1))

Now is this approximately what the probability argument does?

# adding weights manually
weight = rep(x, n * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE)

# plot
hist(x2)
plot(density(x2))

The plots look very similar so it seems that might be the case.

EDIT

I think I made a mistake when I added the weights manually, i.e. I used n*p but I think I should have used x*p. Then the results do change a bit:

# adding weights manually
weight = rep(x, x * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE)

Body:
The results you are getting are expected because by defining p as a sequence of evenly spaced numbers, the greater the value of x the greater its probability of being sampled. This is a weighted sampling procedure, like you say.

See the following two cases.

In the first case the probability of sampling element 2 is 4 times greater, and the results show approximately this.

set.seed(2022)

# sample size
n <- 10000

v <- 1:2
x <- sample(v, n, replace = TRUE, prob = c(1, 4)/5)
proportions(table(x))
#> x
#>      1      2
#> 0.1976 0.8024
barplot(table(x))

In the case below, the probability of sampling a 10 is over 600 times greater than the probability of sampling any other number in the vector 1:100.

s <- 1:100
p <- rep(1, 100)
p[10] <- 400
p <- p/sum(p)
y <- sample(s, n, replace = TRUE, prob = p)
proportions(table(y))
hist(y)

Created on 2022-02-13 by the reprex package (v2.0.1)


问:
The following StateError was thrown by an image listener: Bad state: Future already completed
Why I will receive this exception?

```<code>════════ Exception caught by image resource service ════════════════════════════
The following StateError was thrown by an image listener:
Bad state: Future already completed

When the exception was thrown, this was the stack
#1      _xxxState.setup.<anonymous closure>
xxx/ui/xxx.dart:209
#2      ImageStreamCompleter.setImage
package:flutter/…/painting/image_stream.dart:633
#3      MultiImageStreamCompleter._emitFrame
package:cached_network_image/…/image_provider/multi_image_stream_completer.dart:156
#4      MultiImageStreamCompleter._decodeNextFrameAndSchedule
package:cached_network_image/…/image_provider/multi_image_stream_completer.dart:141
<asynchronous suspension>
(elided one frame from dart:async)
</code>```

Code

```<code>initState(){
   _refresh();
}

_refresh() async {
   ...
   await setUp();
}

 setup() async {

    var data = await _bloc.selectFloorPlan(floorPlanId);

    Image image = Image(image: CachedNetworkImageProvider(data));

    Completer<ui.Image> completer = Completer<ui.Image>();
    image.image
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo image, bool _) {
      completer.complete(image.image);

      if (completer.isCompleted) {
        if (mounted) {
          floorPlanAnnotationUtil.updateValues(
            containerHeight: containerFixedHeight,
            containerWidth: MediaQuery.of(context).size.width -
                20, // minus the container padding 10 * 2
            imageHeight:
                DevicePixelUtil.toDevicePixel(context, image.image.height),
            imageWidth:
                DevicePixelUtil.toDevicePixel(context, image.image.width),
          );
        }

        // setState(() {});
      }
    }));
  }
</code>```

The error pointed to this line

```<code> completer.complete(image.image);
</code>```

答: It looks like you are using https://pub.dev/packages/cached_network_image, which internally uses https://pub.dev/packages/flutter_cache_manager. The default Cache Manager can add multiple (relevant) events to the stream. For example if the image in the cache is stale it first emits the cached image and afterwards it emits the newly downloaded image again. You are probably seeing the effect here since your Completer can only be completed once.

Body:
Why I will receive this exception?

════════ Exception caught by image resource service ════════════════════════════
The following StateError was thrown by an image listener:
Bad state: Future already completed

When the exception was thrown, this was the stack
#1      _xxxState.setup.<anonymous closure>
xxx/ui/xxx.dart:209
#2      ImageStreamCompleter.setImage
package:flutter/…/painting/image_stream.dart:633
#3      MultiImageStreamCompleter._emitFrame
package:cached_network_image/…/image_provider/multi_image_stream_completer.dart:156
#4      MultiImageStreamCompleter._decodeNextFrameAndSchedule
package:cached_network_image/…/image_provider/multi_image_stream_completer.dart:141
<asynchronous suspension>
(elided one frame from dart:async)

Code

initState(){
   _refresh();
}

_refresh() async {
   ...
   await setUp();
}

 setup() async {

    var data = await _bloc.selectFloorPlan(floorPlanId);

    Image image = Image(image: CachedNetworkImageProvider(data));

    Completer<ui.Image> completer = Completer<ui.Image>();
    image.image
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo image, bool _) {
      completer.complete(image.image);

      if (completer.isCompleted) {
        if (mounted) {
          floorPlanAnnotationUtil.updateValues(
            containerHeight: containerFixedHeight,
            containerWidth: MediaQuery.of(context).size.width -
                20, // minus the container padding 10 * 2
            imageHeight:
                DevicePixelUtil.toDevicePixel(context, image.image.height),
            imageWidth:
                DevicePixelUtil.toDevicePixel(context, image.image.width),
          );
        }

        // setState(() {});
      }
    }));
  }

The error pointed to this line

 completer.complete(image.image);


问:
Menu item not showing titles in android
I am currently adding the sorting functionality to my food app. But my app didn't show the menu items instead it shows a blank white menu.Any ways to resolve this problem?

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">

        <item
            android:id="@+id/sortName"
            android:title="Name" />

        <item
            android:id="@+id/sortRating"
            android:title="Rating" />

        <item
            android:id="@+id/sortCostAsc"
            android:title="Cost (low to high)" />

        <item
            android:id="@+id/sortCostDesc"
            android:title="Cost (high to low)" />

    </group>
</menu>
</code>```

This is my menu layout.

```<code><resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.FoodSpot" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/primary_violet</item>
        <item name="colorPrimaryVariant">@color/secondary_violet</item>
        <item name="colorOnPrimary">@color/black</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="android:actionMenuTextColor">@color/black</item>
    </style>

    <style name="ThemeOverlay.AppCompat.navTheme">
        <!-- Color of text and icon when SELECTED -->
        <item name="colorPrimary">@color/secondary_violet</item>
        <!-- Background color when SELECTED -->
        <item name="colorControlHighlight">@color/secondary_violet</item>
    </style>
</resources>
</code>```

This is my themes.xml . Based on some suggestion I've changed my colorOnPrimary and actionMenuTextColor. But Still same problem.

```<code>override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.sort_menu,menu)
    }
</code>```

Here, I inflate the menu layout.

```<code>setHasOptionsMenu(true)
</code>```

And, also I added this inside my Oncreateview method of the fragment to enable the menu in the toolbar.

I've added the screenshot of my app here..

答:
try this way!!
add to style

```<code>    <item name="android:itemTextAppearance">@style/menuStyle</item>
</code>```

and add new style

```<code>    <style name="menuStyle" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
    <item name="android:textColor">@color/your_color</item>
</style>
</code>```

Title: Menu item not showing titles in android

Body:
I am currently adding the sorting functionality to my food app. But my app didn't show the menu items instead it shows a blank white menu.Any ways to resolve this problem?

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">

        <item
            android:id="@+id/sortName"
            android:title="Name" />

        <item
            android:id="@+id/sortRating"
            android:title="Rating" />

        <item
            android:id="@+id/sortCostAsc"
            android:title="Cost (low to high)" />

        <item
            android:id="@+id/sortCostDesc"
            android:title="Cost (high to low)" />

    </group>
</menu>

This is my menu layout.

<resources xmlns:tools="http://schemas.android.com/tools">

</resources>

This is my themes.xml . Based on some suggestion I've changed my colorOnPrimary and actionMenuTextColor. But Still same problem.

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.sort_menu,menu)
    }

Here, I inflate the menu layout.

setHasOptionsMenu(true)

And, also I added this inside my Oncreateview method of the fragment to enable the menu in the toolbar.

I've added the screenshot of my app here..

Body:
try this way!!
add to style

    <item name="android:itemTextAppearance">@style/menuStyle</item>

and add new style

    <style name="menuStyle" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
    <item name="android:textColor">@color/your_color</item>
</style>


问:
Use np.where on a Mixed data type column
I have a column with data type 'o'. It has numbers, as well String. For example:

Days

5

10

15

7

No Sales Data available

9

I am trying to make a separate column using np.where, where I have written the code as

```<code>np.where(df['Days']=='No Sales Data available','No Sales',np.where(df['Days']<=10, 'Less than 10 days Sales','More than 10 Days Sales'))
</code>```

Naturally, the code is giving problems due to mixed data types. Any idea how to get around such cases?

答:
You could rewrite your statement in this way which will preserve the data type of your 'Days' column.

```<code>df['new'] = np.where(pd.to_numeric(df['Days'],errors='coerce').isna(),'No Sale',
             np.where(pd.to_numeric(df['Days'],errors='coerce') <= 10,
               'Less than 10 days Sales','More than 10 Days Sales'))
print(df)
                      Days                      new
0                        5  Less than 10 days Sales
1                       10  Less than 10 days Sales
2                       15  More than 10 Days Sales
3                        7  Less than 10 days Sales
4  No Sales Data available                  No Sale
5                        9  Less than 10 days Sales
</code>```

If you don't mind changing the type of your column, you could first convert to numeric and following a similar logic:

```<code>df['Days'] = pd.to_numeric(df['Days'],errors='coerce')
df['new'] = np.where(df['Days'].isna(),'No Sale',np.where(df['Days']<=10,'Less than 10 days Sales','More than 10 Days Sales'))

print(df)

   Days                      new
0   5.0  Less than 10 days Sales
1  10.0  Less than 10 days Sales
2  15.0  More than 10 Days Sales
3   7.0  Less than 10 days Sales
4   NaN                  No Sale
5   9.0  Less than 10 days Sales
</code>```

Body:
I have a column with data type 'o'. It has numbers, as well String. For example:

Days

5

10

15

7

No Sales Data available

9

I am trying to make a separate column using np.where, where I have written the code as

np.where(df['Days']=='No Sales Data available','No Sales',np.where(df['Days']<=10, 'Less than 10 days Sales','More than 10 Days Sales'))

Naturally, the code is giving problems due to mixed data types. Any idea how to get around such cases?

Body:
You could rewrite your statement in this way which will preserve the data type of your 'Days' column.

df['new'] = np.where(pd.to_numeric(df['Days'],errors='coerce').isna(),'No Sale',
             np.where(pd.to_numeric(df['Days'],errors='coerce') <= 10,
               'Less than 10 days Sales','More than 10 Days Sales'))
print(df)
                      Days                      new
0                        5  Less than 10 days Sales
1                       10  Less than 10 days Sales
2                       15  More than 10 Days Sales
3                        7  Less than 10 days Sales
4  No Sales Data available                  No Sale
5                        9  Less than 10 days Sales

If you don't mind changing the type of your column, you could first convert to numeric and following a similar logic:

df['Days'] = pd.to_numeric(df['Days'],errors='coerce')
df['new'] = np.where(df['Days'].isna(),'No Sale',np.where(df['Days']<=10,'Less than 10 days Sales','More than 10 Days Sales'))

print(df)

   Days                      new
0   5.0  Less than 10 days Sales
1  10.0  Less than 10 days Sales
2  15.0  More than 10 Days Sales
3   7.0  Less than 10 days Sales
4   NaN                  No Sale
5   9.0  Less than 10 days Sales


问:
How to make bottomNavigationBar notch transparent
I want to make the notch margin spacing (space between FAB's sides and bottom bar) like android material design explain in Inset FAB, It looks like a zoom background text in this small visible round portion. How we can make notching space transparent to see the text behind it?
However, mine bottom bar is not showing like that

My implementation

```<code>Scaffold(
  floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
  floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.white,
    child: Image.asset("images/paw.png"),
    onPressed: () {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => Map()));
    },
  ),
  bottomNavigationBar: BottomAppBar(
    shape: CircularNotchedRectangle(),
    child: new Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.menu),
          color: Colors.transparent,
          onPressed: () {},
        ),
      ],
    ),
    color: Utiles.primary_bg_color,
  ),
  body: Container(...)
</code>```

答:
Do:

```<code> return Scaffold(
     extendBody: true,
    (...)
</code>```

after

```<code>  body: SafeArea(
         bottom: false,
    (...)
</code>```

after "no add backgroundColor"

```<code>  BottomNavigationBar(
      //backgroundColor:
</code>```

Body:
I want to make the notch margin spacing (space between FAB's sides and bottom bar) like android material design explain in Inset FAB, It looks like a zoom background text in this small visible round portion. How we can make notching space transparent to see the text behind it?
However, mine bottom bar is not showing like that

My implementation

Scaffold(
  floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
  floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.white,
    child: Image.asset("images/paw.png"),
    onPressed: () {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => Map()));
    },
  ),
  bottomNavigationBar: BottomAppBar(
    shape: CircularNotchedRectangle(),
    child: new Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.menu),
          color: Colors.transparent,
          onPressed: () {},
        ),
      ],
    ),
    color: Utiles.primary_bg_color,
  ),
  body: Container(...)

Body:
Do:

 return Scaffold(
     extendBody: true,
    (...)

after

  body: SafeArea(
         bottom: false,
    (...)

after "no add backgroundColor"

  BottomNavigationBar(
      //backgroundColor:


问:
Remove duplicates in an object array Javascript
I have an array of objects

```<code>list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}]
</code>```

And I'm looking for an efficient way (if possible O(log(n))) to remove duplicates and to end up with

```<code>list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}]
</code>```

I've tried _.uniq or even _.contains but couldn't find a satisfying solution.

Thanks!

Edit : The question has been identified as a duplicate of another one. I saw this question before posting but it didn't answer my question since it's an array of object (and not a 2-dim array, thanks Aaron), or at least the solutions on the other question weren't working in my case.

答:
With Underscore's _.uniq and the standard JSON.stringify it is a oneliner:

var list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}];

var deduped = _.uniq(list, JSON.stringify);

console.log(deduped);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://underscorejs.org/underscore-umd-min.js"></script></code>```

However, this presumes that the keys are always specified in the same order. By sophisticating the iteratee, we can make the solution work even if the order of the keys varies. This problem as well as the solution also apply to other answers that involve JSON.stringify.

var list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {y:2, x:1}];

// Ensure that objects are always stringified
// with the keys in alphabetical order.
function replacer(key, value) {
    if (!_.isObject(value)) return value;
    var sortedKeys = _.keys(value).sort();
    return _.pick(value, sortedKeys);
}

// Create a modified JSON.stringify that always
// uses the above replacer.
var stringify = _.partial(JSON.stringify, _, replacer, null);

var deduped = _.uniq(list, stringify);

console.log(deduped);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://underscorejs.org/underscore-umd-min.js"></script></code>```

For Lodash 4, use _.uniqBy instead of _.uniq.

Body:
I have an array of objects

list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}]

And I'm looking for an efficient way (if possible O(log(n))) to remove duplicates and to end up with

list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}]

I've tried _.uniq or even _.contains but couldn't find a satisfying solution.

Thanks!

Edit : The question has been identified as a duplicate of another one. I saw this question before posting but it didn't answer my question since it's an array of object (and not a 2-dim array, thanks Aaron), or at least the solutions on the other question weren't working in my case.

Body:
With Underscore's _.uniq and the standard JSON.stringify it is a oneliner:

var list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}];

var deduped = _.uniq(list, JSON.stringify);

console.log(deduped);

<script src="https://underscorejs.org/underscore-umd-min.js"></script>

However, this presumes that the keys are always specified in the same order. By sophisticating the iteratee, we can make the solution work even if the order of the keys varies. This problem as well as the solution also apply to other answers that involve JSON.stringify.

var list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {y:2, x:1}];

// Ensure that objects are always stringified
// with the keys in alphabetical order.
function replacer(key, value) {
    if (!_.isObject(value)) return value;
    var sortedKeys = _.keys(value).sort();
    return _.pick(value, sortedKeys);
}

// Create a modified JSON.stringify that always
// uses the above replacer.
var stringify = _.partial(JSON.stringify, _, replacer, null);

var deduped = _.uniq(list, stringify);

console.log(deduped);

<script src="https://underscorejs.org/underscore-umd-min.js"></script>

For Lodash 4, use _.uniqBy instead of _.uniq.


问:
Divide text in different groups using regex
I want to extract some data using regex. I'm currently using python and the data can be like this:

```<code>text [text1 & text2]
text [text1]
text [text2]
text
</code>```

There is a "text" value (can be one, or more words) and can be followed by [] or no. In case [] exists, the text inside can be two words separated by & or only one of them (at the moment exists only two possible words but I think is better to get the words by separator instead of matching the exact word)

So my goal is to get the data in two different groups:

Group1: text

Group2: [text1, text2] (if exists)

My regex is:

```<code>(^([^\[])+)(.+?(?=&|\]))?(.+?(?=\]))?
</code>```

I've tried this using findall which I think fits better with the result I want:

regex = "(^([^\[])+)(.+?(?=&|\]))?(.+?(?=\]))?"
result = re.findall(regex,text)
```
<p>But it returns:</p>
```[('text ', ' ', '[text1 ', '& text2')]
```
<p>And I want, something like:</p>
<pre class="lang-py prettyprint-override"><code>[('text'), ('text1', 'text2')]
</code>```

I've tried in this playground

How can I improve my regex pattern?

Thanks in advance.

答:
I'm not familiar with python, but I don't think it's possible to get more than one value from one group in a regular expression, so my guess is that you'd have to use something like this

```<code>(\w+)(?: \[(.*)\])?
</code>```

Which will give you one or two groups

```<code>[('text'), ('text1 & text2')]
[('text'), ('text1')]
[('text'), ('text2')]
[('text')]
</code>```

And then if the second group exists, use a second regular expression to get each individual value from it.

You can have a look here: https://regex101.com/r/DxF5p1/1

Body:
I want to extract some data using regex. I'm currently using python and the data can be like this:

text [text1 & text2]
text [text1]
text [text2]
text

There is a "text" value (can be one, or more words) and can be followed by [] or no. In case [] exists, the text inside can be two words separated by & or only one of them (at the moment exists only two possible words but I think is better to get the words by separator instead of matching the exact word)

So my goal is to get the data in two different groups:

Group1: text

Group2: [text1, text2] (if exists)

My regex is:

(^([^\[])+)(.+?(?=&|\]))?(.+?(?=\]))?

I've tried this using findall which I think fits better with the result I want:

regex = "(^([^\[])+)(.+?(?=&|\]))?(.+?(?=\]))?"
result = re.findall(regex,text)

But it returns:

[('text ', ' ', '[text1 ', '& text2')]

And I want, something like:

[('text'), ('text1', 'text2')]

I've tried in this playground

How can I improve my regex pattern?

Thanks in advance.

Body:
I'm not familiar with python, but I don't think it's possible to get more than one value from one group in a regular expression, so my guess is that you'd have to use something like this

(\w+)(?: \[(.*)\])?

Which will give you one or two groups

[('text'), ('text1 & text2')]
[('text'), ('text1')]
[('text'), ('text2')]
[('text')]

And then if the second group exists, use a second regular expression to get each individual value from it.

You can have a look here: https://regex101.com/r/DxF5p1/1


问:
I am trying to extract a newspaper data by clicking at next button to get more links
I am trying to extract business standard newspaper economy section data by clicking on the links but I am failing to do it.</p>
```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# Here Chrome is used

# URL of website
url = "https://www.business-standard.com/search?q=economy"

# Opening the website
driver.get(url)

# #button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@href='#']"))).click()
button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(., 'Next')]]"))).click()
</code>```

答:
There are several issues here:

You need to close the floating banner

You are using a wrong locator.

there is no need to define button element on the left side when you click the element returned instantly.

This should work better:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# Here Chrome is used

# URL of website
url = "https://www.business-standard.com/search?q=economy"

# Opening the website
driver.get(url)

wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.btnno"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='next-colum']"))).click()
```

Body:
I am trying to extract business standard newspaper economy section data by clicking on the links but I am failing to do it.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# Here Chrome is used

# URL of website
url = "https://www.business-standard.com/search?q=economy"

# Opening the website
driver.get(url)

# #button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@href='#']"))).click()
button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(., 'Next')]]"))).click()


问:
Accessing private members of surrounding class
I have two classes like this:

#include <iostream>

class A {
    public:
        class B {
            public:
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
    private:
        int x;
};
```
<p>Obviously this piece of code doesn't work because <code>B</code> can't access <code>x</code>, but is there a way to make it work?</p>
<p>I've tried using <code>friend class</code> keyword in both classes like this:</p>
<pre class="lang-c prettyprint-override"><code>class A {
    public:
        class B {
            public:
            friend class A;
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
        friend class B;
    private:
        int x;
};
</code>```

But it didn't work either, and I can't figure out if it's even possible.

答:
As the error message should tell you, A::x isn’t a static member so you need an object instance to access it. If you add a reference to instance of A to B::A, you can use that to access A::x.

For example, the following works:

```<code>class A {
    public:
        class B {
            public:
                B(A const& a) : a(a) {}
                void printX(void) const { std::cout << a.x << std::endl; }

            private:
                A const& a;
        };
    private:
        int x;
};
</code>```

Note that using a reference member has several implications. Notably, you can now no longer reassign instances of type A::B, nor are its instances movable. As a consequence, it’s often convenient to hold a pointer rather than a reference to A inside A::B. Either way, you’ll need to ensure that instances of A::B do not outlive the A instance they refer to, otherwise you end up with a dangling reference.

Body:
I have two classes like this:

#include <iostream>

class A {
    public:
        class B {
            public:
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
    private:
        int x;
};

Obviously this piece of code doesn't work because B can't access x, but is there a way to make it work?

I've tried using friend class keyword in both classes like this:

class A {
    public:
        class B {
            public:
            friend class A;
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
        friend class B;
    private:
        int x;
};

But it didn't work either, and I can't figure out if it's even possible.

Body:
As the error message should tell you, A::x isn’t a static member so you need an object instance to access it. If you add a reference to instance of A to B::A, you can use that to access A::x.

For example, the following works:

class A {
    public:
        class B {
            public:
                B(A const& a) : a(a) {}
                void printX(void) const { std::cout << a.x << std::endl; }

            private:
                A const& a;
        };
    private:
        int x;
};

Note that using a reference member has several implications. Notably, you can now no longer reassign instances of type A::B, nor are its instances movable. As a consequence, it’s often convenient to hold a pointer rather than a reference to A inside A::B. Either way, you’ll need to ensure that instances of A::B do not outlive the A instance they refer to, otherwise you end up with a dangling reference.


问:
Getting <django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0> instead of values
I want to write all model fields to a text file but I am getting:How can I fix this?
I am making a patient registration form and after registration I want to see all the model fields in the text file. The code works, I am getting a text file but instead of the expected value I am seeing a deferredattribute. Where is my fault?

This is my model.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):

    soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="")
    soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="")
    soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="")
    soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="")
</code>```

This is my views.py:

```<code>from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post
from .forms import PostForm
from django.urls import reverse_lazy
from django.db.models import Q
from django.http import HttpResponse
from django.core.files import File

#Dosya Kaydetme

def writetofile(request):
    f = open('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar/test.txt', 'w')
    textfile = File(f)

    kayitlar = Post.objects.all()
    lines = []
    for kayit in kayitlar:
        lines.append(f'{Post.soru1}')

    textfile.write(str(lines))
    textfile.close
    f.close
    return HttpResponse()
</code>```

And here is the result:

```<code>['<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>', '<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>']
</code>```

答:
You have to change Post.soru1 to kayit.soru1. It is because Post is call to the class, not instance you want to get in this case, that's why it shows only the model field instead of an instance's value.

kayitlar = Post.objects.all() here you assigned the all existing instances of Post model to variable kayitlar. Now you can forget about Post and process further the kayitlar variable with all objects.

Body:
I want to write all model fields to a text file but I am getting:How can I fix this?
I am making a patient registration form and after registration I want to see all the model fields in the text file. The code works, I am getting a text file but instead of the expected value I am seeing a deferredattribute. Where is my fault?

This is my model.py

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):

    soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="")
    soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="")
    soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="")
    soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="")

This is my views.py:

from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post
from .forms import PostForm
from django.urls import reverse_lazy
from django.db.models import Q
from django.http import HttpResponse
from django.core.files import File

#Dosya Kaydetme

def writetofile(request):
    f = open('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar/test.txt', 'w')
    textfile = File(f)

    kayitlar = Post.objects.all()
    lines = []
    for kayit in kayitlar:
        lines.append(f'{Post.soru1}')

    textfile.write(str(lines))
    textfile.close
    f.close
    return HttpResponse()

And here is the result:

['<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>', '<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>']