问:
Is it possible to add On Click Button method in a Fragment?
i have added a button in a xml file ..now i want to open it in fragment ..
i am trying to show share option on button click but not findViewbyid working nor anything happen when click on button after RUN..
May be this is the code for sharing.. I am Confused..Please Help

I have Tried My Best..Any Help Will be Appreciated..Thanks to All Experts

(XML Files)

activity_main :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation"
        />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemIconTint="@color/selector_item_gray_color"
        app:itemTextColor="@color/selector_item_gray_color"
        android:background="#302E2D"
        app:menu="@menu/bottom_navigation_android" />

</RelativeLayout>
</code>```

fragment_more :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:background="#fff"
    android:gravity="center_horizontal">

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center_horizontal">

        <androidx.appcompat.widget.SwitchCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Night Mode"
            android:textColor="@color/textcolour"></androidx.appcompat.widget.SwitchCompat>

        <Button
            android:id="@+id/btn_share"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_marginTop="85dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Share"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option2"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_share"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Recommend to friends"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option3"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option2"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Get Free Islamic Apps"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option4"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option3"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Rate and Feedback"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option5"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option4"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Help"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/textview6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="Example Text"
            android:textSize="12sp"
            android:textColor="#000000"/>

    </LinearLayout>

</RelativeLayout>
</code>```

(Java Files)

Main_Activity :

```<code>import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

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

        BottomNavigationView bottomnav = findViewById(R.id.bottom_navigation);
        bottomnav.setOnNavigationItemSelectedListener(navListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new Home_Fragment()).commit();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem MenuItem) {
                    Fragment selectedFragment = null;

                    switch (MenuItem.getItemId()) {
                        case R.id.nav_home:
                            selectedFragment = new Home_Fragment();
                            break;
                        case R.id.nav_settings:
                            selectedFragment = new More_Fragment();
                            break;
                    }

                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            selectedFragment).commit();

                    return true;
                }
            };
}
</code>```

Fragment_More :

```<code>import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class More_Fragment extends Fragment {

    Button btn;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_more, container,false);}

}
</code>```

Even Tried This Code in Fragment_More But Failed

```<code>import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class More_Fragment extends Fragment {

    private String a = "";
    private String b = "";

    private LinearLayout linear1;
    private Button btn_share;
    private TextView textview6;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_more, container,false);}

    private void initialize(Bundle _savedInstanceState) {

        linear1 = (LinearLayout) getActivity().findViewById(R.id.linear1);
        btn_share = (Button) getActivity().findViewById(R.id.btn_share);
        textview6 = (TextView) getActivity().findViewById(R.id.textview6);

        btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View _view) {
                a = textview6.getText().toString();
                b = textview6.getText().toString();
                Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
            }
        });
    }
    private void initializeLogic() { textview6.setVisibility(View.GONE);
    }

}
</code>```

答:
To reference your Button within your fragment you want to do it in onCreateView:</p>

```<code>public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     View rootView = inflater.inflate(R.layout.fragment_more, container,false);
     btn_share = (Button) rootView.findViewById(R.id.btn_share);
     btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View _view) {
                a = textview6.getText().toString();
                b = textview6.getText().toString();
                Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
            }
        });
     return rootView;
}
</code>```

Body:
i have added a button in a xml file ..now i want to open it in fragment ..
i am trying to show share option on button click but not findViewbyid working nor anything happen when click on button after RUN..
May be this is the code for sharing.. I am Confused..Please Help

I have Tried My Best..Any Help Will be Appreciated..Thanks to All Experts

(XML Files)

activity_main :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation"
        />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemIconTint="@color/selector_item_gray_color"
        app:itemTextColor="@color/selector_item_gray_color"
        android:background="#302E2D"
        app:menu="@menu/bottom_navigation_android" />

</RelativeLayout>

fragment_more :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:background="#fff"
    android:gravity="center_horizontal">

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center_horizontal">

        <androidx.appcompat.widget.SwitchCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Night Mode"
            android:textColor="@color/textcolour"></androidx.appcompat.widget.SwitchCompat>

        <Button
            android:id="@+id/btn_share"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_marginTop="85dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Share"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option2"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_share"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Recommend to friends"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option3"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option2"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Get Free Islamic Apps"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option4"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option3"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Rate and Feedback"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_option5"
            android:layout_width="250dp"
            android:layout_height="50dp"
            android:layout_below="@+id/btn_option4"
            android:layout_marginTop="10dp"
            android:background="@color/design_default_color_secondary_variant"
            android:text="Help"
            android:textColor="@color/textcolour"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/textview6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:text="Example Text"
            android:textSize="12sp"
            android:textColor="#000000"/>

    </LinearLayout>

</RelativeLayout>

(Java Files)

Main_Activity :

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

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

        BottomNavigationView bottomnav = findViewById(R.id.bottom_navigation);
        bottomnav.setOnNavigationItemSelectedListener(navListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new Home_Fragment()).commit();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem MenuItem) {
                    Fragment selectedFragment = null;

                    switch (MenuItem.getItemId()) {
                        case R.id.nav_home:
                            selectedFragment = new Home_Fragment();
                            break;
                        case R.id.nav_settings:
                            selectedFragment = new More_Fragment();
                            break;
                    }

                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            selectedFragment).commit();

                    return true;
                }
            };
}

Fragment_More :

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class More_Fragment extends Fragment {

    Button btn;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_more, container,false);}

}

Even Tried This Code in Fragment_More But Failed

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class More_Fragment extends Fragment {

    private String a = "";
    private String b = "";

    private LinearLayout linear1;
    private Button btn_share;
    private TextView textview6;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_more, container,false);}

    private void initialize(Bundle _savedInstanceState) {

        linear1 = (LinearLayout) getActivity().findViewById(R.id.linear1);
        btn_share = (Button) getActivity().findViewById(R.id.btn_share);
        textview6 = (TextView) getActivity().findViewById(R.id.textview6);

        btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View _view) {
                a = textview6.getText().toString();
                b = textview6.getText().toString();
                Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
            }
        });
    }
    private void initializeLogic() { textview6.setVisibility(View.GONE);
    }

}

Body:
To reference your Button within your fragment you want to do it in onCreateView:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     View rootView = inflater.inflate(R.layout.fragment_more, container,false);
     btn_share = (Button) rootView.findViewById(R.id.btn_share);
     btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View _view) {
                a = textview6.getText().toString();
                b = textview6.getText().toString();
                Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
            }
        });
     return rootView;
}


来源: stackexchange

问:
Firebase Function Error: The default Firebase app does not exist
Previously, the function worked. but I added some code, now this error is coming. How to fix this issue?

```<code>Error: Error occurred while parsing your function triggers.

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
    at FirebaseAppError.FirebaseError [as constructor] (/Users/demo/functions/node_modules/firebase-admin/lib/utils/error.js:42:28)
</code>```

code

```<code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { getLocations, getLocationsByType } from '../service/locationQuery/locationQuery';

//I tried both way, but same error came
// admin.initializeApp(functions.config().firebase);
admin.initializeApp();
exports.findUsers = functions.https.onCall(async (data: any, context: any) => {
</code>```

答:
I changed initialize place.. now It's working. I have no idea why is that.</p>

