问:
java.lang.IllegalStateException: The ad size and ad unit ID must be set before loadAd is called.?
I am developing news app and I have implemented adview with databinding but it is giving following exception

```<code>java.lang.IllegalStateException: The ad size and ad unit ID must be set before loadAd is called.
     at com.google.android.gms.internal.ads.zzxv.zza(com.google.android.gms:play-services-ads-lite@@19.1.0:82)
     at com.google.android.gms.ads.BaseAdView.loadAd(com.google.android.gms:play-services-ads-lite@@19.1.0:15)
     at com.google.android.gms.ads.AdView.loadAd(com.google.android.gms:play-services-ads-lite@@19.1.0:20)
     at yodgorbek.komilov.musobaqayangiliklari.ui.TopHeadlinesFragment.initializeAds(TopHeadlinesFragment.kt:95)
     at yodgorbek.komilov.musobaqayangiliklari.ui.TopHeadlinesFragment.onViewCreated(TopHeadlinesFragment.kt:56)
     at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:322)
     at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1185)
     at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1354)
     at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1432)
     at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1495)
     at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
     at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2167)
     at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1990)
     at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1945)
     at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1847)
     at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2621)
     at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2569)
     at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
     at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
     at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1392)
     at android.app.Activity.performStart(Activity.java:7252)
     at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3000)
     at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:185)
     at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:170)
     at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:147)
     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1858)
     at android.os.Handler.dispatchMessage(Handler.java:106)
     at android.os.Looper.loop(Looper.java:201)
     at android.app.ActivityThread.main(ActivityThread.java:6820)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)
</code>```

but I have tried following answers Ad Size and Ad unit id must be set before loadAd is called and  this The ad size and ad unit ID must be set before loadAd when set programmatically  and this one as well Include AdView with databinding and https://github.com/firebase/quickstart-android/blob/master/admob/app/src/main/java/com/google/samples/quickstart/admobexample/kotlin/MainActivity.kt from StackOverflow it did not solve my problem

below my XML file where I have implemented ad view

```<code><data>

    <variable
        name="adId"
        type="String" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="56dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/pb"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@{adId}"
        ads:layout_constraintTop_toBottomOf="@+id/pb"
        ads:layout_constraintBottom_toBottomOf="@+id/pb"/>

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

below my Fragment class

```<code>class TopHeadlinesFragment : Fragment() {

    private lateinit var binding: FragmentTopHeadlinesBinding

    private val viewModel by viewModel<MainViewModel>()

    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter

    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
        binding.lifecycleOwner = this
        topHeadlinesAdapter = TopHeadlinesAdapter()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
        initializeAds()

    }

    private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()
                }
            }
        })

        viewModel.showLoading.observe(this, Observer { showLoading ->
            pb.visibility = if (showLoading) View.VISIBLE else View.GONE
        })

        viewModel.loadNews()
    }

    private fun initializeAds(){
        MobileAds.initialize(context)

       // adView.adSize = AdSize.BANNER
        binding.adId = "my unit id"
        val adRequest = AdRequest.Builder().build()
        binding.adView.loadAd(adRequest)
    }

}
</code>```

I want to  know where exactly I am making mistake I have tried all StackOverflow and even documentation sample it did solve my issue I have tried set unit id and size programmatically using kotlin and XML file as well it did not work at all any tips will be appreciated.

答:
```<code> //Admob banner
        MobileAds.initialize(this, new OnInitializationCompleteListener()  {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                mAdView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAdFailedToLoad(int i) {
                super.onAdFailedToLoad(i);
                mAdView.setVisibility(View.GONE);
            }

        });
</code>```

xml

```<code><com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="30dp"
        android:visibility="gone"
        app:adSize="BANNER"
        app:adUnitId="@string/ad_unit_id_banner1" />
</code>```

manifest

```<code> <meta-data
                android:name="com.google.android.gms.ads.APPLICATION_ID"
                android:value="@string/app_id"/>
        <meta-data
            android:name="com.google.android.gms.ads.AD_MANAGER_APP"
            android:value="true" />
</code>```

Body:
I am developing news app and I have implemented adview with databinding but it is giving following exception

java.lang.IllegalStateException: The ad size and ad unit ID must be set before loadAd is called.
     at com.google.android.gms.internal.ads.zzxv.zza(com.google.android.gms:play-services-ads-lite@@19.1.0:82)
     at com.google.android.gms.ads.BaseAdView.loadAd(com.google.android.gms:play-services-ads-lite@@19.1.0:15)
     at com.google.android.gms.ads.AdView.loadAd(com.google.android.gms:play-services-ads-lite@@19.1.0:20)
     at yodgorbek.komilov.musobaqayangiliklari.ui.TopHeadlinesFragment.initializeAds(TopHeadlinesFragment.kt:95)
     at yodgorbek.komilov.musobaqayangiliklari.ui.TopHeadlinesFragment.onViewCreated(TopHeadlinesFragment.kt:56)
     at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:322)
     at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1185)
     at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1354)
     at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1432)
     at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1495)
     at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
     at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2167)
     at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1990)
     at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1945)
     at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1847)
     at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2621)
     at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2569)
     at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
     at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
     at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1392)
     at android.app.Activity.performStart(Activity.java:7252)
     at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3000)
     at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:185)
     at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:170)
     at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:147)
     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1858)
     at android.os.Handler.dispatchMessage(Handler.java:106)
     at android.os.Looper.loop(Looper.java:201)
     at android.app.ActivityThread.main(ActivityThread.java:6820)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)

but I have tried following answers Ad Size and Ad unit id must be set before loadAd is called and  this The ad size and ad unit ID must be set before loadAd when set programmatically  and this one as well Include AdView with databinding and https://github.com/firebase/quickstart-android/blob/master/admob/app/src/main/java/com/google/samples/quickstart/admobexample/kotlin/MainActivity.kt from StackOverflow it did not solve my problem

below my XML file where I have implemented ad view

<data>

    <variable
        name="adId"
        type="String" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="56dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/pb"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@{adId}"
        ads:layout_constraintTop_toBottomOf="@+id/pb"
        ads:layout_constraintBottom_toBottomOf="@+id/pb"/>

</androidx.constraintlayout.widget.ConstraintLayout>

below my Fragment class

class TopHeadlinesFragment : Fragment() {

    private lateinit var binding: FragmentTopHeadlinesBinding

    private val viewModel by viewModel<MainViewModel>()

    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter

    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
        binding.lifecycleOwner = this
        topHeadlinesAdapter = TopHeadlinesAdapter()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
        initializeAds()

    }

    private fun initViewModel() {
        viewModel.sportList.observe(this, Observer { result ->

            when (result) {
                is Results.Success -> {
                    val newList = result.data
                    if (newList != null) {
                        topHeadlinesAdapter.updateData(newList)
                    }
                    binding.recyclerView.adapter = topHeadlinesAdapter
                    topHeadlinesAdapter.notifyDataSetChanged()
                }
            }
        })

        viewModel.showLoading.observe(this, Observer { showLoading ->
            pb.visibility = if (showLoading) View.VISIBLE else View.GONE
        })

        viewModel.loadNews()
    }

    private fun initializeAds(){
        MobileAds.initialize(context)

       // adView.adSize = AdSize.BANNER
        binding.adId = "my unit id"
        val adRequest = AdRequest.Builder().build()
        binding.adView.loadAd(adRequest)
    }

}

I want to  know where exactly I am making mistake I have tried all StackOverflow and even documentation sample it did solve my issue I have tried set unit id and size programmatically using kotlin and XML file as well it did not work at all any tips will be appreciated.

Body:
 //Admob banner
        MobileAds.initialize(this, new OnInitializationCompleteListener()  {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                mAdView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAdFailedToLoad(int i) {
                super.onAdFailedToLoad(i);
                mAdView.setVisibility(View.GONE);
            }

        });

xml

<com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="30dp"
        android:visibility="gone"
        app:adSize="BANNER"
        app:adUnitId="@string/ad_unit_id_banner1" />

manifest

 <meta-data
                android:name="com.google.android.gms.ads.APPLICATION_ID"
                android:value="@string/app_id"/>
        <meta-data
            android:name="com.google.android.gms.ads.AD_MANAGER_APP"
            android:value="true" />


来源: stackexchange

问:
Can you use AdminBro as admin panel with MySQL and express.js?
Can you use AdminBro as an admin panel with MySQL and express.js without having to use sequelize?</p>

答: You have to use either sequelize or typeorm (supported adapters). Otherwise, you would need to create your own adapter which connects with MySQL directly.</p>

ContentLicense: CC BY-SA 4.0


问:
How to insert a string to a text field programatically in JavaScript
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

```<code><form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>
</code>```

I have tried something like this but it doesn't work:

```<code><script type="text/javascript"> edit-form.value="the new value"; </script>
</code>```

How can I do this?

答:
did you try getting this by document.getElementById()

```<code><script type="text/javascript"> document.getElementById("edit-mail").value="the new value"; </script>
</code>```

assuming edit-mail is your textbox id

Body:
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

<form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>

I have tried something like this but it doesn't work:

How can I do this?

Body:
did you try getting this by document.getElementById()

<script type="text/javascript"> document.getElementById("edit-mail").value="the new value"; </script>

assuming edit-mail is your textbox id

ContentLicense: CC BY-SA 3.0


问:
Initializing the nested anonymus struct created from XML to struct converter
Following is the output from an XML to struct transform for Go

```<code>type Metadata struct {
XMLName     xml.Name `xml:"metadata"`
Text        string   `xml:",chardata"`
Ns2         string   `xml:"ns2,attr"`
PasMetadata struct {
    Text        string `xml:",chardata"`
    SimpleValue struct {
        Text  string `xml:",chardata"`
        Entry struct {
            Text  string `xml:",chardata"`
            Key   string `xml:"key"`
            Value string `xml:"value"`
        } `xml:"entry"`
    } `xml:"simple_value"`
} `xml:"pas_metadata"`}
</code>```

but based on suggestion for nested anonymous struct created other struct as below

```<code>    type PasMetadata struct {
    Text        string `xml:",chardata"`
    SimpleValue `xml:"simple_value"`
}

