问:
How do you use a Google MapView inside of a Fragment?

Desired Behavior

In case it affects any answers or suggestions, what I would like to ultimately see in this app is a navigation UI where one of the Fragment is a map.  I used a template to start with a navigation UI, which gave me several Fragments, one for each tab.  Currently, I'm trying to use the Google API to put a MapView inside of one of those Fragments.

Current Behavior

Generally, this isn't working (obviously).  I have everything up and running, but when I pull up the tab with the map in it, the map is blank.  Nothing crashes, and no errors are output:

```<code>I/Google Maps Android API: Google Play services client version: 12451000
I/Google Maps Android API: Google Play services package version: 201516040
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
    Selected remote version of com.google.android.gms.googlecertificates, version >= 4
</code>```

Other Details/Troubleshooting

I know that my API key works because I have another app in which the maps work as expected.  I doubt I need a second API key, but I looked anyway and since it wasn't overly obvious how to create a second API key, I think that hunch is correct.  Most of the code I'm using was copied from that working example; the primary difference is that other example uses a SupportMapFragment and it has a class MapsActivity extends FragmentActivity.  Here, since I don't really want to deal with nesting fragments, I'm trying to use a MapView inside that fragment.

What bits of my code that weren't copied largely came from online sources.  None of what I've tried has produced better results.

MapView inside fragment is answering a different problem

Creating google maps v2 in a fragment using Navigation Drawer contains only things I already have

android MapView in Fragment gave me the idea to use MapsInitializer.initialize(this.getActivity()); but that didn't help

Mapview in separate fragment android has nothing new

how do i solve integrating google map in fragment in android uses a Fragment not a MapView

I also know that onMapReady is being called.  Inside of that, I move the camera and that subsequently calls onCameraMoveStarted.  However, it does not enter onCameraMove or onCameraIdle.

Code

This is the code as it is, which uses some of the ideas from the above links.  I tried to cut out anything that's unrelated (other fragments, etc)

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.retailtherapy">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateVisible|adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    </application>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

</manifest>
</code>```

activity_main.xml

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        tools:context=".MainActivity" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

mobile_navigation.xml

```<code><navigation 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:id="@+id/mobile_navigation"
    app:startDestination="@+id/navigation_map">

    <fragment
        android:id="@+id/navigation_map"
        android:name="com.example.retailtherapy.ui.map.MapFragment"
        android:label="Map"
        tools:layout="@layout/fragment_map" />

</navigation>
</code>```

fragment_map.xml

```<code>
<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=".ui.map.MapFragment" >

    <com.google.android.gms.maps.MapView
        android:id="@+id/googleMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

MapFragment.java

```<code>public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener {

    /*************************************************************************
     *
     * M E M B E R S
     *
     */

    // Location manager for getting current location
    private LocationManager mLocationManager = null;

    // The map object for reference for ease of adding points and such
    private GoogleMap mGoogleMap = null;
    private MapView mMapView = null;

    // The camera position tells us where the view is on the map
    private CameraPosition mCameraPosition = Constants.GetDefaultCameraPosition();

    // Current latitude and longitude of user
    private LatLng mCurrentLatLong = new LatLng(0.0, 0.0);

    // These are flags that allow us to selectively not move the camera and
    // instead wait for idle so the movement isn't jerky
    private boolean mCameraMoving = false;
    private boolean mPendingUpdate = false;

    /*************************************************************************
     *
     * F R A G M E N T
     *
     */

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_map, container, false);

        // The google map...
        MapsInitializer.initialize(getActivity());
        mMapView = (MapView) root.findViewById(R.id.googleMap);
        mMapView.onCreate(savedInstanceState);
        mMapView.getMapAsync(this);

        // The required permissions...
        final String[] REQUIRED_PERMISSIONS = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.INTERNET,
        };
        requestPermissions(REQUIRED_PERMISSIONS, 0);

        return root;
    }

    @Override
    public void onStart() throws SecurityException {
        super.onStart();

        // Location manager for getting info current location
        mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    /*************************************************************************
     *
     * G O O G L E   M A P S
     *
     */

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        // Assuming if here that we have permissions okay.  Dangerous sure
        // but I'm lazy...
        mGoogleMap.setMyLocationEnabled(true);

        // Store the location of the camera for UI purposes so we can go
        // back to where we were
        mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
            @Override
            public void onCameraMove() {
                mCameraPosition = mGoogleMap.getCameraPosition();
            }
        });
        mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
            @Override
            public void onCameraMoveStarted(int i) {
                mCameraMoving = true;
            }
        });
        mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                mCameraMoving = false;
                if (mPendingUpdate) {
                    centerCameraOnLocation(false);
                }
            }
        });

        // Start with user centered in view
        centerCameraOnLocation(true);
    }

    /*************************************************************************
     *
     * L O C A T I O N
     *
     */

    @Override
    public void onLocationChanged(Location location) {
        // Store the current location so if we start auto-center but aren't
        // already, we know where to pan to
        LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        if (!newLatLng.equals(mCurrentLatLong)) {
            mCurrentLatLong = new LatLng(location.getLatitude(), location.getLongitude());
            centerCameraOnLocation(false);
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    /*************************************************************************
     *
     * M A P   C A M E R A
     *
     */

    /*
     * Updates the camera position based on current state.  If the camera is
     * already moving, then wait.
     */
    private void centerCameraOnLocation(boolean animate) {
        if (mGoogleMap == null) {
            return;
        }

        if (mCameraMoving) {
            mPendingUpdate = true;
            return;
        }

        // Get the CameraPosition to update to based on whether we are auto
        // centering or not.
        if (mCameraPosition == null) {
            mCameraPosition = Constants.GetDefaultCameraPosition();
        }

        // If this is the same as it was before, then don't reset it
        if (mCameraPosition.equals(mGoogleMap.getCameraPosition())) {
            return;
        }

        // Make the update so we can move the camera
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(mCameraPosition);

        // Move the camera with or without animation.  The time we don't want
        // animation is when we're setting the position initially
        if (animate) {
            mGoogleMap.animateCamera(cameraUpdate);
        }
        else {
            mGoogleMap.moveCamera(cameraUpdate);
        }
        mPendingUpdate = false;
    }
}
</code>```

答:
FINALLY I found the answer in a comment at https://stackoverflow.com/a/51464293/3038157.

Basically, it seems there was something stale.  Without changing any code, I uninstalled the app, cleaned the build, rebuilt, and voila it worked.

Body:
Desired Behavior

In case it affects any answers or suggestions, what I would like to ultimately see in this app is a navigation UI where one of the Fragment is a map.  I used a template to start with a navigation UI, which gave me several Fragments, one for each tab.  Currently, I'm trying to use the Google API to put a MapView inside of one of those Fragments.

Current Behavior

Generally, this isn't working (obviously).  I have everything up and running, but when I pull up the tab with the map in it, the map is blank.  Nothing crashes, and no errors are output:

I/Google Maps Android API: Google Play services client version: 12451000
I/Google Maps Android API: Google Play services package version: 201516040
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
    Selected remote version of com.google.android.gms.googlecertificates, version >= 4

Other Details/Troubleshooting

I know that my API key works because I have another app in which the maps work as expected.  I doubt I need a second API key, but I looked anyway and since it wasn't overly obvious how to create a second API key, I think that hunch is correct.  Most of the code I'm using was copied from that working example; the primary difference is that other example uses a SupportMapFragment and it has a class MapsActivity extends FragmentActivity.  Here, since I don't really want to deal with nesting fragments, I'm trying to use a MapView inside that fragment.

What bits of my code that weren't copied largely came from online sources.  None of what I've tried has produced better results.

MapView inside fragment is answering a different problem

Creating google maps v2 in a fragment using Navigation Drawer contains only things I already have

android MapView in Fragment gave me the idea to use MapsInitializer.initialize(this.getActivity()); but that didn't help

Mapview in separate fragment android has nothing new

how do i solve integrating google map in fragment in android uses a Fragment not a MapView

I also know that onMapReady is being called.  Inside of that, I move the camera and that subsequently calls onCameraMoveStarted.  However, it does not enter onCameraMove or onCameraIdle.

Code

This is the code as it is, which uses some of the ideas from the above links.  I tried to cut out anything that's unrelated (other fragments, etc)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.retailtherapy">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateVisible|adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    </application>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

</manifest>

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        tools:context=".MainActivity" />

</androidx.constraintlayout.widget.ConstraintLayout>

mobile_navigation.xml

<navigation 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:id="@+id/mobile_navigation"
    app:startDestination="@+id/navigation_map">

    <fragment
        android:id="@+id/navigation_map"
        android:name="com.example.retailtherapy.ui.map.MapFragment"
        android:label="Map"
        tools:layout="@layout/fragment_map" />

</navigation>

fragment_map.xml

<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=".ui.map.MapFragment" >

    <com.google.android.gms.maps.MapView
        android:id="@+id/googleMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

MapFragment.java