```<code>import * as admin from 'firebase-admin';
admin.initializeApp();//add to here
import { getLocations, getLocationsByType } from '../service/locationQuery/locationQuery';

// admin.initializeApp(functions.config().firebase);

exports.findUsers = functions.https.onCall(async (data: any, context: any) => {
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Previously, the function worked. but I added some code, now this error is coming. How to fix this issue?

Error: Error occurred while parsing your function triggers.

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
    at FirebaseAppError.FirebaseError [as constructor] (/Users/demo/functions/node_modules/firebase-admin/lib/utils/error.js:42:28)

code

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { getLocations, getLocationsByType } from '../service/locationQuery/locationQuery';

//I tried both way, but same error came
// admin.initializeApp(functions.config().firebase);
admin.initializeApp();
exports.findUsers = functions.https.onCall(async (data: any, context: any) => {

Body:
I changed initialize place.. now It's working. I have no idea why is that.

import * as admin from 'firebase-admin';
admin.initializeApp();//add to here
import { getLocations, getLocationsByType } from '../service/locationQuery/locationQuery';

// admin.initializeApp(functions.config().firebase);

exports.findUsers = functions.https.onCall(async (data: any, context: any) => {


问:
When I try to run react for first time on my Windows 10 machine, I get this error in the browser at localhost:3000
Here is the message below about the error.
It turns out that I had to re-install it to fix the error as some package errors occured (thanks to the comment below which hinted that this type of errors comes with package errors.)</p>

```<code>        TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
        at validateString (internal/validators.js:112:11)
        at Object.join (path.js:375:7)
        at noopServiceWorkerMiddleware (C:\myapp1\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
        at Layer.handle [as handle_request] (C:\myapp1\node_modules\express\lib\router\layer.js:95:5)
        at trim_prefix (C:\myapp1\node_modules\express\lib\router\index.js:317:13)
        at C:\myapp1\node_modules\express\lib\router\index.js:284:7
        at Function.process_params (C:\myapp1\node_modules\express\lib\router\index.js:335:12)
        at next (C:\myapp1\node_modules\express\lib\router\index.js:275:10)
        at launchEditorMiddleware (C:\myapp1\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
        at Layer.handle [as handle_request] (C:\myapp1\node_modules\express\lib\router\layer.js:95:5)
        at trim_prefix (C:\myapp1\node_modules\express\lib\router\index.js:317:13)
        at C:\myapp1\node_modules\express\lib\router\index.js:284:7
        at Function.process_params (C:\myapp1\node_modules\express\lib\router\index.js:335:12)
        at next (C:\myapp1\node_modules\express\lib\router\index.js:275:10)
        at handleWebpackInternalMiddleware (C:\myapp1\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
        at Layer.handle [as handle_request] (C:\myapp1\node_modules\express\lib\router\layer.js:95:5)
</code>```

答:
It would be better if you showed us your package.json file or your code.
Sometimes this error appears because of deprecated npm packages. We need to see your code in order to help you.

Body:
Here is the message below about the error.
It turns out that I had to re-install it to fix the error as some package errors occured (thanks to the comment below which hinted that this type of errors comes with package errors.)

        TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
        at validateString (internal/validators.js:112:11)
        at Object.join (path.js:375:7)
        at noopServiceWorkerMiddleware (C:\myapp1\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
        at Layer.handle [as handle_request] (C:\myapp1\node_modules\express\lib\router\layer.js:95:5)
        at trim_prefix (C:\myapp1\node_modules\express\lib\router\index.js:317:13)
        at C:\myapp1\node_modules\express\lib\router\index.js:284:7
        at Function.process_params (C:\myapp1\node_modules\express\lib\router\index.js:335:12)
        at next (C:\myapp1\node_modules\express\lib\router\index.js:275:10)
        at launchEditorMiddleware (C:\myapp1\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
        at Layer.handle [as handle_request] (C:\myapp1\node_modules\express\lib\router\layer.js:95:5)
        at trim_prefix (C:\myapp1\node_modules\express\lib\router\index.js:317:13)
        at C:\myapp1\node_modules\express\lib\router\index.js:284:7
        at Function.process_params (C:\myapp1\node_modules\express\lib\router\index.js:335:12)
        at next (C:\myapp1\node_modules\express\lib\router\index.js:275:10)
        at handleWebpackInternalMiddleware (C:\myapp1\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
        at Layer.handle [as handle_request] (C:\myapp1\node_modules\express\lib\router\layer.js:95:5)


问:
codeigniter transact add data into two table
hi i have a problem about adding data into two tables, heres the situation, i want to add a student with his username and password in users table and his personal info like name and age into users_profiles,, heres my code:

function add_user($username,$password,$fname,$lname,$sex,$address,$city,$country,$role)
    {
        $this->db->trans_start();

```<code>    $user = array(
    'usrName'=>$username,
    'usrPassword'=>sha1($password),
    'roleID'=>$role
    );

    $this->db->insert('users', $user);

    $this->db->query('SELECT usrID FROM users WHERE usrName=$username');

    $usrID = $this->db->get(); //i know this is wrong thats why i need help

    $user_profile = array(
    'usrpFirstName'=>$fname,
    'usrpLastName'=>$lname,
    'usrpSex'=>$sex,
    'usrpAddress'=>$address,
    'usrpCity'=>$city,
    'usrpState'=>$country,
    'usrID'=>**$usrID** // this is the foreign key from users table
    );

    $this->db->insert('users_profiles', $user_profile);

    $this->db->trans_complete();
}
</code>```

答:
You do not need to use get() when you use the query() method. Instead store the result from the query() method and use result() or row() to access the data.

So your code should be something like:

```<code>$result = $this->db->query("SELECT usrID FROM users WHERE usrName=$username");

$row = $result->row();

$user_profile = array(
  'usrpFirstName'=>$fname,
  'usrpLastName'=>$lname,
  'usrpSex'=>$sex,
  'usrpAddress'=>$address,
  'usrpCity'=>$city,
  'usrpState'=>$country,
  'usrID'=>$row->usrID
);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
hi i have a problem about adding data into two tables, heres the situation, i want to add a student with his username and password in users table and his personal info like name and age into users_profiles,, heres my code:

function add_user($username,$password,$fname,$lname,$sex,$address,$city,$country,$role)
    {
        $this->db->trans_start();

    $user = array(
    'usrName'=>$username,
    'usrPassword'=>sha1($password),
    'roleID'=>$role
    );

    $this->db->insert('users', $user);

    $this->db->query('SELECT usrID FROM users WHERE usrName=$username');

    $usrID = $this->db->get(); //i know this is wrong thats why i need help

    $user_profile = array(
    'usrpFirstName'=>$fname,
    'usrpLastName'=>$lname,
    'usrpSex'=>$sex,
    'usrpAddress'=>$address,
    'usrpCity'=>$city,
    'usrpState'=>$country,
    'usrID'=>**$usrID** // this is the foreign key from users table
    );

    $this->db->insert('users_profiles', $user_profile);

    $this->db->trans_complete();
}

Body:
You do not need to use get() when you use the query() method. Instead store the result from the query() method and use result() or row() to access the data.

So your code should be something like:

$result = $this->db->query("SELECT usrID FROM users WHERE usrName=$username");

$row = $result->row();

$user_profile = array(
  'usrpFirstName'=>$fname,
  'usrpLastName'=>$lname,
  'usrpSex'=>$sex,
  'usrpAddress'=>$address,
  'usrpCity'=>$city,
  'usrpState'=>$country,
  'usrID'=>$row->usrID
);


问:
Oracle DB, concat all values from 1 column using "," separator
I have Oracle DB table with 1 column UUID

How can I concatenate all the UUID values in one string separated by "," so the output will be like

```<code>"id1","id2","id3","id4"....
</code>```

答:
You can use listagg():

```<code>select listagg(uuid, ',') within group(order by uuid) uuids
from mytable
</code>```

This will give you a single record with a single column containing all uuids, separated with a comma.

Note that listagg() returns a varchar, hence the output cannot be more than 4000 bytes.

Also note that:

the comma is the default separator, so in your case it is not strictly necessary to pass a second argument to the function

I added an order by clause in order to generate a deterministic result: this option is not mandatory, so if the ordering of items in the list does not matter to you then you can leave it apart (in which case you will get the uuids in an undefined order)

Body:
I have Oracle DB table with 1 column UUID

How can I concatenate all the UUID values in one string separated by "," so the output will be like

"id1","id2","id3","id4"....

Body:
You can use listagg():

select listagg(uuid, ',') within group(order by uuid) uuids
from mytable

This will give you a single record with a single column containing all uuids, separated with a comma.

Note that listagg() returns a varchar, hence the output cannot be more than 4000 bytes.

Also note that:

the comma is the default separator, so in your case it is not strictly necessary to pass a second argument to the function

I added an order by clause in order to generate a deterministic result: this option is not mandatory, so if the ordering of items in the list does not matter to you then you can leave it apart (in which case you will get the uuids in an undefined order)


问:
Add custom IIS handler
I'm facing issues in making a new handler (the very first I've ever tried) for IIS.
My setup is:

IIS on Windows Server 2012

  Visual Studio 2017 on Windows 10 (currently running php website)

This is the code of mt handler:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ProvaIISdotNET
{
    class myHandler : IHttpHandler
    {
        #region IHttpHandler Members
        public bool IsReusable {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {

            context.Response.Write("<html><body>Hi everybody!</body></html>");
        }

        #endregion
    }

}
</code>```

On Visual Studio I made a new visual C# project > class library (.Net Framework)

added System.web to the references

compiled the code (release) for .NET 4

copied the dll file in <s>c:\inetpub\wwwroot\mysite\bin</s> c:\inetpub\wwwroot

<s> added the mapping path to test.test , test as 'name'.</s>

<s>In handler mapping > add managed handler I can't find the "myHandler" Type, even adding it manually the page at mysite/test.test get 404 not found.</s>

Edited my c:\inetpub\wwwroot\web.config as follows:

```<code><configuration>
    <system.webServer>
     <handlers>
        <add name="myhandler" path="/handled/*.my" verb="GET" type="ProvaIISdotNET.myHandler" />
    </handlers>
        <defaultDocument>
            <files>
                <add value="home.html" />
                <add value="home.php" />
            </files>
        </defaultDocument>
        <httpErrors errorMode="Detailed" />
    </system.webServer>
</configuration>
</code>```

When going to http://localhost/handled/test.my
I still get 404

What am I missing?

EDIT -20/2/2020- Edited to reflect the results after edits suggested by Jokies Ding

答:
This is how I deploy my handler.
1.Create a assembly project called "ProvaIISdotNET".

2.I remove the default class.cs and created my myHandler.cs

3.I copied the code like this. Since VS alarmed for system.linq and it is not require here, I removed it.

```<code>using System;
using System.Collections.Generic;

using System.Text;
using System.Web;

namespace ProvaIISdotNET
{
    class myHandler : IHttpHandler
    {
        #region IHttpHandler Members
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {

            context.Response.Write("<html><body>Hi everybody!</body></html>");
        }

        #endregion
    }

}
</code>```

I copy the release .dll to my site's root bin folder D:\mysite\bin (Please ensure you are placing the assembly in the root bin folder)

I added this to the root web.config system.webserver\handlers section. Please ensure no blank space " " have been placed in the end of type attribute.

```<code> <handlers>
        <add name="myhandler" path="*" verb="GET" type="ProvaIISdotNET.myHandler" />
    </handlers>
</code>```

6.I recycled the application pool.

Now its working on my side

Edit:

If the handler added correct, you will see this in C:\inetpub\logs\FailedReqLogFiles\W3SVC(siteID).

You could view the FRT log in IE

Title: Add custom IIS handler

Body:
I'm facing issues in making a new handler (the very first I've ever tried) for IIS.
My setup is:

IIS on Windows Server 2012

  Visual Studio 2017 on Windows 10 (currently running php website)

This is the code of mt handler:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ProvaIISdotNET
{
    class myHandler : IHttpHandler
    {
        #region IHttpHandler Members
        public bool IsReusable {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {

            context.Response.Write("Hi everybody!");
        }

        #endregion
    }

}

On Visual Studio I made a new visual C# project > class library (.Net Framework)

added System.web to the references

compiled the code (release) for .NET 4

copied the dll file in <s>c:\inetpub\wwwroot\mysite\bin</s> c:\inetpub\wwwroot

<s> added the mapping path to test.test , test as 'name'.</s>

<s>In handler mapping > add managed handler I can't find the "myHandler" Type, even adding it manually the page at mysite/test.test get 404 not found.</s>

Edited my c:\inetpub\wwwroot\web.config as follows:

<configuration>
    <system.webServer>
     <handlers>
        <add name="myhandler" path="/handled/*.my" verb="GET" type="ProvaIISdotNET.myHandler" />
    </handlers>
        <defaultDocument>
            <files>
                <add value="home.html" />
                <add value="home.php" />
            </files>
        </defaultDocument>
        <httpErrors errorMode="Detailed" />
    </system.webServer>
</configuration>

When going to http://localhost/handled/test.my
I still get 404

What am I missing?

EDIT -20/2/2020- Edited to reflect the results after edits suggested by Jokies Ding

Body:
This is how I deploy my handler.
1.Create a assembly project called "ProvaIISdotNET".

2.I remove the default class.cs and created my myHandler.cs

3.I copied the code like this. Since VS alarmed for system.linq and it is not require here, I removed it.

using System;
using System.Collections.Generic;

using System.Text;
using System.Web;

namespace ProvaIISdotNET
{
    class myHandler : IHttpHandler
    {
        #region IHttpHandler Members
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {

            context.Response.Write("<html><body>Hi everybody!</body></html>");
        }

        #endregion
    }

}

I copy the release .dll to my site's root bin folder D:\mysite\bin (Please ensure you are placing the assembly in the root bin folder)

I added this to the root web.config system.webserver\handlers section. Please ensure no blank space " " have been placed in the end of type attribute.

 <handlers>
        <add name="myhandler" path="*" verb="GET" type="ProvaIISdotNET.myHandler" />
    </handlers>

6.I recycled the application pool.

Now its working on my side

Edit:

If the handler added correct, you will see this in C:\inetpub\logs\FailedReqLogFiles\W3SVC(siteID).

You could view the FRT log in IE


问:
C++ template packed parameters
I'm wondering how I can specify a template type as "parameter pack".

The commented line doesn't work because it can't deduce T (it has the same template parameters). On the next line I can fix that by supplying T but I'm stuck at how I should supply the parameter pack type (where the question marks are.).

```<code>template<typename T, typename... Args> T& Entity::addComponent(Args&&... args) const
{
    //return entityManager->addComponent(std::forward<Args>(args)...);
    return entityManager->addComponent<T, ?????>(std::forward<Args>(args)...);
}
</code>```

I want to use Args as that type.

答: It worked when I set Visual studio "Conformance Mode" setting to "No"</p>

Title: C++ template packed parameters

Body:
I'm wondering how I can specify a template type as "parameter pack".

The commented line doesn't work because it can't deduce T (it has the same template parameters). On the next line I can fix that by supplying T but I'm stuck at how I should supply the parameter pack type (where the question marks are.).

template<typename T, typename... Args> T& Entity::addComponent(Args&&... args) const
{
    //return entityManager->addComponent(std::forward<Args>(args)...);
    return entityManager->addComponent<T, ?????>(std::forward<Args>(args)...);
}

I want to use Args as that type.


问:
Does reading the Cosmos DB Change Feed consume RU/s?
Does reading the Cosmos DB Change Feed consume RU/s on the container whose feed is being read? From my experimentation, I think the answer is "no", but I'd love confirmation. I cannot find the answer in the docs. Thanks!</p>

答:
Actually I am struggling with a similar question, also can't find any concrete doc (just as @Sajeetharan) but my findings may be of help to you. I was wondering how listening to the Change Feed would affect the registered traffic (or better: RU count). I expected it to be of minimal impact and in any case much lower than a manual polling mechanism. That should be a major point of a Change Feed, shouldn't it?

Remark: I am using C# and the CosmosDB-MongoDB-API. So the experienced behaviour might be an effect of the API implementation and not a result of the CosmosDB bookkeeping.

Anyway, I noticed this in my Metrics page:

This was a test with a C# application just running a Watch() on a collection, printing a marker as soon as the watcher noticed a change. Basically this:

```<code>using (var cursor = c.Watch(pipeline, new ChangeStreamOptions
        {
            FullDocument = ChangeStreamFullDocumentOption.UpdateLookup,
        }))
        {
            foreach (var change in cursor.ToEnumerable())
            {
                // process change event
                Console.WriteLine(change);
            }
        }
</code>```

With no changes to the collection, something obviously caused costs of about 1 RU/s... In my case, I don't need immediate notifications, so manual polling every few seconds would be much cheaper. That seems to narrow the purpose of the Change Feed a lot.

After reading the answer of @MatiasQuaranta (especially noticing the difference of 2RU/s vs. 1RU/s), I wanted to provide this piece of information as well. I still hope someone will come up with a more documented answer.

Body:
Actually I am struggling with a similar question, also can't find any concrete doc (just as @Sajeetharan) but my findings may be of help to you. I was wondering how listening to the Change Feed would affect the registered traffic (or better: RU count). I expected it to be of minimal impact and in any case much lower than a manual polling mechanism. That should be a major point of a Change Feed, shouldn't it?

Remark: I am using C# and the CosmosDB-MongoDB-API. So the experienced behaviour might be an effect of the API implementation and not a result of the CosmosDB bookkeeping.

Anyway, I noticed this in my Metrics page:

This was a test with a C# application just running a Watch() on a collection, printing a marker as soon as the watcher noticed a change. Basically this:

using (var cursor = c.Watch(pipeline, new ChangeStreamOptions
        {
            FullDocument = ChangeStreamFullDocumentOption.UpdateLookup,
        }))
        {
            foreach (var change in cursor.ToEnumerable())
            {
                // process change event
                Console.WriteLine(change);
            }
        }

With no changes to the collection, something obviously caused costs of about 1 RU/s... In my case, I don't need immediate notifications, so manual polling every few seconds would be much cheaper. That seems to narrow the purpose of the Change Feed a lot.

After reading the answer of @MatiasQuaranta (especially noticing the difference of 2RU/s vs. 1RU/s), I wanted to provide this piece of information as well. I still hope someone will come up with a more documented answer.


问:
Taking notes with filename input not working html?
I have added a simple not taking page to my website, which takes in user input of filename and the notedata.

However whenever I run the code the code I just get a bunch of errors and some non-working code:

HTML form:

```<code><form method="post">
    <div style="margin-right:">
      <input type="text" class="fileName" name="fileName" id="fileName" size="35"><br>
      <textarea type="text" name="notes" id="notes"></textarea><br>
      <input type="Submit" name="Submit" value="Save">
    </div>
</form>
</code>```

PHP form:

```<code>$noteName = $_POST['fileName'];
(line 51:)$noteData = $_POST['notes'];

(line 53:)$notes = fopen('' + $noteName,"wb");
fwrite($notes,$noteData);
fclose($notes);
</code>```

Error list:

Notice: Undefined index: notes in C:\xampp\htdocs\NNDbase.php on line 51

Warning: A non-numeric value encountered in C:\xampp\htdocs\NNDbase.php on line 53

Warning: A non-numeric value encountered in C:\xampp\htdocs\NNDbase.php on line 53

答:
Try this

```<code> if($_POST){
    $noteName = $_POST['fileName'];
    $noteData = $_POST['notes'];
    $notes = fopen('' + $noteName,"wb");
    fwrite($notes,$noteData);
    fclose($notes);
}
</code>```

Body:
I have added a simple not taking page to my website, which takes in user input of filename and the notedata.

However whenever I run the code the code I just get a bunch of errors and some non-working code:

HTML form:

<form method="post">

      <input type="text" class="fileName" name="fileName" id="fileName" size="35">

      <textarea type="text" name="notes" id="notes"></textarea>

      <input type="Submit" name="Submit" value="Save">

</form>

PHP form:

$noteName = $_POST['fileName'];
(line 51:)$noteData = $_POST['notes'];

(line 53:)$notes = fopen('' + $noteName,"wb");
fwrite($notes,$noteData);
fclose($notes);

Error list:

Notice: Undefined index: notes in C:\xampp\htdocs\NNDbase.php on line 51

Warning: A non-numeric value encountered in C:\xampp\htdocs\NNDbase.php on line 53

Warning: A non-numeric value encountered in C:\xampp\htdocs\NNDbase.php on line 53

Body:
Try this

 if($_POST){
    $noteName = $_POST['fileName'];
    $noteData = $_POST['notes'];
    $notes = fopen('' + $noteName,"wb");
    fwrite($notes,$noteData);
    fclose($notes);
}


问:
Filter query result by field value inside array of objects [Sanity.io & GROQ]
I'm trying to find a product variant inside my list of products(on sanity.io using GROQ), to do so, I have the sku of the variant that I want.

The query I'm using is
*[_type == "product" && variants[].sku.current =="kit-kat-wasabi-5" ]
But this query returns an empty array. I'm sure that the sku is correct because if I leave the filter aside, and fetch all I can find it.
I tried replacing the "==" with match, but the result is the same.

my schemas are

procuct

```<code>export default {
  name: 'product',
  title: 'Product',
  type: 'document',
  fields: [
    {
      name: 'title',
      title: 'Inner Title',
      type: 'string'
    },
    {
      title: 'SKU',
      name: 'sku',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      },
      validation: Rule => Rule.required()
    },
    {
      name: 'titleWebsite',
      title: 'Title Website',
      type: 'localeString'
    },
    {
      name: 'active',
      title: 'Active',
      type: 'boolean'
    },
    {
      name: 'mainImage',
      title: 'Imagem',
      type:"image"
    },
    {
      name: 'slug',
      title: 'Slug',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      }
    },
    {
      title: 'Base Price',
      name: 'basePrice',
      type: 'localeCurrency'
    },
    {
      title: 'Quantidade',
      name: 'qty',
      type: 'number'
    },
   /* {
      title: 'Default variant',
      name: 'defaultProductVariant',
      type: 'productVariant'
    },*/
    {
      title: 'Variants',
      name: 'variants',
      type: 'array',
      of: [
        {
          title: 'Variant',
          type: 'productVariant'
        }
      ]
    },
    {
      title: 'Tags',
      name: 'tags',
      type: 'array',
      of: [
        {
          type: 'string'
        }
      ],
      options: {
        layout: 'tags'
      }
    },
    {
      name: 'vendor',
      title: 'Vendor',
      type: 'reference',
      to: {type: 'vendor'}
    },
    {
      name: 'blurb',
      title: 'Blurb',
      type: 'localeString'
    },

    {
      name: 'categories',
      title: 'Categories',
      type: 'array',
      of: [
        {
          type: 'reference',
          to: {type: 'category'}
        }
      ]
    },
    {
      name: 'body',
      title: 'Body',
      type: 'localeBlockContent'
    }
  ],

  preview: {
    select: {
      title: 'title',
      manufactor: 'manufactor.title',
      media: 'mainImage'
    }
  }
}