type SimpleValue struct {
    Text  string `xml:",chardata"`
    Entry `xml:"entry"`
}

type Entry struct {
    Text  string `xml:",chardata"`
    Key   string `xml:"key"`
    Value string `xml:"value"`
}

type Metadata struct {
    XMLName     xml.Name `xml:"metadata"`
    Text        string   `xml:",chardata"`
    Ns2         string   `xml:"ns2,attr"`
    PasMetadata `xml:"pas_metadata"`
}
</code>```

Now getting error while initializing with following statement

```<code>metinfo := Metadata{Ns2: "http://test.com", PasMetadata{SimpleValue{Entry{Key: "testcode", Value: "testvalue"}}}}
</code>```

Error was : mixture of field:value and value initializers

答:
Initialization of embedded structs is similar to regular ones, see composite literals. If you specify a field name, you must specify all of them.

For embedded structs, the field name is the name of the embedded type.

So your composite literal becomes:

```<code>metinfo := Metadata{Ns2: "http://test.com", PasMetadata: PasMetadata{SimpleValue: SimpleValue{Entry: Entry{Key: "testcode", Value: "testvalue"}}}}
</code>```

The difference from yours is that the field name is always set. Specifically:

PasMetadata: PasMetadata{...}

SimpleValue: SimpleValue{...}

Entry: Entry{...}

Body:
Following is the output from an XML to struct transform for Go

type Metadata struct {
XMLName     xml.Name `xml:"metadata"`
Text        string   `xml:",chardata"`
Ns2         string   `xml:"ns2,attr"`
PasMetadata struct {
    Text        string `xml:",chardata"`
    SimpleValue struct {
        Text  string `xml:",chardata"`
        Entry struct {
            Text  string `xml:",chardata"`
            Key   string `xml:"key"`
            Value string `xml:"value"`
        } `xml:"entry"`
    } `xml:"simple_value"`
} `xml:"pas_metadata"`}

but based on suggestion for nested anonymous struct created other struct as below

    type PasMetadata struct {
    Text        string `xml:",chardata"`
    SimpleValue `xml:"simple_value"`
}

type SimpleValue struct {
    Text  string `xml:",chardata"`
    Entry `xml:"entry"`
}

type Entry struct {
    Text  string `xml:",chardata"`
    Key   string `xml:"key"`
    Value string `xml:"value"`
}

type Metadata struct {
    XMLName     xml.Name `xml:"metadata"`
    Text        string   `xml:",chardata"`
    Ns2         string   `xml:"ns2,attr"`
    PasMetadata `xml:"pas_metadata"`
}

Now getting error while initializing with following statement

metinfo := Metadata{Ns2: "http://test.com", PasMetadata{SimpleValue{Entry{Key: "testcode", Value: "testvalue"}}}}

Error was : mixture of field:value and value initializers

Body:
Initialization of embedded structs is similar to regular ones, see composite literals. If you specify a field name, you must specify all of them.

For embedded structs, the field name is the name of the embedded type.

So your composite literal becomes:

metinfo := Metadata{Ns2: "http://test.com", PasMetadata: PasMetadata{SimpleValue: SimpleValue{Entry: Entry{Key: "testcode", Value: "testvalue"}}}}

The difference from yours is that the field name is always set. Specifically:

PasMetadata: PasMetadata{...}

SimpleValue: SimpleValue{...}

Entry: Entry{...}


问:
Set timezone relative to user in django
I made a web app using django, I'm not sure about the timezones and stuff. I have the user's preferred timezone, how can I set this timezone relative to that particular user? or will it automatically adjust to the user's timezone?</p>

答:
You can set the time zone that you want django to use in the settings.py

eg
settings.py

```<code>TIME_ZONE = 'Europe/Berlin'
</code>```

Title: Set timezone relative to user in django

Body:
You can set the time zone that you want django to use in the settings.py

eg
settings.py

TIME_ZONE = 'Europe/Berlin'


问:
How to create a circled Image overlapping each half in between two views in react native?

As shown in above image I want my circled Image component to lie between two view components. I tried changing the position to absolute, but the circle gets disappeared after changing the position to absolute. Also I want a responsive kind of behavior for this screen so I can't just add a partitioned background image for this.

答:
After positioning you image absolute you may have to give it a z-index more than that of View1 and View2, so the css for Image would look like:

```<code>.image{
  z-index: 1; //considering all other views aren't given any z-index
  position: absolute;
  height: 20px;
  width: 20px;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</code>```

Please note that this code assumes that Image is a sibling of View1 and View2

Body:
After positioning you image absolute you may have to give it a z-index more than that of View1 and View2, so the css for Image would look like:

.image{
  z-index: 1; //considering all other views aren't given any z-index
  position: absolute;
  height: 20px;
  width: 20px;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Please note that this code assumes that Image is a sibling of View1 and View2


问:
Resources for developing a C++ MySQL application for Linux
I'm going to be developing a C++ application that uses a MySQL database.

I've written similar apps in Java using JDBC, as well as the Spring Framework.

Are there equivalent libraries for C++?  What have you had the most success with?

答: I would use the MySQL C API, it is the simplest solution. You can easily write a class to wrap up the C api for your own uses.</p>

OwnerDisplayName: Clayton

ContentLicense: CC BY-SA 2.5


问:
Switch Views Within UITabBar Tab Using Segmented Control
I am working on an app that allows two media galleries to be loaded into the same tab. They have separate XIB files and are loaded as such. However, once I switch views using the segmented control the UITabBar disappears.

This is how I am switching the views:

```<code>//Switch Views
- (IBAction)segmentSwitch:(id)sender
   {
   if([sender selectedSegmentIndex] == 0)
   {
      MediaViewController *vc = [[MediaViewController alloc] initWithNibName: @"MediaView" bundle:nil];
      vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: vc animated: YES];
   }
   else if([sender selectedSegmentIndex] == 1)
   {
      MediaViewControllerTwo*v2 = [[MediaViewControllerTwo alloc] initWithNibName: @"MediaViewTwo" bundle:nil];
      v2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: v2 animated: YES];
   }
}
</code>```

答:
The reason why your view disappear is that you are showing a modal view controller on top of it:

```<code>    [self presentModalViewController: v2 animated: YES];
</code>```

As you know a modal view controller takes the whole display space for it.

What are you trying to accomplish with your segmented control?

EDIT: in order to change the current view displayed in the UITabBar, you have several options. One is simply adding a subview to the current view; in your view controller do:

```<code>[self.view addSubview: vc.view];
[vc viewWillAppear:NO];
[vc viewDidAppear:NO];
</code>```

the calls to viewWillAppear and viewDidAppear are required, the framework will not call them for you in this case.

I assume that you segmented control is used to control a subarea of your view (i.e., your view has an upper part where the segmented control is and a lower part with some other content). In this case, I would simply try and replace the subview which lays below the segmented control. The technique is just the same.

After reading your comment, you could replace one table with the other one. Or better, have them both added as subview (full frame), and just hide one or the other according to the segmented control selection.

Body:
I am working on an app that allows two media galleries to be loaded into the same tab. They have separate XIB files and are loaded as such. However, once I switch views using the segmented control the UITabBar disappears.

This is how I am switching the views:

//Switch Views
- (IBAction)segmentSwitch:(id)sender
   {
   if([sender selectedSegmentIndex] == 0)
   {
      MediaViewController *vc = [[MediaViewController alloc] initWithNibName: @"MediaView" bundle:nil];
      vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: vc animated: YES];
   }
   else if([sender selectedSegmentIndex] == 1)
   {
      MediaViewControllerTwo*v2 = [[MediaViewControllerTwo alloc] initWithNibName: @"MediaViewTwo" bundle:nil];
      v2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
      [self presentModalViewController: v2 animated: YES];
   }
}

Body:
The reason why your view disappear is that you are showing a modal view controller on top of it:

    [self presentModalViewController: v2 animated: YES];

As you know a modal view controller takes the whole display space for it.

What are you trying to accomplish with your segmented control?

EDIT: in order to change the current view displayed in the UITabBar, you have several options. One is simply adding a subview to the current view; in your view controller do:

[self.view addSubview: vc.view];
[vc viewWillAppear:NO];
[vc viewDidAppear:NO];

the calls to viewWillAppear and viewDidAppear are required, the framework will not call them for you in this case.

I assume that you segmented control is used to control a subarea of your view (i.e., your view has an upper part where the segmented control is and a lower part with some other content). In this case, I would simply try and replace the subview which lays below the segmented control. The technique is just the same.

After reading your comment, you could replace one table with the other one. Or better, have them both added as subview (full frame), and just hide one or the other according to the segmented control selection.


问:
How can I fix "index out of Range" for a multi-dimensional view in SwiftUI
I tried as much as I could before asking the next "Index out of Range" question, because generally I understand why an index out of range issue occurs, but this specific issues makes me crazy:

```<code>struct Parent: Identifiable {
    let id = UUID()
    let name: String
    var children: [Child]?
}