public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener {

    /*************************************************************************
     *
     * M E M B E R S
     *
     */

    // Location manager for getting current location
    private LocationManager mLocationManager = null;

    // The map object for reference for ease of adding points and such
    private GoogleMap mGoogleMap = null;
    private MapView mMapView = null;

    // The camera position tells us where the view is on the map
    private CameraPosition mCameraPosition = Constants.GetDefaultCameraPosition();

    // Current latitude and longitude of user
    private LatLng mCurrentLatLong = new LatLng(0.0, 0.0);

    // These are flags that allow us to selectively not move the camera and
    // instead wait for idle so the movement isn't jerky
    private boolean mCameraMoving = false;
    private boolean mPendingUpdate = false;

    /*************************************************************************
     *
     * F R A G M E N T
     *
     */

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_map, container, false);

        // The google map...
        MapsInitializer.initialize(getActivity());
        mMapView = (MapView) root.findViewById(R.id.googleMap);
        mMapView.onCreate(savedInstanceState);
        mMapView.getMapAsync(this);

        // The required permissions...
        final String[] REQUIRED_PERMISSIONS = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.INTERNET,
        };
        requestPermissions(REQUIRED_PERMISSIONS, 0);

        return root;
    }

    @Override
    public void onStart() throws SecurityException {
        super.onStart();

        // Location manager for getting info current location
        mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    /*************************************************************************
     *
     * G O O G L E   M A P S
     *
     */

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        // Assuming if here that we have permissions okay.  Dangerous sure
        // but I'm lazy...
        mGoogleMap.setMyLocationEnabled(true);

        // Store the location of the camera for UI purposes so we can go
        // back to where we were
        mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
            @Override
            public void onCameraMove() {
                mCameraPosition = mGoogleMap.getCameraPosition();
            }
        });
        mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
            @Override
            public void onCameraMoveStarted(int i) {
                mCameraMoving = true;
            }
        });
        mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                mCameraMoving = false;
                if (mPendingUpdate) {
                    centerCameraOnLocation(false);
                }
            }
        });

        // Start with user centered in view
        centerCameraOnLocation(true);
    }

    /*************************************************************************
     *
     * L O C A T I O N
     *
     */

    @Override
    public void onLocationChanged(Location location) {
        // Store the current location so if we start auto-center but aren't
        // already, we know where to pan to
        LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        if (!newLatLng.equals(mCurrentLatLong)) {
            mCurrentLatLong = new LatLng(location.getLatitude(), location.getLongitude());
            centerCameraOnLocation(false);
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    /*************************************************************************
     *
     * M A P   C A M E R A
     *
     */

    /*
     * Updates the camera position based on current state.  If the camera is
     * already moving, then wait.
     */
    private void centerCameraOnLocation(boolean animate) {
        if (mGoogleMap == null) {
            return;
        }

        if (mCameraMoving) {
            mPendingUpdate = true;
            return;
        }

        // Get the CameraPosition to update to based on whether we are auto
        // centering or not.
        if (mCameraPosition == null) {
            mCameraPosition = Constants.GetDefaultCameraPosition();
        }

        // If this is the same as it was before, then don't reset it
        if (mCameraPosition.equals(mGoogleMap.getCameraPosition())) {
            return;
        }

        // Make the update so we can move the camera
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(mCameraPosition);

        // Move the camera with or without animation.  The time we don't want
        // animation is when we're setting the position initially
        if (animate) {
            mGoogleMap.animateCamera(cameraUpdate);
        }
        else {
            mGoogleMap.moveCamera(cameraUpdate);
        }
        mPendingUpdate = false;
    }
}


来源: stackexchange

问:
Calling angular function from dynamically added hyperlink which is added asyncronously
While ngOnInit i call function which asyncronously gets me variable.
after that I want to create some hyperlinks on components template page using that variable data.
And that hyperlinks must call some function on click.
That part is not working because of

```<code>Angular doesn't understand the events of dynamically added elements
</code>```

Calling angular function from dynamically added hyperlink

But that solution will not help me because ngAfterViewInit() do not get my variable which is made asyncronous.

So how can I do the followoing...

```<code>ngOnInit() {

this.somefunction gets me variable .subscribe(
this.testVar='testData';
And here I construct some hyperlinks using this variable
<a [routerLink]="[]" class="image-fav" (click)="someFunc()">this.testVar</a>
}

someFunc() {
doing something....
}
</code>```

答:
You could adapt the previous answer to your scenario. The ngAfterViewInit from the other answer hook was a general use-case scenario. In your case, you could add the element to the DOM, trigger change detection (eg. using detectChanges()) and add the event listener all in the ngOnInit hook.

import { Component, ChangeDetectorRef, ElementRef, OnInit } from '@angular/core';

export class AppComponent implements OnInit {
  constructor(private changeDetectorRef: ChangeDetectorRef, private elementRef: ElementRef) { }

  ngOnInit() {
    this.someService.someFunction().subscribe(
      response => {
        this.testVar = 'testData';
        // construct dynamic element `this.testVar`
        this.changeDetectorRef.detectChanges();
        this.elementRef.nativeElement.querySelector('.image-fav').addEventListener(
          'click', this.someFunc.bind(this)
        );
      },
      err => {
        // handle error
      }
    );
}
```

ContentLicense: CC BY-SA 4.0

Body:
While ngOnInit i call function which asyncronously gets me variable.
after that I want to create some hyperlinks on components template page using that variable data.
And that hyperlinks must call some function on click.
That part is not working because of

Angular doesn't understand the events of dynamically added elements

Calling angular function from dynamically added hyperlink

But that solution will not help me because ngAfterViewInit() do not get my variable which is made asyncronous.

So how can I do the followoing...

ngOnInit() {

this.somefunction gets me variable .subscribe(
this.testVar='testData';
And here I construct some hyperlinks using this variable
this.testVar
}

someFunc() {
doing something....
}

Body:
You could adapt the previous answer to your scenario. The ngAfterViewInit from the other answer hook was a general use-case scenario. In your case, you could add the element to the DOM, trigger change detection (eg. using detectChanges()) and add the event listener all in the ngOnInit hook.

import { Component, ChangeDetectorRef, ElementRef, OnInit } from '@angular/core';

export class AppComponent implements OnInit {
  constructor(private changeDetectorRef: ChangeDetectorRef, private elementRef: ElementRef) { }

  ngOnInit() {
    this.someService.someFunction().subscribe(
      response => {
        this.testVar = 'testData';
        // construct dynamic element `<a [routerLink]="[]" class="image-fav" (click)="someFunc()">this.testVar</a>`
        this.changeDetectorRef.detectChanges();
        this.elementRef.nativeElement.querySelector('.image-fav').addEventListener(
          'click', this.someFunc.bind(this)
        );
      },
      err => {
        // handle error
      }
    );
}


问:
SQL PHP query multiple tables data
Noob alert here!
I'm trying to display some data on my php page from two tables but I don't know how to do it

```<code>db_bandas TABLE
banda_id | banda_name
    1    |  Rolling Beatles
    2    |  Linkin Bizkit

db_albuns TABLE
album_id | album_name | banda_id | album_ano
    1    |    Music   |    1     |  2000
    2    |   another  |    2     |  2014
    3    |  good one  |    1     |  2004
</code>```

What I want to show on the page is like :

```<code> 1  | Music    | Rolling Beatles | 2000
 2  | another  | Linkin Bizkit   | 2014
 3  | good one | Rolling Beatles | 2004
</code>```

I've tried the query like this

```<code>$sql = "SELECT db_albuns.album_nome AS album_nome, db_albuns.album_id AS album_id, db_albuns.album_ano AS album.ano, db_banda.banda_nome AS banda_nome FROM db_albuns,db_banda";

</code>```

答:
There are a few different ways you can do this, but my go-to is a LEFT JOIN.

```<code>$sql = "SELECT album_id, album_name, banda_name, album_ano
        FROM albuns LEFT JOIN bandas
        USING (banda_id)
        WHERE 1=1;
</code>```

On a side not, prefixing your tables with db_ is a little confusing, because that's the name of a table, not a database.

Title: SQL PHP query multiple tables data

Body:
Noob alert here!
I'm trying to display some data on my php page from two tables but I don't know how to do it

db_bandas TABLE
banda_id | banda_name
    1    |  Rolling Beatles
    2    |  Linkin Bizkit

db_albuns TABLE
album_id | album_name | banda_id | album_ano
    1    |    Music   |    1     |  2000
    2    |   another  |    2     |  2014
    3    |  good one  |    1     |  2004

What I want to show on the page is like :

 1  | Music    | Rolling Beatles | 2000
 2  | another  | Linkin Bizkit   | 2014
 3  | good one | Rolling Beatles | 2004

I've tried the query like this

$sql = "SELECT db_albuns.album_nome AS album_nome, db_albuns.album_id AS album_id, db_albuns.album_ano AS album.ano, db_banda.banda_nome AS banda_nome FROM db_albuns,db_banda";

Body:
There are a few different ways you can do this, but my go-to is a LEFT JOIN.

$sql = "SELECT album_id, album_name, banda_name, album_ano
        FROM albuns LEFT JOIN bandas
        USING (banda_id)
        WHERE 1=1;

On a side not, prefixing your tables with db_ is a little confusing, because that's the name of a table, not a database.


问:
Django application on EC2 and RDS ( Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?)
I have created an EC2 instance on AWS and deployed my django application on it.

Also created RDS postgres database on AWS. Whenever I access my public ip, I get the following error,

OperationalError at /

could not connect to server: Connection refused   Is the server running
  on host "localhost" (127.0.0.1) and accepting     TCP/IP connections on
  port 5432?

Both EC2 and RDS instances are connected. Verified by following,

Connected RDS postgres using pgadmin4 on my local PC.

Created supersuser on ec2 console and it populated the postgres.

Nginx configuration:

```<code>server {
  listen 80;
  server_name 18.218.45.241;
  location = /favicon.ico { access_log off; log_not_found off; }
  location /static/ {
      root /home/ubuntu/Crowdsocial_project;
  }
  location / {
      include proxy_params;
      proxy_pass http://unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock;
  }
}
</code>```

Gunicorn configuration:

```<code>[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/Crowdsocial_project
ExecStart=/home/ubuntu/Crowdsocial_project/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock main.wsgi:application
[Install]
WantedBy=multi-user.target
</code>```

EC2 Security group:

RDS Security group:

Settings.py

```<code># Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['18.218.45.241']

DATE_INPUT_FORMATS= ['%Y-%m-%d',]

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@gmail.com'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_PORT = 587

# Application definition

INSTALLED_APPS = [
    'users.apps.UsersConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap_modal_forms',

    'main',
    'first_app',
    'campaign',
    'invoice',
    'taggit',
    'corsheaders',
    'taggit_selectize',
    'rest_framework',
    'django_filters',
    'django_extensions',
    'shop',
    'search',
    'cart',
    'orders',
    'widget_tweaks',
    'billing',
]

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']

CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 'main.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.media',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'main.wsgi.application'
AUTH_USER_MODEL = 'users.CustomUser'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'name',
        'USER': 'user',
        'PASSWORD': 'pass',
        'HOST': 'crowdsocial-postgres.c9sefqws77mc.us-east-2.rds.amazonaws.com',
        'PORT': '5432',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

LOGIN_URL = 'users:login'
# LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'first_app:home'
</code>```

答:
Answer
I Was facing the same problem. I reboot EC2 Machine and it works for me.
Try it maybe it will work for you.

Body:
I have created an EC2 instance on AWS and deployed my django application on it.

Also created RDS postgres database on AWS. Whenever I access my public ip, I get the following error,

OperationalError at /

could not connect to server: Connection refused   Is the server running
  on host "localhost" (127.0.0.1) and accepting     TCP/IP connections on
  port 5432?

Both EC2 and RDS instances are connected. Verified by following,

Connected RDS postgres using pgadmin4 on my local PC.

Created supersuser on ec2 console and it populated the postgres.

Nginx configuration:

server {
  listen 80;
  server_name 18.218.45.241;
  location = /favicon.ico { access_log off; log_not_found off; }
  location /static/ {
      root /home/ubuntu/Crowdsocial_project;
  }
  location / {
      include proxy_params;
      proxy_pass http://unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock;
  }
}

Gunicorn configuration:

[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/Crowdsocial_project
ExecStart=/home/ubuntu/Crowdsocial_project/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/Crowdsocial_project/crowdsocial.sock main.wsgi:application
[Install]
WantedBy=multi-user.target

EC2 Security group:

RDS Security group:

Settings.py

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['18.218.45.241']

DATE_INPUT_FORMATS= ['%Y-%m-%d',]

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@gmail.com'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_PORT = 587

# Application definition

INSTALLED_APPS = [
    'users.apps.UsersConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap_modal_forms',

    'main',
    'first_app',
    'campaign',
    'invoice',
    'taggit',
    'corsheaders',
    'taggit_selectize',
    'rest_framework',
    'django_filters',
    'django_extensions',
    'shop',
    'search',
    'cart',
    'orders',
    'widget_tweaks',
    'billing',
]

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']

CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 'main.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.media',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'main.wsgi.application'
AUTH_USER_MODEL = 'users.CustomUser'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'name',
        'USER': 'user',
        'PASSWORD': 'pass',
        'HOST': 'crowdsocial-postgres.c9sefqws77mc.us-east-2.rds.amazonaws.com',
        'PORT': '5432',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

LOGIN_URL = 'users:login'
# LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'first_app:home'


问:
click, getElementByClassName etc with for() not working
I am a Javascript beginner and am trying to solve a problem here. I don't find the mistake.

I try that the ID and the class variants work. The click and the message does not work.

java script

let click = document.querySelectorAll('.trigger');

let messageAllClass = document.querySelectorAll('.messageAllClass');
let messageClass = document.getElementByClassName('messageClass');
let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";
let i;
let cls = clicks.length;

//messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
//messageClass.innerHTML = messageClass.textContent + messageTxtClass;
messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;

for(let i = 0; i < messageAllClass.length; i++) {
    messageAllClass[i].innerHTML = document.querySelectorAll('.messageAllClass');
}

for(let i = 0; i < messageClass.length; i++) {
    messageClass[i].innerHTML = document.getElementByClassName('messageClass');
}

for (let i = 0; i < cls; i++) {
  click[i].onclick = function () {
    messageAllClass.innerHTML = "null";
    messageClass.innerHTML = "null";
    messeageIDuniq.innerHTML = deleted;
    alert("all messages deleted!");
  }
}
```

<p><strong>html</strong></p>

<pre class="lang-html prettyprint-override"><code><h1>On one side</h1>

<div class="main">
  <h3>Message:</h3>
  <div class="messageAllClass"></div>
  <div class="messageClass"></div>
  <div id="messageID"></div>
</div>

<div class="panel">
  <h3>Panel:</h3>
  <div class="messageAllClass"></div>
  <div class="messageClass"></div>
</div>

<button type="button" class="trigger">Delete all messages</button>

</code>```

saved on jsfiddle

答:
You make some mistakes, as you can see in comment. So I try fixed and some refactoring your code.

```<code>let clicks = Array.from(document.querySelectorAll('.trigger'));

let messageAllClass = Array.from(document.querySelectorAll('.messageAllClass'));
let messageClass = Array.from(document.getElementsByClassName('messageClass'));
let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";

messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;
messageAllClass.forEach(i=>i.innerHTML = messageTxtAllClass)
messageClass.forEach(i=>i.innerHTML = messageTxtClass)

const onDelete = function() {
  messageAllClass.forEach(i=>i.innerHTML = deleted)
  messageClass.forEach(i=>i.innerHTML = deleted)
  messeageIDuniq.innerHTML = deleted;
  alert("all messages deleted!");
}

clicks.forEach(b=>b.onclick = onDelete)
</code>```

See in playground, I hope this helps you: https://jsfiddle.net/denisstukalov/f6mrx10c/10/#&togetherjs=dBkaxLHuzC

Body:
I am a Javascript beginner and am trying to solve a problem here. I don't find the mistake.

I try that the ID and the class variants work. The click and the message does not work.

java script

let click = document.querySelectorAll('.trigger');

let messageAllClass = document.querySelectorAll('.messageAllClass');
let messageClass = document.getElementByClassName('messageClass');
let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";
let i;
let cls = clicks.length;

//messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
//messageClass.innerHTML = messageClass.textContent + messageTxtClass;
messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;

for(let i = 0; i < messageAllClass.length; i++) {
    messageAllClass[i].innerHTML = document.querySelectorAll('.messageAllClass');
}

for(let i = 0; i < messageClass.length; i++) {
    messageClass[i].innerHTML = document.getElementByClassName('messageClass');
}

for (let i = 0; i < cls; i++) {
  click[i].onclick = function () {
    messageAllClass.innerHTML = "null";
    messageClass.innerHTML = "null";
    messeageIDuniq.innerHTML = deleted;
    alert("all messages deleted!");
  }
}

html

On one side

Message:

Panel:

<button type="button" class="trigger">Delete all messages</button>

saved on jsfiddle

Body:
You make some mistakes, as you can see in comment. So I try fixed and some refactoring your code.

let clicks = Array.from(document.querySelectorAll('.trigger'));

let messageAllClass = Array.from(document.querySelectorAll('.messageAllClass'));
let messageClass = Array.from(document.getElementsByClassName('messageClass'));
let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";

messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;
messageAllClass.forEach(i=>i.innerHTML = messageTxtAllClass)
messageClass.forEach(i=>i.innerHTML = messageTxtClass)

const onDelete = function() {
  messageAllClass.forEach(i=>i.innerHTML = deleted)
  messageClass.forEach(i=>i.innerHTML = deleted)
  messeageIDuniq.innerHTML = deleted;
  alert("all messages deleted!");
}

clicks.forEach(b=>b.onclick = onDelete)

See in playground, I hope this helps you: https://jsfiddle.net/denisstukalov/f6mrx10c/10/#&togetherjs=dBkaxLHuzC


问:
Decoding Korean text files from the 90s
I have a collection of .html files created in the mid-90s, which include a significant ammount of Korean text. The HTML lacks character set metadata, so of course all of the Korean text now does not render properly. The following examples will all make use of the same excerpt of text .

In text editors such as Coda and Text Wrangler the text displays as

╙╦  ╝№бя└К ▓щ╥НВь╕цль▒Ф ▓щ╥НВь╕цль▒Ф

Which in the absence of character set metadata in  is rendered by the browser as:

ÓË ¼ü¡ïÀŠ ²éÒ‚ì¸æ«ì±” ²éÒ‚ì¸æ«ì±”

Adding euc-kr metadata to

```<code><meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
</code>```

Yields the following, which is illegible nonsense (verified by a native speaker):

沓 숩∽핅 꿴�귥멩レ콛 꿴�귥멩レ콛

I have tried this approach with all historic Korean character sets, each yielding similarly unsuccessful results. I also tried parsing and upgrading to UTF-8, via Beautiful Soup, which also failed.

Viewing the files in Emacs seems promising, as it reveals the text encoding a lower level. The following is the same sample of text:

\323\313  \274\374\241\357\300\212
  \262\351\322\215\202\354\270\346\253\354\261\224 \262\3\
  51\322\215\202\354\270\346\253\354\261\224

How can I identify this text encoding and promote it to UTF-8?

答:
Even if this thread is old, it's still an issue, and not having found a way to convert the files in bulk (outside of using a Korean version of Windows7), now I'm using Naver, which has a cloud service like Google docs and if you upload those weirdly encoded files there, it deals with them very well. I just edit and copy the text, and it's back to being standard when I copy it elsewhere.
Not the kind of solution I like, but it might save a few passers-by.
You can register for the cloud account with an ID, even if you do not live in SKorea by the way, there's some minimal english to get by. </p>

ContentLicense: CC BY-SA 3.0

Title: Decoding Korean text files from the 90s

Body:
I have a collection of .html files created in the mid-90s, which include a significant ammount of Korean text. The HTML lacks character set metadata, so of course all of the Korean text now does not render properly. The following examples will all make use of the same excerpt of text .

In text editors such as Coda and Text Wrangler the text displays as

╙╦  ╝№бя└К ▓щ╥НВь╕цль▒Ф ▓щ╥НВь╕цль▒Ф

Which in the absence of character set metadata in  is rendered by the browser as:

ÓË ¼ü¡ïÀŠ ²éÒ‚ì¸æ«ì±” ²éÒ‚ì¸æ«ì±”

Adding euc-kr metadata to

<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">

Yields the following, which is illegible nonsense (verified by a native speaker):

沓 숩∽핅 꿴�귥멩レ콛 꿴�귥멩レ콛

I have tried this approach with all historic Korean character sets, each yielding similarly unsuccessful results. I also tried parsing and upgrading to UTF-8, via Beautiful Soup, which also failed.

Viewing the files in Emacs seems promising, as it reveals the text encoding a lower level. The following is the same sample of text:

\323\313  \274\374\241\357\300\212
  \262\351\322\215\202\354\270\346\253\354\261\224 \262\3\
  51\322\215\202\354\270\346\253\354\261\224

How can I identify this text encoding and promote it to UTF-8?


问:
Exclude invisible Inputs with parsley.js 2.x
How do I tell the parsley-Instance to exclude not visible form elements?

I found this in the Documentation:

data-parsley-excluded="input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden"

But I dont now where to set this Option? How can I parse this option to the Constructor?

Further Info: I am binding parsley to my form with jQuery("#formid").parsley();

Thanks a lot.
Greets

答:
To disable globally, I added this to the same js page where I set up custom validators, ie:</p>

```<code>  window.Parsley.options.excluded = "input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden" ;

  window.Parsley.addValidator('noemoji', {
    requirementType: 'boolean',
    ...
</code>```

Body:
To disable globally, I added this to the same js page where I set up custom validators, ie:

  window.Parsley.options.excluded = "input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden" ;

  window.Parsley.addValidator('noemoji', {
    requirementType: 'boolean',
    ...


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

I want this string:

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

tp be parsed into:

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

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

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

答:
I developed a parser for your example. I also checked some other examples which you can see in the code.</p>

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

public class Program
{
    public static void Main()
    {
        string str = "(example (to (parsing nested paren) but) (first lvl only))"; // => [example  , (to (parsing nested paren) but) ,  (first lvl only)]
        //string str = "(first)(second)(third)"; // => [first , second , third]
        //string str = "(first(second)third)"; // => [first , (second) , third]
        //string str = "(first(second)(third)fourth)"; // => [first , (second) , (third) ,  fourth]
        //string str = "(first((second)(third))fourth)"; // => [first , ((second)(third)) , fourth]

        //string str = "just Text"; // => [ERROR]
        //string str = "start with Text (first , second)"; // => [ERROR]
        //string str = "(first , second) end with text"; // => [ERROR]
        //string str = ""; // => [ERROR]
        //string str = "("; // => [ERROR]
        //string str = "(first()(second)(third))fourth)"; // => [ERROR]
        //string str = "(((extra close pareanthese))))"; // => [ERROR]
        var res = Parser.parse(str);
        showRes(res);
    }

    static void showRes(ArrayList res)
    {
        var strings = res.ToArray();
        var theString = string.Join(" , ", strings);
        Console.WriteLine("[" + theString + "]");
    }
}

public class Parser
{
    static Dictionary<TokenType, TokenType> getRules()
    {
        var rules = new Dictionary<TokenType, TokenType>();
        rules.Add(TokenType.OPEN_PARENTHESE, TokenType.START | TokenType.OPEN_PARENTHESE | TokenType.CLOSE_PARENTHESE | TokenType.SIMPLE_TEXT);
        rules.Add(TokenType.CLOSE_PARENTHESE, TokenType.SIMPLE_TEXT | TokenType.CLOSE_PARENTHESE);
        rules.Add(TokenType.SIMPLE_TEXT, TokenType.SIMPLE_TEXT | TokenType.CLOSE_PARENTHESE | TokenType.OPEN_PARENTHESE);
        rules.Add(TokenType.END, TokenType.CLOSE_PARENTHESE);
        return rules;
    }

    static bool isValid(Token prev, Token cur)
    {
        var rules = Parser.getRules();
        return rules.ContainsKey(cur.type) && ((prev.type & rules[cur.type]) == prev.type);
    }

    public static ArrayList parse(string sourceText)
    {
        ArrayList result = new ArrayList();
        int openParenthesesCount = 0;
        Lexer lexer = new Lexer(sourceText);
        Token prevToken = lexer.getStartToken();
        Token currentToken = lexer.readNextToken();
        string tmpText = "";
        while (currentToken.type != TokenType.END)
        {
            if (currentToken.type == TokenType.OPEN_PARENTHESE)
            {
                openParenthesesCount++;
                if (openParenthesesCount > 1)
                {
                    tmpText += currentToken.token;
                }
            }
            else if (currentToken.type == TokenType.CLOSE_PARENTHESE)
            {
                openParenthesesCount--;
                if (openParenthesesCount < 0)
                {
                    return Parser.Error();
                }

                if (openParenthesesCount > 0)
                {
                    tmpText += currentToken.token;
                }
            }
            else if (currentToken.type == TokenType.SIMPLE_TEXT)
            {
                tmpText += currentToken.token;
            }

            if (!Parser.isValid(prevToken, currentToken))
            {
                return Parser.Error();
            }

            if (openParenthesesCount == 1 && tmpText.Trim() != "")
            {
                result.Add(tmpText);
                tmpText = "";
            }

            prevToken = currentToken;
            currentToken = lexer.readNextToken();
        }

        if (openParenthesesCount != 0)
        {
            return Parser.Error();
        }

        if (!Parser.isValid(prevToken, currentToken))
        {
            return Parser.Error();
        }

        if (tmpText.Trim() != "")
        {
            result.Add(tmpText);
        }

        return result;
    }

    static ArrayList Error()
    {
        var er = new ArrayList();
        er.Add("ERROR");
        return er;
    }
}

class Lexer
{
    string _txt;
    int _index;
    public Lexer(string text)
    {
        this._index = 0;
        this._txt = text;
    }

    public Token getStartToken()
    {
        return new Token(-1, TokenType.START, "");
    }

    public Token readNextToken()
    {
        if (this._index >= this._txt.Length)
        {
            return new Token(-1, TokenType.END, "");
        }

        Token t = null;
        string txt = "";
        if (this._txt[this._index] == '(')
        {
            txt = "(";
            t = new Token(this._index, TokenType.OPEN_PARENTHESE, txt);
        }
        else if (this._txt[this._index] == ')')
        {
            txt = ")";
            t = new Token(this._index, TokenType.CLOSE_PARENTHESE, txt);
        }
        else
        {
            txt = this._readText();
            t = new Token(this._index, TokenType.SIMPLE_TEXT, txt);
        }

        this._index += txt.Length;
        return t;
    }

    private string _readText()
    {
        string txt = "";
        int i = this._index;
        while (i < this._txt.Length && this._txt[i] != '(' && this._txt[i] != ')')
        {
            txt = txt + this._txt[i];
            i++;
        }

        return txt;
    }
}

class Token
{
    public int position
    {
        get;
        private set;
    }

    public TokenType type
    {
        get;
        private set;
    }

    public string token
    {
        get;
        private set;
    }

    public Token(int position, TokenType type, string token)
    {
        this.position = position;
        this.type = type;
        this.token = token;
    }
}

[Flags]
enum TokenType
{
    START = 1,
    OPEN_PARENTHESE = 2,
    SIMPLE_TEXT = 4,
    CLOSE_PARENTHESE = 8,
    END = 16
}
</code>```

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

I want this string:

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

tp be parsed into:

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

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

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

Body:
I developed a parser for your example. I also checked some other examples which you can see in the code.

   using System;
using System.Collections;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string str = "(example (to (parsing nested paren) but) (first lvl only))"; // => [example  , (to (parsing nested paren) but) ,  (first lvl only)]
        //string str = "(first)(second)(third)"; // => [first , second , third]
        //string str = "(first(second)third)"; // => [first , (second) , third]
        //string str = "(first(second)(third)fourth)"; // => [first , (second) , (third) ,  fourth]
        //string str = "(first((second)(third))fourth)"; // => [first , ((second)(third)) , fourth]

        //string str = "just Text"; // => [ERROR]
        //string str = "start with Text (first , second)"; // => [ERROR]
        //string str = "(first , second) end with text"; // => [ERROR]
        //string str = ""; // => [ERROR]
        //string str = "("; // => [ERROR]
        //string str = "(first()(second)(third))fourth)"; // => [ERROR]
        //string str = "(((extra close pareanthese))))"; // => [ERROR]
        var res = Parser.parse(str);
        showRes(res);
    }

    static void showRes(ArrayList res)
    {
        var strings = res.ToArray();
        var theString = string.Join(" , ", strings);
        Console.WriteLine("[" + theString + "]");
    }
}

public class Parser
{
    static Dictionary<TokenType, TokenType> getRules()
    {
        var rules = new Dictionary<TokenType, TokenType>();
        rules.Add(TokenType.OPEN_PARENTHESE, TokenType.START | TokenType.OPEN_PARENTHESE | TokenType.CLOSE_PARENTHESE | TokenType.SIMPLE_TEXT);
        rules.Add(TokenType.CLOSE_PARENTHESE, TokenType.SIMPLE_TEXT | TokenType.CLOSE_PARENTHESE);
        rules.Add(TokenType.SIMPLE_TEXT, TokenType.SIMPLE_TEXT | TokenType.CLOSE_PARENTHESE | TokenType.OPEN_PARENTHESE);
        rules.Add(TokenType.END, TokenType.CLOSE_PARENTHESE);
        return rules;
    }

    static bool isValid(Token prev, Token cur)
    {
        var rules = Parser.getRules();
        return rules.ContainsKey(cur.type) && ((prev.type & rules[cur.type]) == prev.type);
    }

    public static ArrayList parse(string sourceText)
    {
        ArrayList result = new ArrayList();
        int openParenthesesCount = 0;
        Lexer lexer = new Lexer(sourceText);
        Token prevToken = lexer.getStartToken();
        Token currentToken = lexer.readNextToken();
        string tmpText = "";
        while (currentToken.type != TokenType.END)
        {
            if (currentToken.type == TokenType.OPEN_PARENTHESE)
            {
                openParenthesesCount++;
                if (openParenthesesCount > 1)
                {
                    tmpText += currentToken.token;
                }
            }
            else if (currentToken.type == TokenType.CLOSE_PARENTHESE)
            {
                openParenthesesCount--;
                if (openParenthesesCount < 0)
                {
                    return Parser.Error();
                }

                if (openParenthesesCount > 0)
                {
                    tmpText += currentToken.token;
                }
            }
            else if (currentToken.type == TokenType.SIMPLE_TEXT)
            {
                tmpText += currentToken.token;
            }

            if (!Parser.isValid(prevToken, currentToken))
            {
                return Parser.Error();
            }

            if (openParenthesesCount == 1 && tmpText.Trim() != "")
            {
                result.Add(tmpText);
                tmpText = "";
            }

            prevToken = currentToken;
            currentToken = lexer.readNextToken();
        }

        if (openParenthesesCount != 0)
        {
            return Parser.Error();
        }

        if (!Parser.isValid(prevToken, currentToken))
        {
            return Parser.Error();
        }

        if (tmpText.Trim() != "")
        {
            result.Add(tmpText);
        }

        return result;
    }

    static ArrayList Error()
    {
        var er = new ArrayList();
        er.Add("ERROR");
        return er;
    }
}

class Lexer
{
    string _txt;
    int _index;
    public Lexer(string text)
    {
        this._index = 0;
        this._txt = text;
    }

    public Token getStartToken()
    {
        return new Token(-1, TokenType.START, "");
    }

    public Token readNextToken()
    {
        if (this._index >= this._txt.Length)
        {
            return new Token(-1, TokenType.END, "");
        }

        Token t = null;
        string txt = "";
        if (this._txt[this._index] == '(')
        {
            txt = "(";
            t = new Token(this._index, TokenType.OPEN_PARENTHESE, txt);
        }
        else if (this._txt[this._index] == ')')
        {
            txt = ")";
            t = new Token(this._index, TokenType.CLOSE_PARENTHESE, txt);
        }
        else
        {
            txt = this._readText();
            t = new Token(this._index, TokenType.SIMPLE_TEXT, txt);
        }

        this._index += txt.Length;
        return t;
    }

    private string _readText()
    {
        string txt = "";
        int i = this._index;
        while (i < this._txt.Length && this._txt[i] != '(' && this._txt[i] != ')')
        {
            txt = txt + this._txt[i];
            i++;
        }

        return txt;
    }
}

class Token
{
    public int position
    {
        get;
        private set;
    }

    public TokenType type
    {
        get;
        private set;
    }

    public string token
    {
        get;
        private set;
    }

    public Token(int position, TokenType type, string token)
    {
        this.position = position;
        this.type = type;
        this.token = token;
    }
}

[Flags]
enum TokenType
{
    START = 1,
    OPEN_PARENTHESE = 2,
    SIMPLE_TEXT = 4,
    CLOSE_PARENTHESE = 8,
    END = 16
}


问:
jQuery UI slider - can't slide to 0
jQuery 1.3.2 / jQueryUI 1.7 / Slider

```<code>$("#slider").slider({
    range: "min",
    min: 0,
    max: 40,
    value: 0,
    slide: function(event, ui) {
        CalculateOrder(event, ui);
    }
});
</code>```

it starts off just fine, but after I move the slider I can't get it back to 0, ui.Value is 1 when i slide it all the way to the left.

I've tried setting

```<code>min:-1
</code>```

this sets the ui.Value to -1 when i slide it to -1, but when I'm at 0 the ui.Value is still 1.

Any ideas?

答:
What you want is to get the value when the slider has stop, not during the slide. From my experience, the slide event will get you the previous position of the slider. Stop will give you the value of the slider where the user move it to.</p>

```<code>$("#slider").slider({
    range: 'min',
    min: 0,
    max: 40,
    value: 1,
    step: 10,
    slide : function(event, ui){
        console.log("previous value:"+ $(this).slider('option', 'value'));
    },
    stop: function(event, ui){
        console.log("Current value:"+ $(this).slider('option', 'value'));
    }
});
</code>```

OwnerDisplayName: rm

Title: jQuery UI slider - can't slide to 0

Body:
jQuery 1.3.2 / jQueryUI 1.7 / Slider

$("#slider").slider({
    range: "min",
    min: 0,
    max: 40,
    value: 0,
    slide: function(event, ui) {
        CalculateOrder(event, ui);
    }
});

it starts off just fine, but after I move the slider I can't get it back to 0, ui.Value is 1 when i slide it all the way to the left.

I've tried setting

min:-1

this sets the ui.Value to -1 when i slide it to -1, but when I'm at 0 the ui.Value is still 1.

Any ideas?

LastEditorDisplayName: rm

Body:
What you want is to get the value when the slider has stop, not during the slide. From my experience, the slide event will get you the previous position of the slider. Stop will give you the value of the slider where the user move it to.

$("#slider").slider({
    range: 'min',
    min: 0,
    max: 40,
    value: 1,
    step: 10,
    slide : function(event, ui){
        console.log("previous value:"+ $(this).slider('option', 'value'));
    },
    stop: function(event, ui){
        console.log("Current value:"+ $(this).slider('option', 'value'));
    }
});

OwnerDisplayName: Scott


问:
Does adding [DataContract] and [DataMember] to all classes impact performance
Lets say we got a code generating tool that creates thousands of C# classes, and we sometimes need to add those attributes to them.

We are considering whether it is better to put [DataContract] and [DataMember] on all appropriate classes or we need to create a special strategy that will determine whether to do so in order to save up some possible? performance lost in AtribbuteAll approach.

In the end the question is whether adding attributes can somehow affect performance?

I am thinking that adding an attribute on a class will simply stay with its type information and should not affect any performance but would like to be 100% certain here

答: Doubtful that this will affect performance, all these attributes do is mark them as serializable for WCF.</p>


问:
UserDefaults Error in Mac Catalyst App, Recommended solution doesn't work
I am getting the following error when my App runs as a Mac Catalyst app, it does not happen on iOS.

```<code>2020-05-25 11:33:40.249195-0400 Wasted Time[80637:885413] [User Defaults] Couldn't write values for keys (
    ApplicationAccessibilityEnabled
) in CFPrefsPlistSource<0x600002c01b00> (Domain: com.apple.Accessibility, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: Yes): setting preferences outside an application's container requires user-preference-write or file-write-data sandbox access
</code>```

I have confirmed that my my App Sandbox setting ahas "User Selected File" Permissions set to "Read/Write", and have cleaned build build folder and derived data before rebuilding the app.

I am running Xcode 11.5 (11E608c) and am developing on macOS Catalina Version 10.15.5 Beta(19F94a)

I am also seeing this on Xcode 11.1 (11A1027) and macOS Catalina Version 10.15.4

So it does not appear to be an issue with the version of Xcode of Catalina.

答: After reviewing with multiple people, this appears to be a Xcode problem, and the code doesn't actually have any issues.  Closing this post</p>

Body:
I am getting the following error when my App runs as a Mac Catalyst app, it does not happen on iOS.

2020-05-25 11:33:40.249195-0400 Wasted Time[80637:885413] [User Defaults] Couldn't write values for keys (
    ApplicationAccessibilityEnabled
) in CFPrefsPlistSource<0x600002c01b00> (Domain: com.apple.Accessibility, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: Yes): setting preferences outside an application's container requires user-preference-write or file-write-data sandbox access

I have confirmed that my my App Sandbox setting ahas "User Selected File" Permissions set to "Read/Write", and have cleaned build build folder and derived data before rebuilding the app.

I am running Xcode 11.5 (11E608c) and am developing on macOS Catalina Version 10.15.5 Beta(19F94a)

I am also seeing this on Xcode 11.1 (11A1027) and macOS Catalina Version 10.15.4

So it does not appear to be an issue with the version of Xcode of Catalina.


问:
C++ invalid function type casting
I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:

```<code>void SomeFunction() { }

class A {
  public:
    typedef std::function<void(void)> AFunction;
    static void AMethod(AFunction f) { f(); }
};

class B {
  public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); }
};
</code>```

Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!

答:
B1Method is not void(*)(void), it's void(B1::*)(void).

You may do

```<code>void BIncorrectCall() { A::AMethod(std::bind(&B1::B1Method, this)); }
};
</code>```

Title: C++ invalid function type casting

Body:
I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:

void SomeFunction() { }

class A {
  public:
    typedef std::function<void(void)> AFunction;
    static void AMethod(AFunction f) { f(); }
};

class B {
  public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); }
};

Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!