</code>```

And productVariant

```<code>export default {
  title: 'Product variant',
  name: 'productVariant',
  type: 'object',
  fields: [
    {
      title: 'Title',
      name: 'title',
      type: 'string'
    },
    {
      title: 'Title Website',
      name: 'titleWebsite',
      type: 'localeString'
    },
    {
      title: 'Weight in grams',
      name: 'grams',
      type: 'number'
    },
    {
      title: 'Price',
      name: 'price',
      type: 'localeCurrency'
    },
    {
      title: 'SKU',
      name: 'sku',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      },
      validation: Rule => Rule.required()
    },
    {
      title: 'Taxable',
      name: 'taxable',
      type: 'boolean'
    },
    {
      name: 'blurb',
      title: 'Blurb',
      type: 'localeString'
    },
    {
      name: 'images',
      title: 'Images',
      type: 'array',
      of: [
        {
          type: 'image',
          options: {
            hotspot: true
          }
        }
      ]
    },
    {
      title: 'Quantidade',
      name: 'qty',
      type: 'number'
    },
    {
      title: 'Bar code',
      name: 'barcode',
      type: 'barcode'
    }
  ]
}

</code>```

答:
This is a known bug in GROQ when traversing arrays. This will introduce breaking changes if it were to be fixed in GROQ v1. It will therefore be fixed in GROQ v2.

Here is a bug report explaining the issue: https://github.com/sanity-io/sanity/issues/1557. You can show your interest in this problem here.

There's a working draft for version two here: https://github.com/sanity-io/groq.

Regarding your schema, I would consider to change the type of the sku field to be something else, for example a string, and create a new field for the slug which has its source property set to the SKU to be automatically be generated by that field. Documentation for that can be found here: https://www.sanity.io/docs/slug-type.

Body:
I'm trying to find a product variant inside my list of products(on sanity.io using GROQ), to do so, I have the sku of the variant that I want.

The query I'm using is
*[_type == "product" && variants[].sku.current =="kit-kat-wasabi-5" ]
But this query returns an empty array. I'm sure that the sku is correct because if I leave the filter aside, and fetch all I can find it.
I tried replacing the "==" with match, but the result is the same.

my schemas are

procuct

export default {
  name: 'product',
  title: 'Product',
  type: 'document',
  fields: [
    {
      name: 'title',
      title: 'Inner Title',
      type: 'string'
    },
    {
      title: 'SKU',
      name: 'sku',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      },
      validation: Rule => Rule.required()
    },
    {
      name: 'titleWebsite',
      title: 'Title Website',
      type: 'localeString'
    },
    {
      name: 'active',
      title: 'Active',
      type: 'boolean'
    },
    {
      name: 'mainImage',
      title: 'Imagem',
      type:"image"
    },
    {
      name: 'slug',
      title: 'Slug',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      }
    },
    {
      title: 'Base Price',
      name: 'basePrice',
      type: 'localeCurrency'
    },
    {
      title: 'Quantidade',
      name: 'qty',
      type: 'number'
    },
   /* {
      title: 'Default variant',
      name: 'defaultProductVariant',
      type: 'productVariant'
    },*/
    {
      title: 'Variants',
      name: 'variants',
      type: 'array',
      of: [
        {
          title: 'Variant',
          type: 'productVariant'
        }
      ]
    },
    {
      title: 'Tags',
      name: 'tags',
      type: 'array',
      of: [
        {
          type: 'string'
        }
      ],
      options: {
        layout: 'tags'
      }
    },
    {
      name: 'vendor',
      title: 'Vendor',
      type: 'reference',
      to: {type: 'vendor'}
    },
    {
      name: 'blurb',
      title: 'Blurb',
      type: 'localeString'
    },

    {
      name: 'categories',
      title: 'Categories',
      type: 'array',
      of: [
        {
          type: 'reference',
          to: {type: 'category'}
        }
      ]
    },
    {
      name: 'body',
      title: 'Body',
      type: 'localeBlockContent'
    }
  ],

  preview: {
    select: {
      title: 'title',
      manufactor: 'manufactor.title',
      media: 'mainImage'
    }
  }
}

And productVariant

export default {
  title: 'Product variant',
  name: 'productVariant',
  type: 'object',
  fields: [
    {
      title: 'Title',
      name: 'title',
      type: 'string'
    },
    {
      title: 'Title Website',
      name: 'titleWebsite',
      type: 'localeString'
    },
    {
      title: 'Weight in grams',
      name: 'grams',
      type: 'number'
    },
    {
      title: 'Price',
      name: 'price',
      type: 'localeCurrency'
    },
    {
      title: 'SKU',
      name: 'sku',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96
      },
      validation: Rule => Rule.required()
    },
    {
      title: 'Taxable',
      name: 'taxable',
      type: 'boolean'
    },
    {
      name: 'blurb',
      title: 'Blurb',
      type: 'localeString'
    },
    {
      name: 'images',
      title: 'Images',
      type: 'array',
      of: [
        {
          type: 'image',
          options: {
            hotspot: true
          }
        }
      ]
    },
    {
      title: 'Quantidade',
      name: 'qty',
      type: 'number'
    },
    {
      title: 'Bar code',
      name: 'barcode',
      type: 'barcode'
    }
  ]
}


答:
You can use listagg() -- assuming there are not too many values.  The maximum string size is 4000 bytes.

```<code>selest '"' || listagg(uuid, '","') within group (order by uuid) || '"'
</code>```

Title: Oracle DB, concat all values from 1 column using "," separator

Body:
You can use listagg() -- assuming there are not too many values.  The maximum string size is 4000 bytes.

selest '"' || listagg(uuid, '","') within group (order by uuid) || '"'


问:
React Component not rendered properly with Turbolinks in Rails 5.1
I have a very simple Rails app with a react component that just displays "Hello" in an existing div element in a particular page (let's say the show page).

When I load the related page using its URL, it works. I see Hello on the page.

However, when I'm previously on another page (let's say the index page and then I go to the show page using Turbolinks, well, the component is not rendered, unless I go back and forth again. (going back to the index Page and coming back to the show page)

From here every time I go back and forth, I can say that the view is rendered twice more time.
Not only twice but twice more time! (i.e. 2 times then 4, then 6 etc..)

I know that since in the same time I set the content of the div I output a message to the console.

In fact I guess that going back to the index page should still run the component code without the display since the div element is not on the index page. But why in a cumulative manner?

The problems I want to solve are:

To get the code run on the first request of the show page

To block the code from running in other pages (including the index page)

To get the code run once on subsequent requests of the show page

Here the exact steps and code I used (I'll try to be as concise as possible.)

I have a Rails 5.1 app with react installed with:

```<code>rails new myapp --webpack=react
</code>```

I then create a simple Item scaffold to get some pages to play with:

```<code>rails generate scaffold Item name
</code>```

I just add the following div element in the Show page (app/views/items/show.html.erb):

```<code><div id=hello></div>
</code>```

Webpacker already generated a Hello component (hello_react.jsx) that I modified as following in ordered to use the above div element. I changed the original 'DOMContentLoaded' event:

```<code>document.addEventListener('turbolinks:load', () => {
  console.log("DOM loaded..");
  var element = document.getElementById("hello");
  if(element) {
    ReactDOM.render(<Hello name="React" />, element)
  }
})
</code>```

I then added the following webpack script tag at the bottom of the previous view (app/views/items/show.html.erb):

```<code><%= javascript_pack_tag("hello_react") %>
</code>```

I then run the rails server and the webpack-dev-server using foreman start (installed by adding gem 'foreman' in the Gemfile) . Here is the content of the Procfile I used:

```<code>web:     bin/rails server -b 0.0.0.0 -p 3000
webpack: bin/webpack-dev-server --port 8080 --hot
</code>```

And here are the steps to follow to reproduce the described behavior:

Load the index page using the URL http://localhost:3000/items

Click New Item to add a new item. Rails redirects to the item's show page at the URL localhost:3000/items/1. Here we can see the Hello React! message. It works well!

Reload the index page using the URL http://localhost:3000/items. The item is displayed as expected.

Reload the show page using the URL http://localhost:3000/items/1. The Hello message is displayed as expected with one console message.

Reload the index page using the URL http://localhost:3000/items

Click to the Show link (should be performed via turbolink). The message is not shown neither the console message.

Click the Back link (should be performed via turbolink) to go to the index page.

Click again to the Show link (should be performed via turbolink). This time the message is well displayed. The console message for its part is shown twice.

From there each time I go back to the index and come back again to the show page displays two more messages at the console each time.

Note: Instead of using (and replacing) a particular div element, if I let the original hello_react file that append a div element, this behavior is even more noticeable.

Edit: Also, if I change the link_to links by including data: {turbolinks: false}. It works well. Just as we loaded the pages using the URLs in the browser address bar.

I don't know what I'm doing wrong..

Any ideas?

Edit: I put the code in the following repo if interested to try this:
https://github.com/sanjibukai/react-turbolinks-test

答:
I was struggling with similar problem (link_to helper method was changing URL but react content was not loaded; had to refresh page manually to load it properly). After some googling I've found simple workaround on this page.

```<code><%= link_to "Foo", new_rabbit_path(@rabbit), data: { turbolinks: false } %>
</code>```

Since this causes a full page refresh when the link is clicked, now my react pages are loaded properly. Maybe you will find it useful in your project as well :)

Body:
I have a very simple Rails app with a react component that just displays "Hello" in an existing div element in a particular page (let's say the show page).

When I load the related page using its URL, it works. I see Hello on the page.

However, when I'm previously on another page (let's say the index page and then I go to the show page using Turbolinks, well, the component is not rendered, unless I go back and forth again. (going back to the index Page and coming back to the show page)

From here every time I go back and forth, I can say that the view is rendered twice more time.
Not only twice but twice more time! (i.e. 2 times then 4, then 6 etc..)

I know that since in the same time I set the content of the div I output a message to the console.

In fact I guess that going back to the index page should still run the component code without the display since the div element is not on the index page. But why in a cumulative manner?

The problems I want to solve are:

To get the code run on the first request of the show page

To block the code from running in other pages (including the index page)

To get the code run once on subsequent requests of the show page

Here the exact steps and code I used (I'll try to be as concise as possible.)

I have a Rails 5.1 app with react installed with:

rails new myapp --webpack=react

I then create a simple Item scaffold to get some pages to play with:

rails generate scaffold Item name

I just add the following div element in the Show page (app/views/items/show.html.erb):

Webpacker already generated a Hello component (hello_react.jsx) that I modified as following in ordered to use the above div element. I changed the original 'DOMContentLoaded' event:

document.addEventListener('turbolinks:load', () => {
  console.log("DOM loaded..");
  var element = document.getElementById("hello");
  if(element) {
    ReactDOM.render(<Hello name="React" />, element)
  }
})

I then added the following webpack script tag at the bottom of the previous view (app/views/items/show.html.erb):

<%= javascript_pack_tag("hello_react") %>

I then run the rails server and the webpack-dev-server using foreman start (installed by adding gem 'foreman' in the Gemfile) . Here is the content of the Procfile I used:

web:     bin/rails server -b 0.0.0.0 -p 3000
webpack: bin/webpack-dev-server --port 8080 --hot

And here are the steps to follow to reproduce the described behavior:

Load the index page using the URL http://localhost:3000/items

Click New Item to add a new item. Rails redirects to the item's show page at the URL localhost:3000/items/1. Here we can see the Hello React! message. It works well!

Reload the index page using the URL http://localhost:3000/items. The item is displayed as expected.

Reload the show page using the URL http://localhost:3000/items/1. The Hello message is displayed as expected with one console message.

Reload the index page using the URL http://localhost:3000/items

Click to the Show link (should be performed via turbolink). The message is not shown neither the console message.

Click the Back link (should be performed via turbolink) to go to the index page.

Click again to the Show link (should be performed via turbolink). This time the message is well displayed. The console message for its part is shown twice.

From there each time I go back to the index and come back again to the show page displays two more messages at the console each time.

Note: Instead of using (and replacing) a particular div element, if I let the original hello_react file that append a div element, this behavior is even more noticeable.

Edit: Also, if I change the link_to links by including data: {turbolinks: false}. It works well. Just as we loaded the pages using the URLs in the browser address bar.

I don't know what I'm doing wrong..

Any ideas?

Edit: I put the code in the following repo if interested to try this:
https://github.com/sanjibukai/react-turbolinks-test

Body:
I was struggling with similar problem (link_to helper method was changing URL but react content was not loaded; had to refresh page manually to load it properly). After some googling I've found simple workaround on this page.

<%= link_to "Foo", new_rabbit_path(@rabbit), data: { turbolinks: false } %>

Since this causes a full page refresh when the link is clicked, now my react pages are loaded properly. Maybe you will find it useful in your project as well :)


问:
jQuery add class based on parent URL
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.

However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?

Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"

Here is my jQuery:

```<code>var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
    if(jQuery(this).attr('href')=== cururl){
        jQuery(this).addClass("current-slider-menu");
    }
});
</code>```

EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.

答:
Try this,

Change the class/selectors as per your requirement. This will add a unique class in the li element, now you can style this using css.

```<code>$(document).ready(function() {
  $(".main_menu li").removeClass('current-slider-menu');
  $(".main_menu li>a").filter(function(){
    return  this.href == location.href.replace(/#.*/, "");
  }).parent("li").addClass("current-slider-menu");
});
</code>```

Title: jQuery add class based on parent URL

Body:
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.

However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?

Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"

Here is my jQuery:

var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
    if(jQuery(this).attr('href')=== cururl){
        jQuery(this).addClass("current-slider-menu");
    }
});

EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.

Body:
Try this,

Change the class/selectors as per your requirement. This will add a unique class in the li element, now you can style this using css.

$(document).ready(function() {
  $(".main_menu li").removeClass('current-slider-menu');
  $(".main_menu li>a").filter(function(){
    return  this.href == location.href.replace(/#.*/, "");
  }).parent("li").addClass("current-slider-menu");
});


问:
How to enable TLS 1.2 in Java 7
I am trying to enable TLS 1.2 in my web app which uses JBoss 6.4 and Java 1.7. I have -Dhttp.protocols = TLSv1.2 in my application environment but it doesn't seem to work for me.

Is there anything I could do to enable TLS 1.2?

I wrote a simple program

```<code>context = SSLContext.getInstance("TLSv1.2");
context.init(null,null,null);
SSLContext.setDefault(context);
SSLSocketFactory factory = (SSLSocketFactory)context.getSocketFactory();
SSLSocket socket = (SSLSocket)factory.createSocket();
protocols = socket.getEnabledProtocols();
</code>```

After running this program within the app the TLS 1.2 gets enabled. I do not want to run this program but I want to directly enable it during app startup. Is there any way to do it?

答:
I had similar issue when connecting to RDS Oracle even when client and server were both set to TLSv1.2 the certs was right and java was 1.8.0_141
So Finally I had to apply patch at Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files

After applying the patch the issue went away and connection went fine.

Title: How to enable TLS 1.2 in Java 7

Body:
I am trying to enable TLS 1.2 in my web app which uses JBoss 6.4 and Java 1.7. I have -Dhttp.protocols = TLSv1.2 in my application environment but it doesn't seem to work for me.

Is there anything I could do to enable TLS 1.2?

I wrote a simple program

context = SSLContext.getInstance("TLSv1.2");
context.init(null,null,null);
SSLContext.setDefault(context);
SSLSocketFactory factory = (SSLSocketFactory)context.getSocketFactory();
SSLSocket socket = (SSLSocket)factory.createSocket();
protocols = socket.getEnabledProtocols();

After running this program within the app the TLS 1.2 gets enabled. I do not want to run this program but I want to directly enable it during app startup. Is there any way to do it?


问:
Microsoft T-SQL: Can I CONVERT smallint to varchar
It may just be me, but... Despite the fact that most sql developers may consider cast & convert to be very basic stuff, and that may be true, I find Microsoft's documentation page on CAST & CONVERT to be one of the most hideous, not-intuitively-laid-out, hard to understand things I have ever seen. Much of their documentation is great. Like constantly trying to blend the entire page into a mix of both cast and convert, jumping back and forth in each sentence... rather than dealing with them separately. And who puts the target_type as the first argument? Putting the expression as the first argument would be more intuitive - and follow the other 99% of numerous programming languages' syntax.  UH

MS says that I can only convert to 3 data types: (well actually I'm not really sure if this applies to both CAST and CONVERT, since they ARE, in fact, different... But according to the layout of that webpage, it apparently applies equally to both - even though I already know for a fact that it is not true for CAST, which I use much more frequently).

It says:  "Is the target data type. This includes xml, bigint, and sql_variant"

Putting aside for the moment the fact that I CAST things as many other datatypes all the time (date, varchar),

My immediate question is:  if I can only CONVERT to those data types, then why does this work?

```<code>select CONVERT(varchar(200), cast(50 as smallint))
</code>```

And finally, I'd like to run an INSERT that will be getting a smallint and putting it into a varchar(200) column.

All I'm trying to do is avoid any failures, so maybe I don't really "need" to convert or cast over to varchar, but any commments on

answer on what is my apparent misunderstanding about the CONVERT documentation

or

how to safely convert it to insert to varchar

are welcome. As long as you're not just overly unpleasant, since there are always those MS fans who get hot under the collar at all critiques of MS .. :|

答:
Numbers always get silently truncated for me. I would propose:

Option 1

Compare the converted value with the original value.

```<code>DECLARE @ORIGINAL DECIMAL(13,2) = -99999999999.99 --
DECLARE @EXPECTED VARCHAR(15) = ''
SELECT @EXPECTED = CONVERT(VARCHAR(15),@ORIGINAL)
IF CONVERT(DECIMAL(13,2),@EXPECTED) != @ORIGINAL SELECT 'Ooops'
</code>```

Option 2

Make sure that all possible values will fit in target varchar.

Decimal(13,2). Widest number possible will be "-99999999999.99" needs varchar(15):

13 chars for digits

1 char for decimal separator

1 char for minus sign

Smallint stores 2 bytes, from "-32768" to "32767", needs varchar(6):
 - 5 chars for digits
 - 1 char for minus sign

Not sure if you need chars for thousands separators, or if you can change it via settings.

Body:
It may just be me, but... Despite the fact that most sql developers may consider cast & convert to be very basic stuff, and that may be true, I find Microsoft's documentation page on CAST & CONVERT to be one of the most hideous, not-intuitively-laid-out, hard to understand things I have ever seen. Much of their documentation is great. Like constantly trying to blend the entire page into a mix of both cast and convert, jumping back and forth in each sentence... rather than dealing with them separately. And who puts the target_type as the first argument? Putting the expression as the first argument would be more intuitive - and follow the other 99% of numerous programming languages' syntax.  UH

MS says that I can only convert to 3 data types: (well actually I'm not really sure if this applies to both CAST and CONVERT, since they ARE, in fact, different... But according to the layout of that webpage, it apparently applies equally to both - even though I already know for a fact that it is not true for CAST, which I use much more frequently).

It says:  "Is the target data type. This includes xml, bigint, and sql_variant"

Putting aside for the moment the fact that I CAST things as many other datatypes all the time (date, varchar),

My immediate question is:  if I can only CONVERT to those data types, then why does this work?

select CONVERT(varchar(200), cast(50 as smallint))

And finally, I'd like to run an INSERT that will be getting a smallint and putting it into a varchar(200) column.

All I'm trying to do is avoid any failures, so maybe I don't really "need" to convert or cast over to varchar, but any commments on

answer on what is my apparent misunderstanding about the CONVERT documentation

or

how to safely convert it to insert to varchar

are welcome. As long as you're not just overly unpleasant, since there are always those MS fans who get hot under the collar at all critiques of MS .. :|

Body:
Numbers always get silently truncated for me. I would propose:

Option 1

Compare the converted value with the original value.

DECLARE @ORIGINAL DECIMAL(13,2) = -99999999999.99 --
DECLARE @EXPECTED VARCHAR(15) = ''
SELECT @EXPECTED = CONVERT(VARCHAR(15),@ORIGINAL)
IF CONVERT(DECIMAL(13,2),@EXPECTED) != @ORIGINAL SELECT 'Ooops'

Option 2

Make sure that all possible values will fit in target varchar.

Decimal(13,2). Widest number possible will be "-99999999999.99" needs varchar(15):

13 chars for digits

1 char for decimal separator

1 char for minus sign

Smallint stores 2 bytes, from "-32768" to "32767", needs varchar(6):
 - 5 chars for digits
 - 1 char for minus sign

Not sure if you need chars for thousands separators, or if you can change it via settings.


问:
Is there a C snippet that computes overflow-safe addition efficiently without using compiler builtins?
Here is a C function that adds an int to another, failing if overflow would happen:

```<code>int safe_add(int *value, int delta) {
        if (*value >= 0) {
                if (delta > INT_MAX - *value) {
                        return -1;
                }
        } else {
                if (delta < INT_MIN - *value) {
                        return -1;
                }
        }

        *value += delta;
        return 0;
}
</code>```

Unfortunately it is not optimized well by GCC or Clang:

```<code>safe_add(int*, int):
        movl    (%rdi), %eax
        testl   %eax, %eax
        js      .L2
        movl    $2147483647, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jl      .L6
.L4:
        addl    %esi, %eax
        movl    %eax, (%rdi)
        xorl    %eax, %eax
        ret
.L2:
        movl    $-2147483648, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jle     .L4
.L6:
        movl    $-1, %eax
        ret
</code>```

This version with __builtin_add_overflow()

```<code>int safe_add(int *value, int delta) {
        int result;
        if (__builtin_add_overflow(*value, delta, &result)) {
                return -1;
        } else {
                *value = result;
                return 0;
        }
}
</code>```

is optimized better:

```<code>safe_add(int*, int):
        xorl    %eax, %eax
        addl    (%rdi), %esi
        seto    %al
        jo      .L5
        movl    %esi, (%rdi)
        ret
.L5:
        movl    $-1, %eax
        ret
</code>```

but I'm curious if there's a way without using builtins that will get pattern-matched by GCC or Clang.

答:
The situation with signed operations is much worse than with unsigned ones, and I see only one pattern for signed addition, only for clang and only when a wider type is available:

int safe_add(int *value, int delta)
{
    long long result = (long long)*value + delta;

    if (result > INT_MAX || result < INT_MIN) {
        return -1;
    } else {
        *value = result;
        return 0;
    }
}
```

<p>clang gives exactly the same asm as with __builtin_add_overflow:</p>

```safe_add:                               # @safe_add
        addl    (%rdi), %esi
        movl    $-1, %eax
        jo      .LBB1_2
        movl    %esi, (%rdi)
        xorl    %eax, %eax
.LBB1_2:
        retq
```

<p>Otherwise, the simplest solution I can think of is this (with the interface as Jens used):</p>

<pre class="lang-c prettyprint-override"><code>_Bool overadd(int a[static 1], int b)
{
    // compute the unsigned sum
    unsigned u = (unsigned)a[0] + b;

    // convert it to signed
    int sum = u <= -1u / 2 ? (int)u : -1 - (int)(-1 - u);

    // see if it overflowed or not
    _Bool overflowed = (b > 0) != (sum > a[0]);

    // return the results
    a[0] = sum;
    return overflowed;
}
</code>```

gcc and clang generate very similar asm. gcc gives this:

```<code>overadd:
        movl    (%rdi), %ecx
        testl   %esi, %esi
        setg    %al
        leal    (%rcx,%rsi), %edx
        cmpl    %edx, %ecx
        movl    %edx, (%rdi)
        setl    %dl
        xorl    %edx, %eax
        ret
</code>```

We want to compute the sum in unsigned, so unsigned have to be able to represent all values of int without any of them sticking together. To easily convert the result from unsigned to int, the opposite is useful too. Overall, two's complement is assumed.

On all popular platforms I think we can convert from unsigned to int by a simple assignment like int sum = u; but, as Jens mentioned, even the latest variant of the C2x standard allows it to raise a signal. The next most natural way is to do something like that: *(unsigned *)&sum = u; but non-trap variants of padding apparently could differ for signed and unsigned types. So the example above goes the hard way. Fortunately, both gcc and clang optimize this tricky conversion away.

P.S. The two variants above could not be compared directly as they have different behavior. The first one follows the original question and doesn't clobber the *value in case of overflow. The second one follows the answer from Jens and always clobbers the variable pointed to by the first parameter but it's branchless.

Body:
Here is a C function that adds an int to another, failing if overflow would happen:

int safe_add(int *value, int delta) {
        if (*value >= 0) {
                if (delta > INT_MAX - *value) {
                        return -1;
                }
        } else {
                if (delta < INT_MIN - *value) {
                        return -1;
                }
        }

        *value += delta;
        return 0;
}

Unfortunately it is not optimized well by GCC or Clang:

safe_add(int*, int):
        movl    (%rdi), %eax
        testl   %eax, %eax
        js      .L2
        movl    $2147483647, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jl      .L6
.L4:
        addl    %esi, %eax
        movl    %eax, (%rdi)
        xorl    %eax, %eax
        ret
.L2:
        movl    $-2147483648, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jle     .L4
.L6:
        movl    $-1, %eax
        ret

This version with __builtin_add_overflow()

int safe_add(int *value, int delta) {
        int result;
        if (__builtin_add_overflow(*value, delta, &result)) {
                return -1;
        } else {
                *value = result;
                return 0;
        }
}

is optimized better:

safe_add(int*, int):
        xorl    %eax, %eax
        addl    (%rdi), %esi
        seto    %al
        jo      .L5
        movl    %esi, (%rdi)
        ret
.L5:
        movl    $-1, %eax
        ret

but I'm curious if there's a way without using builtins that will get pattern-matched by GCC or Clang.

Body:
The situation with signed operations is much worse than with unsigned ones, and I see only one pattern for signed addition, only for clang and only when a wider type is available:

int safe_add(int *value, int delta)
{
    long long result = (long long)*value + delta;

    if (result > INT_MAX || result < INT_MIN) {
        return -1;
    } else {
        *value = result;
        return 0;
    }
}

clang gives exactly the same asm as with __builtin_add_overflow:

safe_add:                               # @safe_add
        addl    (%rdi), %esi
        movl    $-1, %eax
        jo      .LBB1_2
        movl    %esi, (%rdi)
        xorl    %eax, %eax
.LBB1_2:
        retq

Otherwise, the simplest solution I can think of is this (with the interface as Jens used):

_Bool overadd(int a[static 1], int b)
{
    // compute the unsigned sum
    unsigned u = (unsigned)a[0] + b;

    // convert it to signed
    int sum = u <= -1u / 2 ? (int)u : -1 - (int)(-1 - u);

    // see if it overflowed or not
    _Bool overflowed = (b > 0) != (sum > a[0]);

    // return the results
    a[0] = sum;
    return overflowed;
}

gcc and clang generate very similar asm. gcc gives this:

overadd:
        movl    (%rdi), %ecx
        testl   %esi, %esi
        setg    %al
        leal    (%rcx,%rsi), %edx
        cmpl    %edx, %ecx
        movl    %edx, (%rdi)
        setl    %dl
        xorl    %edx, %eax
        ret

We want to compute the sum in unsigned, so unsigned have to be able to represent all values of int without any of them sticking together. To easily convert the result from unsigned to int, the opposite is useful too. Overall, two's complement is assumed.

On all popular platforms I think we can convert from unsigned to int by a simple assignment like int sum = u; but, as Jens mentioned, even the latest variant of the C2x standard allows it to raise a signal. The next most natural way is to do something like that: *(unsigned *)&sum = u; but non-trap variants of padding apparently could differ for signed and unsigned types. So the example above goes the hard way. Fortunately, both gcc and clang optimize this tricky conversion away.

P.S. The two variants above could not be compared directly as they have different behavior. The first one follows the original question and doesn't clobber the *value in case of overflow. The second one follows the answer from Jens and always clobbers the variable pointed to by the first parameter but it's branchless.


问:
How to log users off automatically after a period of inactivity?
After a lot of search in the web and find nothing, I wonder if there is an easy way to automatic logout the user logged through the Symfony Security after an inactive period. I want that the user be logged out after 30 minutes of inactivity, for example.

I use a custom User Provider like this.

But after the user login into the system, the session never expires. Even if he close the browser and open it again after some days the session is still valid.

There is anyway to logout this user by an automatic way or even a manual way?
How can I do that?

答:
A simple redirection to logout after moment using twig in your layout

First create your twig extension

```<code>#App/Twig/LogoutAfterMomentExtension.php

<?php

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class LogoutAfterMomentExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('logoutAfter', [$this, 'logoutAfter']),
        ];
    }

    public function logoutAfter(int $seconds)
    {
        return header( "refresh:".$seconds.";url=/admin/logout" );
    }

}
</code>```

call the function in the template

```<code>#templates/layout.html.twig