struct Child: Identifiable {
    let id = UUID()
    let name: String
    var puppets: [Puppet]?
}

struct Puppet: Identifiable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)]),
            Parent(name: "FooBar", children: nil)
        ]
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach (appState.parents.indices, id: \.self) { parentIndex in
                        NavigationLink (destination: ChildrenView(parentIndex: parentIndex).environmentObject(self.appState)) {
                            Text(self.appState.parents[parentIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
                Button(action: {
                    self.appState.parents.append(Parent(name: "Test", children: nil))
                }) {
                    Text("Add")
                }
                .padding(.bottom, 15)
            }
        .navigationBarTitle(Text("Parents"))
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var body: some View {
        let children = appState.parents[parentIndex].children
        return VStack {
            List {
                if (children?.indices != nil) {
                    ForEach (children!.indices, id: \.self) { childIndex in
                        NavigationLink (destination: PuppetsView(parentIndex: self.parentIndex, childIndex: childIndex).environmentObject(self.appState)) {
                            Text(children![childIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var children = self.appState.parents[self.parentIndex].children
                if (children != nil) {
                    children?.append(Child(name: "Teest"))
                } else {
                    children = [Child(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Children"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children!.remove(atOffsets: indexSet)
        }
    }
}

struct PuppetsView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var childIndex: Int
    var body: some View {
        let child = appState.parents[parentIndex].children?[childIndex]
        return VStack {
            List {
                if (child != nil && child!.puppets?.indices != nil) {
                    ForEach (child!.puppets!.indices, id: \.self) { puppetIndex in
                        Text(self.appState.parents[self.parentIndex].children![self.childIndex].puppets![puppetIndex].name)
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var puppets = self.appState.parents[self.parentIndex].children![self.childIndex].puppets
                if (puppets != nil) {
                   puppets!.append(Puppet(name: "Teest"))
                } else {
                   puppets = [Puppet(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Puppets"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children![self.childIndex].puppets!.remove(atOffsets: indexSet)
        }
    }
}
</code>```

I can remove both children of Foo and FooBar without issues, but when I remove the Puppet of child bar first, then the app crashes like shown in the comments.

I unterstand that the childIndex doesn't exist anymore, but I don't understand why the view gets built again when there is no child with puppets.

答:
The problem with your optional chaining is that this line produces the result of type Child and not Child?:

```<code>appState.parents[parentIndex].children?[childIndex]
</code>```

And if it's not an optional you can't call puppets on children?[childIndex] without checking if childIndex is valid:

```<code>// this will crash when childIndex is out of range
appState.parents[parentIndex].children?[childIndex].puppets?.indices
</code>```

I recommend to use safeIndex subscript for accessing possible empty elements:

```<code>var body: some View {

    let child = appState.parents[safeIndex: parentIndex]?.children?[safeIndex: childIndex]
    return VStack {
        List {
            if (child != nil && child!.puppets?.indices != nil) {
                ForEach ((appState.parents[parentIndex].children?[childIndex].puppets!.indices)!, id: \.self) { puppetIndex in
                    Text(self.appState.parents[self.parentIndex].children![self.childIndex].puppets![puppetIndex].name)
                }
                .onDelete(perform: deleteItem)
            }
        }
    ...
}
</code>```

To do this you would need an Array extension which allows to access array elements in a safe way (ie. return nil instead of throwing an error):

```<code>extension Array {
    public subscript(safeIndex index: Int) -> Element? {
        guard index >= 0, index < endIndex else {
            return nil
        }

        return self[index]
    }
}
</code>```

Note: You'd need to do the same for the ParentView, so in overall Paulw11's answer is cleaner.

Body:
I tried as much as I could before asking the next "Index out of Range" question, because generally I understand why an index out of range issue occurs, but this specific issues makes me crazy:

struct Parent: Identifiable {
    let id = UUID()
    let name: String
    var children: [Child]?
}

struct Child: Identifiable {
    let id = UUID()
    let name: String
    var puppets: [Puppet]?
}

struct Puppet: Identifiable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)]),
            Parent(name: "FooBar", children: nil)
        ]
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach (appState.parents.indices, id: \.self) { parentIndex in
                        NavigationLink (destination: ChildrenView(parentIndex: parentIndex).environmentObject(self.appState)) {
                            Text(self.appState.parents[parentIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
                Button(action: {
                    self.appState.parents.append(Parent(name: "Test", children: nil))
                }) {
                    Text("Add")
                }
                .padding(.bottom, 15)
            }
        .navigationBarTitle(Text("Parents"))
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var body: some View {
        let children = appState.parents[parentIndex].children
        return VStack {
            List {
                if (children?.indices != nil) {
                    ForEach (children!.indices, id: \.self) { childIndex in
                        NavigationLink (destination: PuppetsView(parentIndex: self.parentIndex, childIndex: childIndex).environmentObject(self.appState)) {
                            Text(children![childIndex].name)
                        }
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var children = self.appState.parents[self.parentIndex].children
                if (children != nil) {
                    children?.append(Child(name: "Teest"))
                } else {
                    children = [Child(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Children"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children!.remove(atOffsets: indexSet)
        }
    }
}

struct PuppetsView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var childIndex: Int
    var body: some View {
        let child = appState.parents[parentIndex].children?[childIndex]
        return VStack {
            List {
                if (child != nil && child!.puppets?.indices != nil) {
                    ForEach (child!.puppets!.indices, id: \.self) { puppetIndex in
                        Text(self.appState.parents[self.parentIndex].children![self.childIndex].puppets![puppetIndex].name)
                    }
                    .onDelete(perform: deleteItem)
                }
            }
            Button(action: {
                var puppets = self.appState.parents[self.parentIndex].children![self.childIndex].puppets
                if (puppets != nil) {
                   puppets!.append(Puppet(name: "Teest"))
                } else {
                   puppets = [Puppet(name: "Teest")]
                }
            }) {
                Text("Add")
            }
            .padding(.bottom, 15)
        }
        .navigationBarTitle(Text("Puppets"))
    }
    private func deleteItem(at indexSet: IndexSet) {
        if (self.appState.parents[self.parentIndex].children != nil) {
            self.appState.parents[self.parentIndex].children![self.childIndex].puppets!.remove(atOffsets: indexSet)
        }
    }
}

I can remove both children of Foo and FooBar without issues, but when I remove the Puppet of child bar first, then the app crashes like shown in the comments.

I unterstand that the childIndex doesn't exist anymore, but I don't understand why the view gets built again when there is no child with puppets.

Body:
The problem with your optional chaining is that this line produces the result of type Child and not Child?:

appState.parents[parentIndex].children?[childIndex]

And if it's not an optional you can't call puppets on children?[childIndex] without checking if childIndex is valid:

// this will crash when childIndex is out of range
appState.parents[parentIndex].children?[childIndex].puppets?.indices

I recommend to use safeIndex subscript for accessing possible empty elements:

var body: some View {

    let child = appState.parents[safeIndex: parentIndex]?.children?[safeIndex: childIndex]
    return VStack {
        List {
            if (child != nil && child!.puppets?.indices != nil) {
                ForEach ((appState.parents[parentIndex].children?[childIndex].puppets!.indices)!, id: \.self) { puppetIndex in
                    Text(self.appState.parents[self.parentIndex].children![self.childIndex].puppets![puppetIndex].name)
                }
                .onDelete(perform: deleteItem)
            }
        }
    ...
}

To do this you would need an Array extension which allows to access array elements in a safe way (ie. return nil instead of throwing an error):

extension Array {
    public subscript(safeIndex index: Int) -> Element? {
        guard index >= 0, index < endIndex else {
            return nil
        }

        return self[index]
    }
}

Note: You'd need to do the same for the ParentView, so in overall Paulw11's answer is cleaner.


问:
How to pass state to LinearStepper in reactjs?
This is my constructor where my variable is, all i want is to pass this variable in HorizontalLinearStepper...

```<code>export class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      area: null,
    };
  }
</code>```

I succesfyllu get the value and set it to this.state.area

```<code> var Area = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
        var area1 = L.GeometryUtil.formattedNumber(Area * 0.001) + "  m²";
        console.log(area1);
        this.setState({
          area: area1,
        });
</code>```

This is how on step 1 i give my component Dashboard

```<code>case 1:
        return (
          <div style={{ padding: "2% 0" }}>
            <Typography variant="h4">Find your land on the map</Typography>
            <AlertNoPoly errorStatusPolly={errorStatusPolly} />
            <ul>
              <li>
                Find your land on the map and mark it using the map tools.
              </li>
              <li>Or upload a digital file of your land</li>
            </ul>
            <Dashboard viewMap={viewMap}  area={area} />
          </div>
        );
</code>```

Now my problems is that from the stepper to Dashboard no problems to pass a variable with its value but how to make from Dashboard to stepper to pass variable?

答:
If i understood your question correctly - here is an example of passing value from parent to child

```<code>const Stepper = props => {
  const childValueHandler = (childValue) => {
    // do what you want with childValue
  }

  return <Dashboard childValueHandler={childValueHandler} />
}
</code>```

so inside Dashboard you just call props.childValueHandler passing value as argument

Body:
This is my constructor where my variable is, all i want is to pass this variable in HorizontalLinearStepper...

export class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      area: null,
    };
  }

I succesfyllu get the value and set it to this.state.area

 var Area = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
        var area1 = L.GeometryUtil.formattedNumber(Area * 0.001) + "  m²";
        console.log(area1);
        this.setState({
          area: area1,
        });

This is how on step 1 i give my component Dashboard

case 1:
        return (

            <Typography variant="h4">Find your land on the map</Typography>
            <AlertNoPoly errorStatusPolly={errorStatusPolly} />

                Find your land on the map and mark it using the map tools.

Or upload a digital file of your land

            <Dashboard viewMap={viewMap}  area={area} />

        );

Now my problems is that from the stepper to Dashboard no problems to pass a variable with its value but how to make from Dashboard to stepper to pass variable?

Body:
If i understood your question correctly - here is an example of passing value from parent to child

const Stepper = props => {
  const childValueHandler = (childValue) => {
    // do what you want with childValue
  }

  return <Dashboard childValueHandler={childValueHandler} />
}

so inside Dashboard you just call props.childValueHandler passing value as argument


问:
AWS Glue ETL job from AWS Redshift to S3 fails
I am trying out AWS Glue service to ETL some data from redshift to S3. Crawler runs successfully and creates the meta table in data catalog, however when I run the ETL job ( generated by AWS ) it fails after around 20 minutes saying "Resource unavailable".

I cannot see AWS glue logs or error logs created in Cloudwatch. When I try to view them it says "Log stream not found. The log stream jr_xxxxxxxxxx could not be found. Check if it was correctly created and retry."

I would appreciate it if you could provide any guidance to resolve this issue.

答:
I have recently struggled with Resource Unavailable thrown by Glue Job

Also i was not able to make a direct connection in Glue using RDS -it said "no suitable security group found"

I faced this issue while trying to connect with AWS RDS and Redshift

The problem was with the Security Group that the Redshift was using. There is a need to place a self referencing inbound rule in the Security Group.

For those who dont know what is self referencing inbound rule, follow the steps

1) Go to the Security Group you are using (VPC -> Security Group)

2) In the Inbound Rules select Edit Inbound Rules

3) Add a Rule

a) Type - All Traffic b) Protocol - All c) Port Range - ALL d) Source - custom and in space available write the initial of your security group and select it. e) Save it.

Its done !

if you were missing this condition in your Security Group Inbound Rules

Try creating the connection you will be able to create the connection.

Also job should work this time.


问:
update data frame based on data from another data frame using pandas python
I have two data frames df1 and df2. Both have first column common SKUCode=SKU

df1:

df2:

I want to update df1 and set SKUStatus=0 if SKUCode matches SKU in df2.

I want to add new row to df1 if SKU from df2 has no match to SKUCode.

So after the operation df1 looks like following:

One way I could get this done is via df2.iterrows() and looping through values however I think there must be another neat way of doing this?
Thank you

```<code>import pandas as pdx

df1=pdx.DataFrame({'SKUCode':['A','B','C','D'],'ListPrice':[1798,2997,1798,999],'SalePrice':[1798,2997,1798,999],'SKUStatus':[1,1,1,0],'CostPrice':[500,773,525,300]})

df2=pdx.DataFrame({'SKUCode':['X','Y','B'],'Status':[0,0,0],'e_date':['31-05-2020','01-06-2020','01-06-2020']})

df1.merge(df2,left_on='SKUCode')
</code>```

答:
I'm not sure exactly if I understood you correctly but I think you can use .loc. something along the lines of:

```<code>df1.loc[df2['SKUStatu'] != 0, 'SKUStatus'] = 1
</code>```

Body:
I have two data frames df1 and df2. Both have first column common SKUCode=SKU

df1:

df2:

I want to update df1 and set SKUStatus=0 if SKUCode matches SKU in df2.

I want to add new row to df1 if SKU from df2 has no match to SKUCode.

So after the operation df1 looks like following:

One way I could get this done is via df2.iterrows() and looping through values however I think there must be another neat way of doing this?
Thank you

import pandas as pdx

df1=pdx.DataFrame({'SKUCode':['A','B','C','D'],'ListPrice':[1798,2997,1798,999],'SalePrice':[1798,2997,1798,999],'SKUStatus':[1,1,1,0],'CostPrice':[500,773,525,300]})

df2=pdx.DataFrame({'SKUCode':['X','Y','B'],'Status':[0,0,0],'e_date':['31-05-2020','01-06-2020','01-06-2020']})

df1.merge(df2,left_on='SKUCode')

Body:
I'm not sure exactly if I understood you correctly but I think you can use .loc. something along the lines of:

df1.loc[df2['SKUStatu'] != 0, 'SKUStatus'] = 1


问:
Trying to get my
 to fill out the bottom of my container using Flexbox
Utter beginner here.

I'm trying to get my nav bar list items to spread evenly along the bottom of the nav container.
I'm trying to do this specifically in flexbox. Justify-content: space-between; is what I've been trying but it doesn't seem to wanna play the game.

Code included below

Any ideas as to how I can achieve this with flexbox?

Thank you for taking the time to read this

Have a good day
Johnathan

@import url('https://fonts.googleapis.com/css2?family=Tenali+Ramakrishna&display=swap');
/*font-family: 'Tenali Ramakrishna', sans-serif;*/

* { /*Hugs border to edges of screen */
  margin: 0;
  padding: 0;
}

body{

 padding: 40px;
 overflow-x: hidden; /* For Opera */

 -webkit-box-shadow:
  inset #19d4ff 0 0 0 5px,
  inset #18cdf7 0 0 0 1px,
  inset #53dfff 0 0 0 10px,
  inset #50d8f7 0 0 0 11px,
  inset #8ce9ff 0 0 0 16px,
  inset #88e2f7 0 0 0 17px,
  inset #c5f4ff 0 0 0 22px,
  inset #bfecf7 0 0 0 23px;
 -moz-box-shadow:
  inset #19d4ff 0 0 0 5px,
  inset #18cdf7 0 0 0 1px,
  inset #53dfff 0 0 0 10px,
  inset #50d8f7 0 0 0 11px,
  inset #8ce9ff 0 0 0 16px,
  inset #88e2f7 0 0 0 17px,
  inset #c5f4ff 0 0 0 22px,
  inset #bfecf7 0 0 0 23px;
  box-shadow:
  inset #19d4ff 0 0 0 5px,
  inset #18cdf7 0 0 0 1px,
  inset #53dfff 0 0 0 10px,
  inset #50d8f7 0 0 0 11px,
  inset #8ce9ff 0 0 0 16px,
  inset #88e2f7 0 0 0 17px,
  inset #c5f4ff 0 0 0 22px,
  inset #bfecf7 0 0 0 23px;
  font-family: 'Tenali Ramakrishna', sans-serif;
  text-align: center;
}

header{
 display: flex;
  /*Lovely Gold*/
}

nav{
  padding: 0;
  background-color: #fcba03;

        display: -webkit-flex;
        display: flex;
        -webkit-flex-direction: column;
        flex-direction: column;
        -webkit-align-items: center;
        align-items: center;

  width: 100%; /*Nav is filling 100% of it's available container*/
}

#header-img{

}

#title{
  font-size: 42px;
}

nav ul{

        display: -webkit-flex;
        display: flex;
        -webkit-flex-direction: row;
        flex-direction: row;
        justify-content: flex-start;
}

a, li {
  display: flex;
  justify-content: flex-start;
  font-family: 'Tenali Ramakrishna', sans-serif;
  font-weight: 400;
  font-size: 32px;
  text-decoration: none;
}

/* w3 schools- https://www.w3schools.com/css/tryit.asp?filename=trycss_mediaqueries_navbar
Parts have been edited*/

 a:hover{
  color: blue;
  transform: scale(1.1);
}

  @media screen and (max-width: 600px) {
  .nav a {
    float: none;
    width: 100%;
  }
}
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>

<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<body>

<header id="header">

    <nav id="nav-bar">

        <img class="logo" src="http://pngimg.com/uploads/sun/sun_PNG13450.png" id="header-img" alt="SunLogo">

      <div id="title">
        <h1> Vitamin D </h1>
      </div>

      <ul>
        <li>Video</li>
        <li>Benefits</li>
        <li>How It Works</li>

      </ul>
    </nav>

</header></code>```

答:
This is because the ul generally will occupy the space based on its inner elements box size. So the maximum width of it will be the summation width of its li. To make it work you should specify its width to let it know how much space should it fill.

So just add width: 100%; to your stylesheet like this:

```<code>nav ul {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
}
</code>```

Then your final code should be something like this:

@import url("https://fonts.googleapis.com/css2?family=Tenali+Ramakrishna&display=swap");

/*font-family: 'Tenali Ramakrishna', sans-serif;*/

* {
  /*Hugs border to edges of screen */
  margin: 0;
  padding: 0;
}

body {
  padding: 40px;
  overflow-x: hidden;
  /* For Opera */
  -webkit-box-shadow: inset #19d4ff 0 0 0 5px, inset #18cdf7 0 0 0 1px, inset #53dfff 0 0 0 10px, inset #50d8f7 0 0 0 11px, inset #8ce9ff 0 0 0 16px, inset #88e2f7 0 0 0 17px, inset #c5f4ff 0 0 0 22px, inset #bfecf7 0 0 0 23px;
  -moz-box-shadow: inset #19d4ff 0 0 0 5px, inset #18cdf7 0 0 0 1px, inset #53dfff 0 0 0 10px, inset #50d8f7 0 0 0 11px, inset #8ce9ff 0 0 0 16px, inset #88e2f7 0 0 0 17px, inset #c5f4ff 0 0 0 22px, inset #bfecf7 0 0 0 23px;
  box-shadow: inset #19d4ff 0 0 0 5px, inset #18cdf7 0 0 0 1px, inset #53dfff 0 0 0 10px, inset #50d8f7 0 0 0 11px, inset #8ce9ff 0 0 0 16px, inset #88e2f7 0 0 0 17px, inset #c5f4ff 0 0 0 22px, inset #bfecf7 0 0 0 23px;
  font-family: "Tenali Ramakrishna", sans-serif;
  text-align: center;
}

header {
  display: flex;
  /*Lovely Gold*/
}

nav {
  padding: 0;
  background-color: #fcba03;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
  -webkit-align-items: center;
  align-items: center;
  width: 100%;
  /*Nav is filling 100% of it's available container*/
}

#header-img {}

#title {
  font-size: 42px;
}

nav ul {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
}

a,
li {
  display: flex;
  justify-content: flex-start;
  font-family: "Tenali Ramakrishna", sans-serif;
  font-weight: 400;
  font-size: 32px;
  text-decoration: none;
}

/* w3 schools- https://www.w3schools.com/css/tryit.asp?filename=trycss_mediaqueries_navbar
Parts have been edited*/

a:hover {
  color: blue;
  transform: scale(1.1);
}

@media screen and (max-width: 600px) {
  .nav a {
    float: none;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>

<body>

  <header id="header">

    <nav id="nav-bar">

      <img class="logo" src="http://pngimg.com/uploads/sun/sun_PNG13450.png" id="header-img" alt="SunLogo">

      <div id="title">
        <h1> Vitamin D </h1>
      </div>

      <ul>
        <li>Video</li>
        <li>Benefits</li>
        <li>How It Works</li>

      </ul>
    </nav>

  </header></code>```

Title: Trying to get my <ul> to fill out the bottom of my container using Flexbox

Body:
Utter beginner here.

I'm trying to get my nav bar list items to spread evenly along the bottom of the nav container.
I'm trying to do this specifically in flexbox. Justify-content: space-between; is what I've been trying but it doesn't seem to wanna play the game.

Code included below

Any ideas as to how I can achieve this with flexbox?

Thank you for taking the time to read this

Have a good day
Johnathan

@import url('https://fonts.googleapis.com/css2?family=Tenali+Ramakrishna&display=swap');
/*font-family: 'Tenali Ramakrishna', sans-serif;*/

* { /*Hugs border to edges of screen */
  margin: 0;
  padding: 0;
}

body{

 padding: 40px;
 overflow-x: hidden; /* For Opera */

 -webkit-box-shadow:
  inset #19d4ff 0 0 0 5px,
  inset #18cdf7 0 0 0 1px,
  inset #53dfff 0 0 0 10px,
  inset #50d8f7 0 0 0 11px,
  inset #8ce9ff 0 0 0 16px,
  inset #88e2f7 0 0 0 17px,
  inset #c5f4ff 0 0 0 22px,
  inset #bfecf7 0 0 0 23px;
 -moz-box-shadow:
  inset #19d4ff 0 0 0 5px,
  inset #18cdf7 0 0 0 1px,
  inset #53dfff 0 0 0 10px,
  inset #50d8f7 0 0 0 11px,
  inset #8ce9ff 0 0 0 16px,
  inset #88e2f7 0 0 0 17px,
  inset #c5f4ff 0 0 0 22px,
  inset #bfecf7 0 0 0 23px;
  box-shadow:
  inset #19d4ff 0 0 0 5px,
  inset #18cdf7 0 0 0 1px,
  inset #53dfff 0 0 0 10px,
  inset #50d8f7 0 0 0 11px,
  inset #8ce9ff 0 0 0 16px,
  inset #88e2f7 0 0 0 17px,
  inset #c5f4ff 0 0 0 22px,
  inset #bfecf7 0 0 0 23px;
  font-family: 'Tenali Ramakrishna', sans-serif;
  text-align: center;
}

header{
 display: flex;
  /*Lovely Gold*/
}

nav{
  padding: 0;
  background-color: #fcba03;

        display: -webkit-flex;
        display: flex;
        -webkit-flex-direction: column;
        flex-direction: column;
        -webkit-align-items: center;
        align-items: center;

  width: 100%; /*Nav is filling 100% of it's available container*/
}

#header-img{

}

#title{
  font-size: 42px;
}

nav ul{

        display: -webkit-flex;
        display: flex;
        -webkit-flex-direction: row;
        flex-direction: row;
        justify-content: flex-start;
}

a, li {
  display: flex;
  justify-content: flex-start;
  font-family: 'Tenali Ramakrishna', sans-serif;
  font-weight: 400;
  font-size: 32px;
  text-decoration: none;
}

/* w3 schools- https://www.w3schools.com/css/tryit.asp?filename=trycss_mediaqueries_navbar
Parts have been edited*/

 a:hover{
  color: blue;
  transform: scale(1.1);
}

  @media screen and (max-width: 600px) {
  .nav a {
    float: none;
    width: 100%;
  }
}

<!doctype html>

 Vitamin D

Video

Benefits

How It Works

Body:
This is because the ul generally will occupy the space based on its inner elements box size. So the maximum width of it will be the summation width of its li. To make it work you should specify its width to let it know how much space should it fill.

So just add width: 100%; to your stylesheet like this:

nav ul {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
}

Then your final code should be something like this:

@import url("https://fonts.googleapis.com/css2?family=Tenali+Ramakrishna&display=swap");

/*font-family: 'Tenali Ramakrishna', sans-serif;*/

* {
  /*Hugs border to edges of screen */
  margin: 0;
  padding: 0;
}

body {
  padding: 40px;
  overflow-x: hidden;
  /* For Opera */
  -webkit-box-shadow: inset #19d4ff 0 0 0 5px, inset #18cdf7 0 0 0 1px, inset #53dfff 0 0 0 10px, inset #50d8f7 0 0 0 11px, inset #8ce9ff 0 0 0 16px, inset #88e2f7 0 0 0 17px, inset #c5f4ff 0 0 0 22px, inset #bfecf7 0 0 0 23px;
  -moz-box-shadow: inset #19d4ff 0 0 0 5px, inset #18cdf7 0 0 0 1px, inset #53dfff 0 0 0 10px, inset #50d8f7 0 0 0 11px, inset #8ce9ff 0 0 0 16px, inset #88e2f7 0 0 0 17px, inset #c5f4ff 0 0 0 22px, inset #bfecf7 0 0 0 23px;
  box-shadow: inset #19d4ff 0 0 0 5px, inset #18cdf7 0 0 0 1px, inset #53dfff 0 0 0 10px, inset #50d8f7 0 0 0 11px, inset #8ce9ff 0 0 0 16px, inset #88e2f7 0 0 0 17px, inset #c5f4ff 0 0 0 22px, inset #bfecf7 0 0 0 23px;
  font-family: "Tenali Ramakrishna", sans-serif;
  text-align: center;
}

header {
  display: flex;
  /*Lovely Gold*/
}

nav {
  padding: 0;
  background-color: #fcba03;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
  -webkit-align-items: center;
  align-items: center;
  width: 100%;
  /*Nav is filling 100% of it's available container*/
}

#header-img {}

#title {
  font-size: 42px;
}

nav ul {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
}

a,
li {
  display: flex;
  justify-content: flex-start;
  font-family: "Tenali Ramakrishna", sans-serif;
  font-weight: 400;
  font-size: 32px;
  text-decoration: none;
}

/* w3 schools- https://www.w3schools.com/css/tryit.asp?filename=trycss_mediaqueries_navbar
Parts have been edited*/

a:hover {
  color: blue;
  transform: scale(1.1);
}

@media screen and (max-width: 600px) {
  .nav a {
    float: none;
    width: 100%;
  }
}

<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>

<body>

  <header id="header">

    <nav id="nav-bar">

      <img class="logo" src="http://pngimg.com/uploads/sun/sun_PNG13450.png" id="header-img" alt="SunLogo">

      <div id="title">
        <h1> Vitamin D </h1>
      </div>

      <ul>
        <li><a class="nav-link" href="#video">Video</a></li>
        <li><a class="nav-link" href="#benefits">Benefits</a></li>
        <li><a class="nav-link" href="#how-it-works">How It Works</a></li>

      </ul>
    </nav>

  </header>


问:
Encode formatting information into a Google Sheets or Excel formula
I'm using an Excel document opened in Google Sheets. I understand that either Google Sheets syntax or Excel syntax may therefore be used, so either style would be useful to me here.

I'm have a cell which compares two durations.

For example:

Cell 1 = 01:05

  Cell 2 = 01:15

  Cell 3 = 00:10 [RED]

If Cell 2's duration is greater than cell 1's then cell 3 should be colored red. If not, then green.

I can't do this using conditional formatting because the cell 3 is always a positive number, so I have to following formula to compute cell 3 (which is placed in cell 3:

```<code>=IF(C2 > C1, [RED]C2 - C1, [GREEN]C1 - C2)
</code>```

The above is producing the correct values with the colors removed, but but the can't find away to
implement the red and green successfully. If the colors are included it gives a parsing error.

答:
Set the fill colour of C3 to green then in conditional formatting for C3 use custom formula:

```<code>=C2>C1
</code>```

with fill colour red.

Body:
I'm using an Excel document opened in Google Sheets. I understand that either Google Sheets syntax or Excel syntax may therefore be used, so either style would be useful to me here.

I'm have a cell which compares two durations.

For example:

Cell 1 = 01:05

  Cell 2 = 01:15

  Cell 3 = 00:10 [RED]

If Cell 2's duration is greater than cell 1's then cell 3 should be colored red. If not, then green.

I can't do this using conditional formatting because the cell 3 is always a positive number, so I have to following formula to compute cell 3 (which is placed in cell 3:

=IF(C2 > C1, [RED]C2 - C1, [GREEN]C1 - C2)

The above is producing the correct values with the colors removed, but but the can't find away to
implement the red and green successfully. If the colors are included it gives a parsing error.

Body:
Set the fill colour of C3 to green then in conditional formatting for C3 use custom formula:

=C2>C1

with fill colour red.


问:
power bi : cloned report not showing data in visualizations
I am new to PowerBI and trying to copy/clone an existing report to new one with new dataset.

Here is the scenario:

I already have a report and dataset imported with .pbix file.

Now, I got new csv data, and I have created entirely new dataset using REST api.

At this point, I want to copy existing report and point it to newly created dataset.

I have tried following approaches:

Clone Report with new dataset:

used clone report api with datasetId pointing to new data set

Clone Report and then Rebind:

used clone report api without datasetId param

used Rebind api to bind newly cloned report to new dataset

However, with both of above, the report or its visualisations are not populated. It is showing error Something's wrong with one or more fields.

Here is how the cloned report looks:

I have been struggling with this since couple of days.

Thanks for help in adv.

答:
I was able to solve this using below mentioned approach.

Posting it here so that someday it will help someone.

tl;dr:-> clone source report via api with new dataset, then manually fix the cloned report visualisations, and then use this fixed report as source for cloning as and when required.

Clone report approach worked for me:

Let's assume we have a source report say 'ReportA' linked to dataset 'DatasetA'.

Now, create a new app workspace say 'WS_B'.

Create a new dataset in WS_B with name 'DatasetB' having tables similar to 'DatasetA'

Clone report 'ReportA' into 'WS_B' with new dataset 'DatasetB', using clone_report_api. Call cloned report as 'ReportB'

After cloning, manually edit the ReportB and fix the visualisations by setting correct legends, values, x & y axis sources, etc. And, save the report.

Now, in your subsequent cloning usecases, use this 'ReportB' report as source report with new datasets created by apis.

With this, you will get a working cloned report, without any manual intervention anymore.


问:
Postman not shows my exception for non existing parameter in GET method
I used SpringBoot REST api with MongDB.
And I use docker compose.
In the part of Docker all are fine but in the Postman when I have GET method, if there is not exist the parameter, it is not show me the error.why?
For example:
In GET method, if the score is not exist the method should throw my exception. But it doese not work.

The GET method:

```<code>@GetMapping("/{score}")
        public ResponseEntity<?>  getScore(@PathParam("score") Long score){
            //Query query = new Query();
            //new Criteria();
            //query.addCriteria(Criteria.where("score").is(score));

            try {

                List<Score> sc = srepo.findByScoresc(score);
                        //mongoTemplate.find(query, Score.class);
                return ResponseEntity.ok(sc);

            } catch (Exception e) {
                return ResponseEntity.status(404).body("Not found!");
            }

        }
</code>```

this is Postman:

答: No data doesn't mean exception. The sc variable will have 0 size. so you get a blank array in return

Body:
I used SpringBoot REST api with MongDB.
And I use docker compose.
In the part of Docker all are fine but in the Postman when I have GET method, if there is not exist the parameter, it is not show me the error.why?
For example:
In GET method, if the score is not exist the method should throw my exception. But it doese not work.

The GET method:

@GetMapping("/{score}")
        public ResponseEntity<?>  getScore(@PathParam("score") Long score){
            //Query query = new Query();
            //new Criteria();
            //query.addCriteria(Criteria.where("score").is(score));

            try {

                List<Score> sc = srepo.findByScoresc(score);
                        //mongoTemplate.find(query, Score.class);
                return ResponseEntity.ok(sc);

            } catch (Exception e) {
                return ResponseEntity.status(404).body("Not found!");
            }

        }

this is Postman:


问:
Where my application's database is stored
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.</p>

```<code>SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");
</code>```

答:
The Default location of the SQLLiteDatabase is </p>

```<code>   /data/data/ur packeage/databases
</code>```

Body:
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.

SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");

Body:
The Default location of the SQLLiteDatabase is

   /data/data/ur packeage/databases


问:
How do I split a string by a whitespace after a bracket and keep the bracket in the same line
I have an array of strings that look like the following:

```<code>const stringArray = [
    'string1[1] string2[2] string3[3] [4 5]',
    'string6[6] string7[7] string8[8] [9 10]'
];
</code>```

I want to be able to separate each string into four rows (in this case, because there are 4 columns). So the array would end up like:

```<code>const splittedArray = [
    [
        'string1[1]',
        'string2[2]',
        'string3[3]',
        '[4 5]'
    ],
    [
        'string6[6]',
        'string7[7]',
        'string8[8]',
        '[9 10]'
    ]
]
</code>```

I've been searching and trying regex even though I am not a fan of it as it is unreadable, but it does not seem to be working.

Whenever I try /(?=\])\s/g it does not separate the string, whenever I try /(?=\])\s*/ it separates the string and keeps both the ] and the whitespace, but does so in the next line (and well, keeps the whitespace).

I can't seem to find a way to do what I want, but perhaps I'm just miss understanding something. Perhaps there is a simpler way to do this. Splitting after the ] without needing to check for a space would be ideal but I would still have the problem of keeping the bracket and not splitting an extra time on that last ] hence why I'm trying this solution.

Here is a little code snipper with what I have and what it returns:

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/(?=\])\s/g));

console.log(splittedStringArray);

const anotherSplittedStringArray = stringArray.map(string => string.split(/(?=\])\s*/g));

console.log(anotherSplittedStringArray);

const splittedByBrackets = stringArray.map(string => string.split(/(?=\])/));

// The same as the previous one
console.log(splittedByBrackets);```

For my case, the answer was: /\w*\[.*?\]/g (with match instead of split) by Thomas. From what I understood:

The \w* matches any word (0 or more times)

The \[ matches the [ after a word (or no word, above condition)

The .*? matches any character excluding line breaks (0 or more times) lazyly, I believe the ? is to tell to stop matching on the first character(s) otherwise it would search the whole string.

The \] matches the ] after what is after the other bracket (which is the above condition).

The /g flag makes it so it searched for more than one occurrence.

答:
Instead of splitting by what you don't want, you could also match the parts that you want.

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.match(/\w*\[.*?\]/g));

console.log(splittedStringArray);```

Body:
I have an array of strings that look like the following:

const stringArray = [
    'string1[1] string2[2] string3[3] [4 5]',
    'string6[6] string7[7] string8[8] [9 10]'
];

I want to be able to separate each string into four rows (in this case, because there are 4 columns). So the array would end up like:

const splittedArray = [
    [
        'string1[1]',
        'string2[2]',
        'string3[3]',
        '[4 5]'
    ],
    [
        'string6[6]',
        'string7[7]',
        'string8[8]',
        '[9 10]'
    ]
]

I've been searching and trying regex even though I am not a fan of it as it is unreadable, but it does not seem to be working.

Whenever I try /(?=\])\s/g it does not separate the string, whenever I try /(?=\])\s*/ it separates the string and keeps both the ] and the whitespace, but does so in the next line (and well, keeps the whitespace).

I can't seem to find a way to do what I want, but perhaps I'm just miss understanding something. Perhaps there is a simpler way to do this. Splitting after the ] without needing to check for a space would be ideal but I would still have the problem of keeping the bracket and not splitting an extra time on that last ] hence why I'm trying this solution.

Here is a little code snipper with what I have and what it returns:

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/(?=\])\s/g));

console.log(splittedStringArray);

const anotherSplittedStringArray = stringArray.map(string => string.split(/(?=\])\s*/g));

console.log(anotherSplittedStringArray);

const splittedByBrackets = stringArray.map(string => string.split(/(?=\])/));

// The same as the previous one
console.log(splittedByBrackets);

For my case, the answer was: /\w*\[.*?\]/g (with match instead of split) by Thomas. From what I understood:

The \w* matches any word (0 or more times)

The \[ matches the [ after a word (or no word, above condition)

The .*? matches any character excluding line breaks (0 or more times) lazyly, I believe the ? is to tell to stop matching on the first character(s) otherwise it would search the whole string.

The \] matches the ] after what is after the other bracket (which is the above condition).

The /g flag makes it so it searched for more than one occurrence.


问:
Can't get charts to vertically autofit screen, despite using height=100% or autofit
So i’m new to plotly, and can’t seem to find a fix for this issue. I have four charts that I want displayed in a column, at full screen, i.e., i want to see all four charts vertically, without having to scroll.

When i plot them, however, I end up having to scroll down. I have tried setting size=100% or autofit=True, but neither worked - the column in which the charts are displayed is still too big for the screen, and i need to scroll. However, when i used width=50%, that worked; the charts only take half the width of the screen, but i still need to scroll down to view them all. I have listed my code below.

Any help here would be greatly appreciated

```<code>app = dash.Dash()

app.layout = html.Div([
    # State
    html.Div([
        html.H1(id='map-header',children='State'),
        dcc.Graph(id='map-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'State'}}),
    # Business Units
    html.Div([
        html.H1(id='bu-header',children='Business Units'),
        dcc.Graph(id='bu-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Business Unit'}})
    ]),
    # Job Family
    html.Div([
        html.H1(id='jf-header',children='Job Family'),
        dcc.Graph(id='jf-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Job Family'}})
    ]),
    # Job Level
    html.Div([
        html.H1(id='fl-header',children='Job Level'),
        dcc.Graph(id='jl-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Job Level'}})
    ])
    ])

],style={'width':'50%'})

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

答:
You can change the height of each graph to 100 by adding 'height':'100' inside the dcc.graph part like so:

```<code>dcc.Graph(id='jl-graph',
              figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Job Level', 'height':'100'}})
</code>```

But do remember, that there is a possibility that the graph would not look readable this way. Alternately I suggest, that you use other layout components of dash, like rows and columns, or cards, and add your graph inside these components, then they resize to fit that container in which they are.

Body:
So i’m new to plotly, and can’t seem to find a fix for this issue. I have four charts that I want displayed in a column, at full screen, i.e., i want to see all four charts vertically, without having to scroll.

When i plot them, however, I end up having to scroll down. I have tried setting size=100% or autofit=True, but neither worked - the column in which the charts are displayed is still too big for the screen, and i need to scroll. However, when i used width=50%, that worked; the charts only take half the width of the screen, but i still need to scroll down to view them all. I have listed my code below.

Any help here would be greatly appreciated

app = dash.Dash()

app.layout = html.Div([
    # State
    html.Div([
        html.H1(id='map-header',children='State'),
        dcc.Graph(id='map-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'State'}}),
    # Business Units
    html.Div([
        html.H1(id='bu-header',children='Business Units'),
        dcc.Graph(id='bu-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Business Unit'}})
    ]),
    # Job Family
    html.Div([
        html.H1(id='jf-header',children='Job Family'),
        dcc.Graph(id='jf-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Job Family'}})
    ]),
    # Job Level
    html.Div([
        html.H1(id='fl-header',children='Job Level'),
        dcc.Graph(id='jl-graph',
                  figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Job Level'}})
    ])
    ])

],style={'width':'50%'})

if __name__ == '__main__':
    app.run_server()

Body:
You can change the height of each graph to 100 by adding 'height':'100' inside the dcc.graph part like so:

dcc.Graph(id='jl-graph',
              figure={'data':[{'x':[3,2],'y':[7,12]}],'layout':{'title':'Job Level', 'height':'100'}})

But do remember, that there is a possibility that the graph would not look readable this way. Alternately I suggest, that you use other layout components of dash, like rows and columns, or cards, and add your graph inside these components, then they resize to fit that container in which they are.


问:
ACF repeater order by date sub field
I have been trying to order my ACF subfields by date order, however it isn't working quite right. It should go

01/06/2020
20/05/2020
14/05/2020
10/05/2020

but it currently goes

01/06/2020
10/05/2020
14/05/2020
20/05/2020

this is my code, can someone please tell me where I have gone wrong?

```<code><section class="news-updates">
        <?php
    $repeater = get_field('news_repeater');
    $order = array();

    if( $repeater ):
        foreach( $repeater as $i => $row ) {

            $eventdate = $row['news_date'];
            $order[ $i ] = $eventdate;

        }
    array_multisort( $order, SORT_ASC, $repeater );
?>

        <table class="news">
            <?php foreach( $repeater as $i => $row ): ?>
            <?php
                $eventdate = $row['news_date'];
             ?>

            <div class="news-item">
                <div class="news-date"><?php echo $eventdate; ?></div>
                <div class="news-content"><?php echo $row['description']; ?></div>
            </div>

            <?php endforeach; ?>
        </table>
        <?php

?>
        <?php endif; ?>
    </section>
</code>```

I have looked all over the internet but can't seem to figure it out.

答:
Did you tried</p>

```<code>array_multisort( $order, SORT_ASC, $repeater );
</code>```

Title: ACF repeater order by date sub field

Body:
I have been trying to order my ACF subfields by date order, however it isn't working quite right. It should go

01/06/2020
20/05/2020
14/05/2020
10/05/2020

but it currently goes

01/06/2020
10/05/2020
14/05/2020
20/05/2020

this is my code, can someone please tell me where I have gone wrong?

        <?php
    $repeater = get_field('news_repeater');
    $order = array();

    if( $repeater ):
        foreach( $repeater as $i => $row ) {

            $eventdate = $row['news_date'];
            $order[ $i ] = $eventdate;

        }
    array_multisort( $order, SORT_ASC, $repeater );
?>

            <?php foreach( $repeater as $i => $row ): ?>
            <?php
                $eventdate = $row['news_date'];
             ?>

<?php echo $eventdate; ?>

<?php echo $row['description']; ?>

            <?php endforeach; ?>

        <?php

?>
        <?php endif; ?>

I have looked all over the internet but can't seem to figure it out.

Body:
Did you tried

array_multisort( $order, SORT_ASC, $repeater );


问:
escaping string - php in html element
i know this is really obvious but i just don't know what I'm missing. </p>

```<code>$option[] = "<option value='user' selected=' " . ($row[5]=='admin') ? echo 'selected' : null. "'>user </option>";`
</code>```

<p>thanks </p>

答:
You do not need to write

```<code>value=\'user\'
</code>```

Just do

```<code>value='user'
</code>```

Escaping is needed when you use the same quote marks like:

```<code>echo 'Mark\'s dinner';
</code>```

Title: escaping string - php in html element

Body:
i know this is really obvious but i just don't know what I'm missing.

$option[] = "<option value='user' selected=' " . ($row[5]=='admin') ? echo 'selected' : null. "'>user </option>";`

thanks

Body:
You do not need to write

value=\'user\'

Just do

value='user'

Escaping is needed when you use the same quote marks like:

echo 'Mark\'s dinner';


问:
PostgreSQL: how to install plpythonu extension
I'm running PostgreSQL 9.3.1 on Ubuntu 12.04.4.  I'd like to use the plpython language extension but I get an error when I try to use it I get:

ERROR:  language "plpythonu" does not exist

When I try to create the extension:

CREATE EXTENSION plpythonu
```
<p>I get <code>ERROR: could not access file "$libdir/plpython2": No such file or directory</code>
After much searching and digging through blog posts, I've tried installing additional packages, and have copied all the plpython files from /usr/share/postgresql/9.1/extension to /opt/bitnami/postgresql/share/extension where PostgreSQL seems to be looking for them. That at least got me to a point at which PostgreSQL actually <em>sees</em> the available extensions. When I run:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT name, default_version, installed_version FROM pg_available_extensions WHERE name LIKE('plpy*')
</code>```

I get :

```<code>    name    | default_version | installed_version
------------+-----------------+-------------------
 plpython2u | 1.0             |
 plpython3u | 1.0             |
 plpythonu  | 1.0             |
</code>```

There are still no plpython libraries that I can see in /opt/bitnami/postgresql/lib. Can anybody help me get through remaining steps to make the extension work? Thanks in advance!

答:
I'm running Raspbian 10 (buster) / Linux raspberrypi 4.19.97-v7+ #1294 and ran the following commands to install PL/Python 3 on PostgreSQL 11.7.

Identify which versions are available for install:

```<code>pi@raspberrypi:~/$ sudo apt-cache search ".*plpython3.*"
postgresql-plpython3-11 - PL/Python 3 procedural language for PostgreSQL 11
</code>```

sudo apt-get install postgresql-contrib postgresql-plpython3-11

sudo systemctl start postgresql (or use enable to start this at every startup, see Getting started with PostgreSQL on Linux) on stand-alone Linux or sudo service postgresql start (on WSL2).

Else, you would get the error:

```<code>psql: error: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

sudo su - postgres

psql

CREATE EXTENSION plpython3u;

Verify with command:

```<code>select * from pg_language;
</code>```

Body:
I'm running PostgreSQL 9.3.1 on Ubuntu 12.04.4.  I'd like to use the plpython language extension but I get an error when I try to use it I get:

ERROR:  language "plpythonu" does not exist

When I try to create the extension:

CREATE EXTENSION plpythonu

I get ERROR: could not access file "$libdir/plpython2": No such file or directory
After much searching and digging through blog posts, I've tried installing additional packages, and have copied all the plpython files from /usr/share/postgresql/9.1/extension to /opt/bitnami/postgresql/share/extension where PostgreSQL seems to be looking for them. That at least got me to a point at which PostgreSQL actually sees the available extensions. When I run:

SELECT name, default_version, installed_version FROM pg_available_extensions WHERE name LIKE('plpy*')

I get :

    name    | default_version | installed_version
------------+-----------------+-------------------
 plpython2u | 1.0             |
 plpython3u | 1.0             |
 plpythonu  | 1.0             |

There are still no plpython libraries that I can see in /opt/bitnami/postgresql/lib. Can anybody help me get through remaining steps to make the extension work? Thanks in advance!

Body:
I'm running Raspbian 10 (buster) / Linux raspberrypi 4.19.97-v7+ #1294 and ran the following commands to install PL/Python 3 on PostgreSQL 11.7.

Identify which versions are available for install:

pi@raspberrypi:~/$ sudo apt-cache search ".*plpython3.*"
postgresql-plpython3-11 - PL/Python 3 procedural language for PostgreSQL 11

sudo apt-get install postgresql-contrib postgresql-plpython3-11

sudo systemctl start postgresql (or use enable to start this at every startup, see Getting started with PostgreSQL on Linux) on stand-alone Linux or sudo service postgresql start (on WSL2).

Else, you would get the error:

psql: error: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

sudo su - postgres

psql

CREATE EXTENSION plpython3u;

Verify with command:

select * from pg_language;


问:
How to reference a file for StorageFile class in UWP?
In my UWP project I am trying to use Syncfusion's PDF library to fill out a PDF from. In order to open the template that I would like to use I constructed the following code:

```<code>//Browse and chose the file
Windows.Storage.StorageFolder storageFolder
= Windows.Storage.ApplicationData.Current.LocalFolder;

StorageFile file
= await storageFolder.GetFileAsync("/Assets/template.pdf");

//Creates an empty PDF loaded document instance
PdfLoadedDocument loadedDocument = new PdfLoadedDocument();

//Loads or opens an existing PDF document through Open method of PdfLoadedDocument class
await loadedDocument.OpenAsync(file);
</code>```

The PDF, template.pdf, is located inside my Assets library in the project, and it's property "Copy to Output Directory" is set to "Copy always".

Running this code results in the following error: System.ArgumentException: 'Value does not fall within the expected range.'

What would be to correct syntax to use for this problem?

答:
You can try:

var file = await StorageFile.
     GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/template.pdf"));
```

Body:
In my UWP project I am trying to use Syncfusion's PDF library to fill out a PDF from. In order to open the template that I would like to use I constructed the following code:

//Browse and chose the file
Windows.Storage.StorageFolder storageFolder
= Windows.Storage.ApplicationData.Current.LocalFolder;

StorageFile file
= await storageFolder.GetFileAsync("/Assets/template.pdf");

//Creates an empty PDF loaded document instance
PdfLoadedDocument loadedDocument = new PdfLoadedDocument();

//Loads or opens an existing PDF document through Open method of PdfLoadedDocument class
await loadedDocument.OpenAsync(file);

The PDF, template.pdf, is located inside my Assets library in the project, and it's property "Copy to Output Directory" is set to "Copy always".

Running this code results in the following error: System.ArgumentException: 'Value does not fall within the expected range.'

What would be to correct syntax to use for this problem?


答:
You should have a look at pd.merge function [https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html].

First rename a column with the same name (e.g rename SKU to SKUCode). Then try:

```<code>df1.merge(df2, left_on='SKUCode')
</code>```

If you provide input data (not screenshots), I can try with the appropriate parameters.

Title: update data frame based on data from another data frame using pandas python

Body:
I have two data frames df1 and df2. Both have first column common SKUCode=SKU

df1:

df2:

I want to update df1 and set SKUStatus=0 if SKUCode matches SKU in df2.

I want to add new row to df1 if SKU from df2 has no match to SKUCode.

So after the operation df1 looks like following:

One way I could get this done is via df2.iterrows() and looping through values however I think there must be another neat way of doing this?
Thank you

import pandas as pdx

df1=pdx.DataFrame({'SKUCode':['A','B','C','D'],'ListPrice':[1798,2997,1798,999],'SalePrice':[1798,2997,1798,999],'SKUStatus':[1,1,1,0],'CostPrice':[500,773,525,300]})

df2=pdx.DataFrame({'SKUCode':['X','Y','B'],'Status':[0,0,0],'e_date':['31-05-2020','01-06-2020','01-06-2020']})

df1.merge(df2,left_on='SKUCode')

Body:
You should have a look at pd.merge function [https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html].

First rename a column with the same name (e.g rename SKU to SKUCode). Then try:

df1.merge(df2, left_on='SKUCode')

If you provide input data (not screenshots), I can try with the appropriate parameters.


问:
Pip authenticate task creates new value for PIP_INDEX_URL/PIP_EXTRA_INDEX_URL each time the pipeline runs, preventing docker to reuse cached layer
I am using azure devops classic build pipeline's pip authenticate task to create a connection to a private package feed. This task creates environment variables PIP_INDEX_URL and PIP_EXTRA_INDEX_URL.

I am passing the above value as an argument into the dockerfile to configure the package source credentials.

```<code>ARG EXTRA_INDEX_URL
ENV ENV_EXTRA_INDEX_URL ${EXTRA_INDEX_URL}
RUN pip config set global.extra-index-url "$ENV:ENV_EXTRA_INDEX_URL"
RUN pip install -r requirements.txt
</code>```

Azure devops Pip authenticate task creates new value for PIP_INDEX_URL/PIP_EXTRA_INDEX_URL each time the pipeline runs preventing docker to reuse cached layer. Is there any way to allow docker image layer re-use when deriving the credentials using the pip authenticate task?

答:
Azure devops Pip authenticate task creates new value for
  PIP_INDEX_URL/PIP_EXTRA_INDEX_URL each time the pipeline runs
  preventing docker to reuse cached layer. Is there any way to allow
  docker image layer re-use when deriving the credentials using the pip
  authenticate task?

Sorry but I'm afraid the answer is No. It's expected behavior about docker that cached layer won't be reused when the ARG's value gets changed every time. Since the pip authenticate task always creates new temporary credentials each time when the pipeline is triggered, we can't avoid creating the new layers.

The suggestion is that you can put the script above in Dockerfile just before where you need to use those python packages, instead of the very top. This can save some time when the commands above your script can reuse cached layers. You can check this similar post.

Body:
I am using azure devops classic build pipeline's pip authenticate task to create a connection to a private package feed. This task creates environment variables PIP_INDEX_URL and PIP_EXTRA_INDEX_URL.

I am passing the above value as an argument into the dockerfile to configure the package source credentials.

ARG EXTRA_INDEX_URL
ENV ENV_EXTRA_INDEX_URL ${EXTRA_INDEX_URL}
RUN pip config set global.extra-index-url "$ENV:ENV_EXTRA_INDEX_URL"
RUN pip install -r requirements.txt

Azure devops Pip authenticate task creates new value for PIP_INDEX_URL/PIP_EXTRA_INDEX_URL each time the pipeline runs preventing docker to reuse cached layer. Is there any way to allow docker image layer re-use when deriving the credentials using the pip authenticate task?


问:
Convert PEM file to DER
I am currently trying to write a script that allows me to compute the Tor HS address from the hiddens service's private key file.
In order to do this the file needs to be brought into the DER format.

Using OpenSSL this can be done with:

```<code>openssl rsa -in private_key -pubout -outform DER
</code>```

Piping this into python with:

```<code>base64.b32encode(hashlib.sha1(sys.stdin.read()[22:]).digest()[:10]).lower()'
</code>```

will return the address correctly.

However I would like to perform the same using only python. My problem  is that using the pycrypto module the DER output is different and the address therefore incorrect.

```<code>key = RSA.importKey(keyfile.read()).publickey()
print(key.exportKey(format='DER'))
</code>```

Will result in a different output than the openssl call.
Is this just a matter of implementation that allows different results? Or am I making a mistake somewhere?

Any help would be appreciated

答:
I want Convert Certificate file not the key file from DER to PEM, but Google took me here. thanks @alleen1's answer, I can convert certificate or key from DER to PEM and vice versa.

Step one, load the file.

Step two,save it to the format you want.

I ommit the process to get the "pem_data" and "der_data",you can get it from file or anywhere else. they should be bytes not string, use method .encode() when needed.

```<code>from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

# Step one, load the file.

# Load key file
# PEM
key = serialization.load_pem_private_key(pem_data, None, default_backend())
# DER
key = serialization.load_pem_private_key(der_data, None, default_backend())

# Load cert file
# PEM
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
# DER
cert = x509.load_der_x509_certificate(der_data, default_backend())

# Step two,save it to the format you want.
# PEM key
key_val = key.private_bytes(
              serialization.Encoding.PEM,
              serialization.PrivateFormat.TraditionalOpenSSL,
              serialization.NoEncryption()
          )
# DER key
key_val = key.private_bytes(
              serialization.Encoding.DER,
              serialization.PrivateFormat.TraditionalOpenSSL,
              serialization.NoEncryption()
          )

# PEM cert
cert_val = cert.public_bytes(serialization.Encoding.PEM)
# DER cert
cert_val = cert.public_bytes(serialization.Encoding.DER)
</code>```

Title: Convert PEM file to DER

Body:
I am currently trying to write a script that allows me to compute the Tor HS address from the hiddens service's private key file.
In order to do this the file needs to be brought into the DER format.

Using OpenSSL this can be done with:

openssl rsa -in private_key -pubout -outform DER

Piping this into python with:

base64.b32encode(hashlib.sha1(sys.stdin.read()[22:]).digest()[:10]).lower()'

will return the address correctly.

However I would like to perform the same using only python. My problem  is that using the pycrypto module the DER output is different and the address therefore incorrect.

key = RSA.importKey(keyfile.read()).publickey()
print(key.exportKey(format='DER'))

Will result in a different output than the openssl call.
Is this just a matter of implementation that allows different results? Or am I making a mistake somewhere?

Any help would be appreciated

Body:
I want Convert Certificate file not the key file from DER to PEM, but Google took me here. thanks @alleen1's answer, I can convert certificate or key from DER to PEM and vice versa.

Step one, load the file.

Step two,save it to the format you want.

I ommit the process to get the "pem_data" and "der_data",you can get it from file or anywhere else. they should be bytes not string, use method .encode() when needed.

from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

# Step one, load the file.

# Load key file
# PEM
key = serialization.load_pem_private_key(pem_data, None, default_backend())
# DER
key = serialization.load_pem_private_key(der_data, None, default_backend())

# Load cert file
# PEM
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
# DER
cert = x509.load_der_x509_certificate(der_data, default_backend())

# Step two,save it to the format you want.
# PEM key
key_val = key.private_bytes(
              serialization.Encoding.PEM,
              serialization.PrivateFormat.TraditionalOpenSSL,
              serialization.NoEncryption()
          )
# DER key
key_val = key.private_bytes(
              serialization.Encoding.DER,
              serialization.PrivateFormat.TraditionalOpenSSL,
              serialization.NoEncryption()
          )

# PEM cert
cert_val = cert.public_bytes(serialization.Encoding.PEM)
# DER cert
cert_val = cert.public_bytes(serialization.Encoding.DER)