Body:
B1Method is not void(*)(void), it's void(B1::*)(void).

You may do

void BIncorrectCall() { A::AMethod(std::bind(&B1::B1Method, this)); }
};


问:
Python class adds empty line to last value
I'm trying to write a Login Program in python. I'm trying to read and add the usernames, emails and passwords to a text file. When reading the file I'm using a class to create accounts using the usernames etc. and store them inside my users[] list so I can access it with something like "users[3].username".  Everything worked fine but I'm having one problem: When printing the last value of each account (in this case the password) there is an additional empty line. I dont want this because I cant use it like that for example when checking if a password is correct.

This is the code

```<code>class Accounts:
    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password = password

users = []

def add_account(username, email, password):
    file = open("useraccounts.txt", "a")
    file.write(username + ", " + email + ", " + password + "\n")
    file.close()

def read_accounts():
    file = open("useraccounts.txt", "r")
    count = 0
    for line in file:
        count += 1

    file.seek(0)
    for i in range(count):
        x = file.readline()
        x = x.rsplit(", ")
        new_account = Accounts(x[0], x[1], x[2])
        users.append(new_account)
    file.close()

add_account("Banana", "banana@email.com", "1234")
read_accounts()
print(users[0].username)
print(users[0].email)
print(users[0].password)
print("Something")
</code>```