<body>

{{ logoutAfter(5) }} #it will logout after 5 seconds
...

</body>
</code>```

Body:
A simple redirection to logout after moment using twig in your layout

First create your twig extension

#App/Twig/LogoutAfterMomentExtension.php

<?php

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class LogoutAfterMomentExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('logoutAfter', [$this, 'logoutAfter']),
        ];
    }

    public function logoutAfter(int $seconds)
    {
        return header( "refresh:".$seconds.";url=/admin/logout" );
    }

}

call the function in the template

#templates/layout.html.twig

<body>

{{ logoutAfter(5) }} #it will logout after 5 seconds
...

</body>


问:
Angular : Datepipe is showing date as '01/01/0001' when trying to bind NULL data from Database
Do angular by default bind '01/01/0001' if we try to bind with NULL date value from database, when using DatePipe?</p>

答:
Date pipe is used to format a date value according to locale rules.

{{ date_value | date [ : format [ : timezone [ : locale ] ] ] }}

Therefore, if you set date_value to null; nothing will be displayed in your view.


问:
How to render JSON response as dropdown list in React
I'm currently trying to take some JSON data that I've received from an API and put that into a dropdown in a very simple React application.

This is my DropDown component thus far:

```<code>import React from 'react';

var values;

fetch('http://localhost:8080/values')
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        values = json;
        console.log(values);
    });

class DropDown extends React.Component {
    render(){
        return <div className="drop-down">
            <p>I would like to render a dropdown here from the values object</p>
            </div>;
    }
}

export default DropDown;
</code>```

Any my JSON looks like this:

```<code>{
   "values":[
      {
         "id":0,
         "name":"Jeff"
      },
      {
         "id":1,
         "name":"Joe"
      },
      {
         "id":2,
         "name":"John"
      },
      {
         "id":3,
         "name":"Billy"
      },
      {
         "id":4,
         "name":"Horace"
      },
      {
         "id":5,
         "name":"Greg"
      }
   ]
}
</code>```

I'd like the dropdown options to correspond to the 'name' of each element, and the 'id' to be used as an element identifier when an event is triggered by selecting an option. Any advice on getting this data into a dropdown which responds to user input would be greatly appreciated.

答:
JSON FILE: terrifcalculatordata.json
[
    {
      "id": 1,
      "name": "Vigo",
    },
    {
      "id": 2,
      "name": "Mercedes",
    },
    {
        "id": 3,
        "name": "Lexus",
      },
      {
        "id": 4,
        "name": "Buggati",
      },
]

CODE:
1st import json file on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

2nd in render method type this code:

                      <Form>
                            <FormGroup>
                              <Input
                              type="select"
                              onChange = {this.changeCarmodel}
                              value={this.state.changeCar}
                              >
                              {calculatorData.map((caldata, index) =>
                                <option
                                key={index}
                                value= {caldata.id}
                                > {caldata.name} </option>
                              )}
                              </Input>
                            </FormGroup>
                         </Form>```