This is what the Output looks like

```<code>Banana
banana@email.com
1234

Something
</code>```

It also happens when dealing wiht multiple accounts and when writing the text file manually instead of using the add_account function.
I'm sure the problem is my read_accounts function, because the problem does not occur when creating an account manually like this

```<code>account = Accounts("Banana", "banana@email.com", "1234")
</code>```

Also since this is one my firsts programs let me know if you have any other tips.

1 More thing: Originally my post started with "Hey guys" but it got removed. Why does that happen lol?

答:
file.readline() doesn't strip the newline character from the end of the line, so when you split it up, the newline is still attached to the last element (the password). So you should add an rstrip() to your reading, e.g.:

```<code>x = file.readline().rstrip()
</code>```

This should help, happy coding!

Body:
I'm trying to write a Login Program in python. I'm trying to read and add the usernames, emails and passwords to a text file. When reading the file I'm using a class to create accounts using the usernames etc. and store them inside my users[] list so I can access it with something like "users[3].username".  Everything worked fine but I'm having one problem: When printing the last value of each account (in this case the password) there is an additional empty line. I dont want this because I cant use it like that for example when checking if a password is correct.

This is the code

class Accounts:
    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password = password

users = []

def add_account(username, email, password):
    file = open("useraccounts.txt", "a")
    file.write(username + ", " + email + ", " + password + "\n")
    file.close()