Body:
I'm currently trying to take some JSON data that I've received from an API and put that into a dropdown in a very simple React application.

This is my DropDown component thus far:

import React from 'react';

var values;

fetch('http://localhost:8080/values')
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        values = json;
        console.log(values);
    });

class DropDown extends React.Component {
    render(){
        return

I would like to render a dropdown here from the values object

;
    }
}

export default DropDown;

Any my JSON looks like this:

{
   "values":[
      {
         "id":0,
         "name":"Jeff"
      },
      {
         "id":1,
         "name":"Joe"
      },
      {
         "id":2,
         "name":"John"
      },
      {
         "id":3,
         "name":"Billy"
      },
      {
         "id":4,
         "name":"Horace"
      },
      {
         "id":5,
         "name":"Greg"
      }
   ]
}

I'd like the dropdown options to correspond to the 'name' of each element, and the 'id' to be used as an element identifier when an event is triggered by selecting an option. Any advice on getting this data into a dropdown which responds to user input would be greatly appreciated.


问:
Delays acquiring worker threads in an ASP .Net Core 3.0 project
Our application is experiencing delays when acquiring worker/pool threads in an ASP .Net Core 3.0 project.

In newer language, this means effectively when spawning a Task, the amount of time between the Task.Start() command and the first line of code in the tasks executing.  Essentially the amount of time the thread pool management process takes to create the thread.

Some factors to bear in mind:

At the time of asking, there are 600+ free worker/pool threads.

The code doing this is in a .Net Framework 4.7.2 application being referenced by an ASP .Net Core 3.0 host application.

There isn't always a delay, but when there is, all items requesting worker threads from that same 4.7.2 component are subject to it.  Times vary, but I've seem 300ms.

The application is not under heavy load at the time, with memory usage and CPU utilization at normal levels.

The code requesting the worker/pool thread is doing it in a .Net 1.1 style:

```<code>    System.Threading.ThreadPool.QueueUserWorkItem(MethodName, e);
</code>```

We are issuing this command in void Main in Program.cs:

```<code>    ThreadPool.SetMinThreads(1000, 1000);
</code>```

答:
I think you use ThreadPool for what it's not supposed to be used. This is what official Silverlight docs say, which is most likely applicable to .Net Framework 4 as well:

When Not to Use Thread Pool Threads

In the following scenarios, it is appropriate to create and manage your own threads instead of using thread pool threads:

You need to start a number of threads in a very short time, to execute tasks that last a second or more. As part of its thread management strategy, the thread pool delays before creating threads. Therefore, when a number of tasks are queued in a short period of time, there can be a significant delay before all the tasks are started.

Body:
Our application is experiencing delays when acquiring worker/pool threads in an ASP .Net Core 3.0 project.