def read_accounts():
    file = open("useraccounts.txt", "r")
    count = 0
    for line in file:
        count += 1

    file.seek(0)
    for i in range(count):
        x = file.readline()
        x = x.rsplit(", ")
        new_account = Accounts(x[0], x[1], x[2])
        users.append(new_account)
    file.close()

add_account("Banana", "banana@email.com", "1234")
read_accounts()
print(users[0].username)
print(users[0].email)
print(users[0].password)
print("Something")

This is what the Output looks like

Banana
banana@email.com
1234

Something

It also happens when dealing wiht multiple accounts and when writing the text file manually instead of using the add_account function.
I'm sure the problem is my read_accounts function, because the problem does not occur when creating an account manually like this

account = Accounts("Banana", "banana@email.com", "1234")

Also since this is one my firsts programs let me know if you have any other tips.

1 More thing: Originally my post started with "Hey guys" but it got removed. Why does that happen lol?

Body:
file.readline() doesn't strip the newline character from the end of the line, so when you split it up, the newline is still attached to the last element (the password). So you should add an rstrip() to your reading, e.g.:

x = file.readline().rstrip()

This should help, happy coding!


问:
How to add background to different parts of FlatList in react-native
Do you have any ideas?

P.S. I need a ListHeaderComponent

orig pic