In newer language, this means effectively when spawning a Task, the amount of time between the Task.Start() command and the first line of code in the tasks executing.  Essentially the amount of time the thread pool management process takes to create the thread.

Some factors to bear in mind:

At the time of asking, there are 600+ free worker/pool threads.

The code doing this is in a .Net Framework 4.7.2 application being referenced by an ASP .Net Core 3.0 host application.

There isn't always a delay, but when there is, all items requesting worker threads from that same 4.7.2 component are subject to it.  Times vary, but I've seem 300ms.

The application is not under heavy load at the time, with memory usage and CPU utilization at normal levels.

The code requesting the worker/pool thread is doing it in a .Net 1.1 style:

    System.Threading.ThreadPool.QueueUserWorkItem(MethodName, e);

We are issuing this command in void Main in Program.cs:

    ThreadPool.SetMinThreads(1000, 1000);


问:
Running Servlets in Apache Tomcat
I'm working through the Java Ranch Cattle Drive online tutorials and got up to the Servlets projects. I wanted to install and run Apache instead of Orion, because I wanted to learn a more mainstream HTTP server.

I got Apache up and running on my machine (this is a Windows XP/Cygwin environment, so I'm using the Apache package that comes with the latest version of cygwin, currently httpd version 1.3.33)

I'm to the point of directing a browser to http://localhost and the server is correctly fetching the welcome page (index.html) at C:\cygwin\var\www\htdocs.

I've installed Java EE and was able to compile the following Servlet:

```<code>import java.io.* ;
import javax.servlet.http.* ;

public class BeeServlet extends HttpServlet
{

    public void doGet( HttpServletRequest request , HttpServletResponse response )
    {
        response.setContentType("text/html");
        try
        {
            PrintWriter out = response.getWriter();
            out.println( "a-buzz-buzz ..." );
            out.close();
        }
        catch( Exception e )
        {
            System.out.println( "cannot get writer: " + e );
        }
    }

}
</code>```

This compiles into a .class file without errors. My question is, where do I install this file in the server?

The file is called BeeServlet.class and the tutorial says to direct a browser to http://localhost/servlet/BeeServlet after installing the BeeServlet.class in the appropriate directory in the web server.

(EDIT: I've successfully installed Tomcat and have the basic welcome page showing, as explained in the steps below. I'm still not sure where to put the .class file though or how to access it):

Here's are the steps of installing Tomcat and running it through Cygwin:

Go to http://tomcat.apache.org/ and download the latest version of Tomcat (for the above system configuration, select the 32-bit/64-bit Windows Service Installer method, which will create a 9 MB installation at C:\Program Files\Apache Software Foundation\Tomcat 7.0).

Add this path to the Windows system environment variable 'Path'

Start a Cygwin bash shell

type 'tomcat7' (with Path set, it will find this .exe in the above path). This will start the tomcat server.

Start a browser and direct it to http://localhost:8080.  This will bring up the Tomcat welcome screen (which is really Tomcat reading the file: C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\index.jsp).

Create new directories under C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps named examples\WEB-INF\classes.

Add a @WebServlet annotation to the source code file (this would be located after any imports): @WebServlet(urlPatterns={"/servlet/BeeServlet"}).  Compile the BeeServlet.java file and place the .class file in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\examples\WEB-INF\classes\BeeServlet.class

Direct your browser to http://localhost:8080/examples/servlet/BeeServlet

答:
You need to let the servletcontainer know that you've a servlet which it has to execute. Since you're already on Tomcat 7.0, a @WebServlet annotation should suffice.

```<code>@WebServlet(urlPatterns={"/servlet/BeeServlet"})
public class BeeServlet extends HttpServlet {
    // ...
}
</code>```

Or the old way (probably as the JavaRanch tutorial should have mentioned), by a declaration in web.xml.

```<code><servlet>
    <servlet-name>beeServlet</servlet-name>
    <servlet-class>BeeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>beeServlet</servlet-name>
    <url-pattern>/servlet/BeeServlet</url-pattern>
</servlet-mapping>
</code>```

Please note that putting classes in a default package is a bad practice. You should be placing classes in a package if you want them to be visible to classes inside a package. The servletcontainer, written in pure Java, needs to be able to see them as well. Now, Tomcat has hacks for this, but this works in specific versions/configurations only. Always, always put servlet classes in a package.

See also:

Our servlets wiki page

Unrelated to the concrete problem:

I've installed Java EE

Please note that the Java EE download from Oracle.com contains basically the Glassfish application server along with some documentation. You don't need it when all you want is just running servlets on Tomcat.

See also:

Java SE or Java EE (standard or enterprise)?

Title: Running Servlets in Apache Tomcat

Body:
I'm working through the Java Ranch Cattle Drive online tutorials and got up to the Servlets projects. I wanted to install and run Apache instead of Orion, because I wanted to learn a more mainstream HTTP server.

I got Apache up and running on my machine (this is a Windows XP/Cygwin environment, so I'm using the Apache package that comes with the latest version of cygwin, currently httpd version 1.3.33)

I'm to the point of directing a browser to http://localhost and the server is correctly fetching the welcome page (index.html) at C:\cygwin\var\www\htdocs.

I've installed Java EE and was able to compile the following Servlet:

import java.io.* ;
import javax.servlet.http.* ;

public class BeeServlet extends HttpServlet
{

    public void doGet( HttpServletRequest request , HttpServletResponse response )
    {
        response.setContentType("text/html");
        try
        {
            PrintWriter out = response.getWriter();
            out.println( "a-buzz-buzz ..." );
            out.close();
        }
        catch( Exception e )
        {
            System.out.println( "cannot get writer: " + e );
        }
    }

}

This compiles into a .class file without errors. My question is, where do I install this file in the server?

The file is called BeeServlet.class and the tutorial says to direct a browser to http://localhost/servlet/BeeServlet after installing the BeeServlet.class in the appropriate directory in the web server.

(EDIT: I've successfully installed Tomcat and have the basic welcome page showing, as explained in the steps below. I'm still not sure where to put the .class file though or how to access it):

Here's are the steps of installing Tomcat and running it through Cygwin:

Go to http://tomcat.apache.org/ and download the latest version of Tomcat (for the above system configuration, select the 32-bit/64-bit Windows Service Installer method, which will create a 9 MB installation at C:\Program Files\Apache Software Foundation\Tomcat 7.0).

Add this path to the Windows system environment variable 'Path'

Start a Cygwin bash shell

type 'tomcat7' (with Path set, it will find this .exe in the above path). This will start the tomcat server.

Start a browser and direct it to http://localhost:8080.  This will bring up the Tomcat welcome screen (which is really Tomcat reading the file: C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\index.jsp).

Create new directories under C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps named examples\WEB-INF\classes.

Add a @WebServlet annotation to the source code file (this would be located after any imports): @WebServlet(urlPatterns={"/servlet/BeeServlet"}).  Compile the BeeServlet.java file and place the .class file in C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\examples\WEB-INF\classes\BeeServlet.class

Direct your browser to http://localhost:8080/examples/servlet/BeeServlet

Body:
You need to let the servletcontainer know that you've a servlet which it has to execute. Since you're already on Tomcat 7.0, a @WebServlet annotation should suffice.

@WebServlet(urlPatterns={"/servlet/BeeServlet"})
public class BeeServlet extends HttpServlet {
    // ...
}

Or the old way (probably as the JavaRanch tutorial should have mentioned), by a declaration in web.xml.

<servlet>
    <servlet-name>beeServlet</servlet-name>
    <servlet-class>BeeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>beeServlet</servlet-name>
    <url-pattern>/servlet/BeeServlet</url-pattern>
</servlet-mapping>

Please note that putting classes in a default package is a bad practice. You should be placing classes in a package if you want them to be visible to classes inside a package. The servletcontainer, written in pure Java, needs to be able to see them as well. Now, Tomcat has hacks for this, but this works in specific versions/configurations only. Always, always put servlet classes in a package.

See also:

Our servlets wiki page

Unrelated to the concrete problem:

I've installed Java EE

Please note that the Java EE download from Oracle.com contains basically the Glassfish application server along with some documentation. You don't need it when all you want is just running servlets on Tomcat.

See also:

Java SE or Java EE (standard or enterprise)?