答:
You should add style in container and override other style like this </p>

```<code>    import React from 'react';
import {
  SafeAreaView,
  TouchableOpacity,
  FlatList,
  StyleSheet,
  Text,
  View
} from 'react-native';
import Constants from 'expo-constants';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

function Item({ id, title, selected, onSelect }) {
  return (
    <TouchableOpacity
      onPress={() => onSelect(id)}
      style={[
        styles.item,
        { backgroundColor: selected ? '#6e3b6e' : '#f9c2ff' },
      ]}
    >
      <Text style={styles.title}>{title}</Text>
    </TouchableOpacity>
  );
}

export default function App() {
  const [selected, setSelected] = React.useState(new Map());

  const onSelect = React.useCallback(
    id => {
      const newSelected = new Map(selected);
      newSelected.set(id, !selected.get(id));

      setSelected(newSelected);
    },
    [selected],
  );

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        ListHeaderComponent={()=><View style={{height:80,backgroundColor:'red'}}/>}
        renderItem={({ item }) => (
          <Item
            id={item.id}
            title={item.title}
            selected={!!selected.get(item.id)}
            onSelect={onSelect}
          />
        )}
        keyExtractor={item => item.id}
        extraData={selected}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: Constants.statusBarHeight,
    backgroundColor:'green'
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});
</code>```

Body:
You should add style in container and override other style like this

    import React from 'react';
import {
  SafeAreaView,
  TouchableOpacity,
  FlatList,
  StyleSheet,
  Text,
  View
} from 'react-native';
import Constants from 'expo-constants';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

function Item({ id, title, selected, onSelect }) {
  return (
    <TouchableOpacity
      onPress={() => onSelect(id)}
      style={[
        styles.item,
        { backgroundColor: selected ? '#6e3b6e' : '#f9c2ff' },
      ]}
    >
      <Text style={styles.title}>{title}</Text>
    </TouchableOpacity>
  );
}

export default function App() {
  const [selected, setSelected] = React.useState(new Map());

  const onSelect = React.useCallback(
    id => {
      const newSelected = new Map(selected);
      newSelected.set(id, !selected.get(id));

      setSelected(newSelected);
    },
    [selected],
  );

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        ListHeaderComponent={()=><View style={{height:80,backgroundColor:'red'}}/>}
        renderItem={({ item }) => (
          <Item
            id={item.id}
            title={item.title}
            selected={!!selected.get(item.id)}
            onSelect={onSelect}
          />
        )}
        keyExtractor={item => item.id}
        extraData={selected}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: Constants.statusBarHeight,
    backgroundColor:'green'
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});


问:
How to read a file and replace a string in another file using shell script in linux?
I am try to read the value of the key from the text file. After reading it I wanted to concatenate this value with some string and replace that line in another file. Please find the below code

```<code>source.txt file

USERNAME='cffde308-a1f8-436f-9750-619856e70b88'
PASSWORD='XEAstplhfKNAjUg2Z2oXjIe7o9D4VW3q2dtnkoiMEP0='
</code>```

target.js file

```<code>auth: {
  username: 'zfgde308-a1f8-436f-9750-619856e70b89',
  password: 'ZEAstplhfKNAjUg2Z2oXjIe7o9D4VW3q2dtnkoiMEP0=',
 },
</code>```

I wanted to copy username and password from the source file and replace it in the config file. I tried the below code

```<code>#! /bin/sh
source "/opt/source/source.txt"
USER="username: '$USERNAME',"
PWD="password: '$PASSWORD',"

echo $USER
echo $PWD

sed '/username/c\$USER' target.js
sed '/password/c\$PWD' target.js
</code>```

And the result that i get it is

```<code>    [l21m23 source]$ ./ClientDetailsSetup.sh
    ',ername: 'cffde308-a1f8-436f-9750-619856e70b88
    password: 'XEAstplhfKNAjUg2Z2oXjIe7o9D4VW3q2dtnkoiMEP0=',

    auth: {
      username: 'zfgde308-a1f8-436f-9750-619856e70b89',
$PWD
    },
</code>```

If some help at the earliest to resolve this issue would be of great help

答:
```<code>#!/bin/sh
source "/opt/source/source.txt"
USERN="username: '$USERNAME',"
PWD="password: '$PASSWORD',"

echo $USERN
echo $PWD

sed -i "s/username:.*/$USERN/" target.js
sed -i "s/password:.*/$PWD/" target.js
</code>```

There were a few issues:

USER is a reserved shell variable so you have to give it a different name

your sed script needs s/.../.../ to substitute and you also need to match the rest of the line in your regexp so the .* is needed or the old credentials are still in the output

-i option on sed is needed for an in-place edit

variable substitution is not performed in a string delimited with ', so changed to " here

Body:
I am try to read the value of the key from the text file. After reading it I wanted to concatenate this value with some string and replace that line in another file. Please find the below code

source.txt file

USERNAME='cffde308-a1f8-436f-9750-619856e70b88'
PASSWORD='XEAstplhfKNAjUg2Z2oXjIe7o9D4VW3q2dtnkoiMEP0='

target.js file

auth: {
  username: 'zfgde308-a1f8-436f-9750-619856e70b89',
  password: 'ZEAstplhfKNAjUg2Z2oXjIe7o9D4VW3q2dtnkoiMEP0=',
 },

I wanted to copy username and password from the source file and replace it in the config file. I tried the below code

#! /bin/sh
source "/opt/source/source.txt"
USER="username: '$USERNAME',"
PWD="password: '$PASSWORD',"

echo $USER
echo $PWD

sed '/username/c\$USER' target.js
sed '/password/c\$PWD' target.js

And the result that i get it is

    [l21m23 source]$ ./ClientDetailsSetup.sh
    ',ername: 'cffde308-a1f8-436f-9750-619856e70b88
    password: 'XEAstplhfKNAjUg2Z2oXjIe7o9D4VW3q2dtnkoiMEP0=',

    auth: {
      username: 'zfgde308-a1f8-436f-9750-619856e70b89',
$PWD
    },

If some help at the earliest to resolve this issue would be of great help

Body:
#!/bin/sh
source "/opt/source/source.txt"
USERN="username: '$USERNAME',"
PWD="password: '$PASSWORD',"

echo $USERN
echo $PWD

sed -i "s/username:.*/$USERN/" target.js
sed -i "s/password:.*/$PWD/" target.js

There were a few issues:

USER is a reserved shell variable so you have to give it a different name

your sed script needs s/.../.../ to substitute and you also need to match the rest of the line in your regexp so the .* is needed or the old credentials are still in the output

-i option on sed is needed for an in-place edit

variable substitution is not performed in a string delimited with ', so changed to " here


问:
Window.matchMedia in JavaScript not functioning
I have an HTML, CSS and JavaScript files. The HTML contains three quotes which shuffles every two seconds. I have written the JavaScript code to show these quotes only when the screen width is at most 600px. The problem is that the quote continues to display across every screen width. I've tried using the media query in CSS, but to no avail. What might be the issue? Please, see code below.

HTML Code:

```<code><div class="preNavBar">
        <div class="quoteWrapper">
            <span class="quote">The roots of education are bitter, but the fruit is sweet.  </span>
            <span class="quoteAuthor">— Aristotle</span>
        </div>
        <div class="quoteWrapper">
            <span class="quote">To teach is to learn twice.  </span>
            <span class="quoteAuthor">— Unknown</span>
        </div>
        <div class="quoteWrapper">
            <span class="quote">A person who won't read has no advantage over one who can't read.  </span>
            <span class="quoteAuthor">— Mark Twain</span>
        </div>
    </div>
</code>```

CSS Code:

```<code>body {
    padding: 0 !important;
    margin: 0 !important;
    font-size: 16pxm;
    background: rgb(53, 54, 58);
}

* {
    box-sizing: border-box;
    /* margin: 0; */
    padding: 0;
}

/* PRE-NAVIGATION BAR */
.preNavBar {
    background-color: navy;
    color: white;
    padding: 10px 30px;
    display: grid;
    justify-content: center;
}

.preNavBar .quoteAuthor {
    font-weight: bolder;
    float: right;
}

@media only screen and (min-width: 768px) {
    /* .preNavBar .quoteWrapper{
        display: none;
    } */
}
</code>```

JavaScript Code:

```<code><script>
        let x = window.matchMedia("(max-width: 600px)");
        if (x.matches) {
            showQuote();
            function showQuote() {
                let slides = document.getElementsByClassName("quoteWrapper");
                let i;
                for (i = 0; i < slides.length; i++) {
                    slides[i].style.display = "none";
                }

                let min = 0;
                let max = slides.length - 1;
                let randNum = Math.floor(Math.random() * (max - min + 1)) + min;

                slides[randNum].style.display = "block";

                setTimeout(showQuote, 2000); // change every 2 seconds
            }
        }
    </script>
</code>```

答:
Let's take a look at the very first line:

let x = window.matchMedia("(max-width: 800px)");
```

You invoke window.matchMedia and store returned value in x.

The important thing here is that x will not change if screen is resized after the moment it was declared.

If you want it to, you'll need a resize event listener.

Also, a possible pitfall here is that depending on where in the document your

Body:
I have an HTML, CSS and JavaScript files. The HTML contains three quotes which shuffles every two seconds. I have written the JavaScript code to show these quotes only when the screen width is at most 600px. The problem is that the quote continues to display across every screen width. I've tried using the media query in CSS, but to no avail. What might be the issue? Please, see code below.

HTML Code:

            The roots of education are bitter, but the fruit is sweet.
            — Aristotle

            To teach is to learn twice.
            — Unknown

            A person who won't read has no advantage over one who can't read.
            — Mark Twain

CSS Code:

body {
    padding: 0 !important;
    margin: 0 !important;
    font-size: 16pxm;
    background: rgb(53, 54, 58);
}

* {
    box-sizing: border-box;
    /* margin: 0; */
    padding: 0;
}

/* PRE-NAVIGATION BAR */
.preNavBar {
    background-color: navy;
    color: white;
    padding: 10px 30px;
    display: grid;
    justify-content: center;
}

.preNavBar .quoteAuthor {
    font-weight: bolder;
    float: right;
}

@media only screen and (min-width: 768px) {
    /* .preNavBar .quoteWrapper{
        display: none;
    } */
}

JavaScript Code:

Body:
Let's take a look at the very first line:

let x = window.matchMedia("(max-width: 800px)");

You invoke window.matchMedia and store returned value in x.

The important thing here is that x will not change if screen is resized after the moment it was declared.

If you want it to, you'll need a resize event listener.

Also, a possible pitfall here is that depending on where in the document your <script> tag is placed, you might want to wrap all your code into an IIFE to ensure it fires after the document is completely loaded.


问:
Page stops responding and freezes while sending continuous request to web server from ajax
I'm trying to create a signal on the webpage and display green or red color on the basis of values retrieved from a database. But when I'm sending request after 10 seconds page seems to be freezed and not responding. I'm unable to find out where I'm going wrong, please help me to resolve this problem.

Techstack Using - HTML, CSS, Js, Ajax, Python(Flask) and PostgreSQL

```<code>function latest_status(){

    var header = document.getElementById("circle");

    var tbid = $('#mtb').val();

    var signal = $.ajax({
        type: 'POST',
        url: '/status?tbid='+tbid,
        data: "",
        contentType: false,
        dataType: "json",
        async:false,
        cache: false,
        processData: false,
        success: function(data) {
        },
        //error: function(data) {
        //  alert("Data Not received !!");
        //},
        complete: function(data){
            setTimeout(latest_status, 10000);
        }
    });

    var signaldata = JSON.parse(signal.responseText);

    var signalvalue = signaldata[0].signalvalue;
    var datevalue = signaldata[0].date;

    if(signalvalue == '1')
    {
        header.style.background = "green";
    }
    else
    {
        header.style.background = "red";
    }
};

setTimeout(latest_status, 10000);
</code>```

Flask Code :

```<code>from flask import Flask, redirect, url_for, request, render_template
from flask_socketio import SocketIO
from werkzeug.utils import secure_filename
from flask import jsonify
import json
import eventlet

from collections import OrderedDict

import psycopg2

app = Flask(__name__)
app.config['SECRET_KEY'] = 'project!'
socketio = SocketIO(app)

@app.route('/status', methods = ['POST', 'GET'])
def latest_status():

    tbid = request.args['tbid']

    if request.method == 'POST':

        connection = psycopg2.connect(user = "postgres", password = "abcd",host = "localhost",port = "5432", database="mydb")
        cursor = connection.cursor()

        sql1 = "Select * from hst_vw where tb_id = %s"

        record_to_update = (tbid,)

        cursor.execute(sql1,record_to_update)
        record = cursor.fetchall()
        connection.commit()

        status_arr = []

        for i in record:
            hs = OrderedDict()
            hs["signalvalue"] = i[0]
            hs["date"] = i[1]
            hs["tbid"] = i[2]

            status_arr.append(hs)

        json_date = json.dumps(status_arr, default = str)

        return json_date

if __name__ == '__main__':
    socketio.run(app)
</code>```

答:
If you put the setTimeout(latest_status, 10000); inside success block then it will run once the request is completed so your code will look something like this.

```<code>var signal = $.ajax({
    type: 'POST',
    url: '/status?tbid='+tbid,
    data: "",
    contentType: false,
    dataType: "json",
    async:false,
    cache: false,
    processData: false,
    success: function(data) {
        setTimeout(latest_status, 10000);
    },
});
</code>```

I hope this will help.

Body:
I'm trying to create a signal on the webpage and display green or red color on the basis of values retrieved from a database. But when I'm sending request after 10 seconds page seems to be freezed and not responding. I'm unable to find out where I'm going wrong, please help me to resolve this problem.

Techstack Using - HTML, CSS, Js, Ajax, Python(Flask) and PostgreSQL

function latest_status(){

    var header = document.getElementById("circle");

    var tbid = $('#mtb').val();

    var signal = $.ajax({
        type: 'POST',
        url: '/status?tbid='+tbid,
        data: "",
        contentType: false,
        dataType: "json",
        async:false,
        cache: false,
        processData: false,
        success: function(data) {
        },
        //error: function(data) {
        //  alert("Data Not received !!");
        //},
        complete: function(data){
            setTimeout(latest_status, 10000);
        }
    });

    var signaldata = JSON.parse(signal.responseText);

    var signalvalue = signaldata[0].signalvalue;
    var datevalue = signaldata[0].date;

    if(signalvalue == '1')
    {
        header.style.background = "green";
    }
    else
    {
        header.style.background = "red";
    }
};

setTimeout(latest_status, 10000);

Flask Code :

from flask import Flask, redirect, url_for, request, render_template
from flask_socketio import SocketIO
from werkzeug.utils import secure_filename
from flask import jsonify
import json
import eventlet

from collections import OrderedDict

import psycopg2

app = Flask(__name__)
app.config['SECRET_KEY'] = 'project!'
socketio = SocketIO(app)

@app.route('/status', methods = ['POST', 'GET'])
def latest_status():

    tbid = request.args['tbid']

    if request.method == 'POST':

        connection = psycopg2.connect(user = "postgres", password = "abcd",host = "localhost",port = "5432", database="mydb")
        cursor = connection.cursor()

        sql1 = "Select * from hst_vw where tb_id = %s"

        record_to_update = (tbid,)

        cursor.execute(sql1,record_to_update)
        record = cursor.fetchall()
        connection.commit()

        status_arr = []

        for i in record:
            hs = OrderedDict()
            hs["signalvalue"] = i[0]
            hs["date"] = i[1]
            hs["tbid"] = i[2]

            status_arr.append(hs)

        json_date = json.dumps(status_arr, default = str)

        return json_date

if __name__ == '__main__':
    socketio.run(app)

Body:
If you put the setTimeout(latest_status, 10000); inside success block then it will run once the request is completed so your code will look something like this.

var signal = $.ajax({
    type: 'POST',
    url: '/status?tbid='+tbid,
    data: "",
    contentType: false,
    dataType: "json",
    async:false,
    cache: false,
    processData: false,
    success: function(data) {
        setTimeout(latest_status, 10000);
    },
});

I hope this will help.


问:
Find the first 300 members of the server
I want to create a bot that can tell me the list of the first 300 members of my server. Is this possible with Discord.js? Any help would be appreciated. I just don't know where to start</p>

答:
Assuming you want to get the first 300 members that joined the guild, you can use the GuildMember.joinedAt property. You would go through these steps:

Fetch all the members in the guild: you can use Guild.members.fetch() for that

Sort them by the date you get from the joinedAt property

Get the first 300

Here's how I would do it:

guild.members.fetch() // Fectch all the members in the guild
  .then(members => {
    let first300 = members
      .sort((a, b) => a.joinedAt - b.joinedAt) // Order them by they date the joined the guild
      .first(300) // Take the first 300
  })
```


问:
Rails 3, using mongoid but syntax error gets produced
In my development environment, which is windows 7, Ruby1.9.2p180, everything works fine.

However, in production environment, which is Ubuntu 10.04, Ree 1.8.7 using rvm, following error gets produced.
(I am using passenger-apache-module to run the application.)

```<code>/home/randomapp/public_html/app/models/article.rb:14: syntax error, unexpected ':', expecting kEND field :user_id, type: Hash ^
/home/randomapp/public_html/app/models/article.rb:15: syntax error, unexpected ':', expecting kEND field :username, type: String ^
/home/randomapp/public_html/app/models/article.rb:16: syntax error, unexpected ':', expecting kEND field :title, type: String ^
/home/randomapp/public_html/app/models/article.rb:17: syntax error, unexpected ':', expecting kEND field :content, type: String ^
/home/randomapp/public_html/app/models/article.rb:18: syntax error, unexpected ':', expecting kEND field :display_content, type: String ^
</code>```

Where those lines have below codes

```<code>  field :user_id, type: Hash
  field :username, type: String
  field :title, type: String
  field :content, type: String
  field :display_content, type: String
</code>```

Assuming above lines work fine in development, do you think it may be a problem with syntax parser???
How can I resolve this problem?

答:
You are using the 1.9.2 hash syntax. If you want to run on both 1.9.2 and 1.8.7 then try this:</p>

```<code>field :user_id, :type => Hash
field :username, :type => String
field :title, :type => String
field :content, :type => String
field :display_content, :type => String
</code>```

Body:
In my development environment, which is windows 7, Ruby1.9.2p180, everything works fine.

However, in production environment, which is Ubuntu 10.04, Ree 1.8.7 using rvm, following error gets produced.
(I am using passenger-apache-module to run the application.)

/home/randomapp/public_html/app/models/article.rb:14: syntax error, unexpected ':', expecting kEND field :user_id, type: Hash ^
/home/randomapp/public_html/app/models/article.rb:15: syntax error, unexpected ':', expecting kEND field :username, type: String ^
/home/randomapp/public_html/app/models/article.rb:16: syntax error, unexpected ':', expecting kEND field :title, type: String ^
/home/randomapp/public_html/app/models/article.rb:17: syntax error, unexpected ':', expecting kEND field :content, type: String ^
/home/randomapp/public_html/app/models/article.rb:18: syntax error, unexpected ':', expecting kEND field :display_content, type: String ^

Where those lines have below codes

  field :user_id, type: Hash
  field :username, type: String
  field :title, type: String
  field :content, type: String
  field :display_content, type: String

Assuming above lines work fine in development, do you think it may be a problem with syntax parser???
How can I resolve this problem?

Body:
You are using the 1.9.2 hash syntax. If you want to run on both 1.9.2 and 1.8.7 then try this:

field :user_id, :type => Hash
field :username, :type => String
field :title, :type => String
field :content, :type => String
field :display_content, :type => String