问:
How to fix Device Definitions not responding
I am working on a app and i wanted to view what it looks like on different devices, but it seems like its only my current device definition it allows.
I have tried to inspect it and i found error concerning the implementation of my foreground drawable which it says will not be usable in API lower than version 23 which i made the required changes to them  but i just don't understand it
here is what it shows me:
enter image description here

please how can i fix this issue
hers is what my code looks like:

package com.polawa.glowingagesacademy;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;

public class elearning_page extends AppCompatActivity implements View.OnClickListener {
    private ImageButton mainpagee;
    private ImageButton googleclick;
    private ImageButton khanbutton;
    private ImageButton elearnclick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_elearning_page);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_orange_light"
        tools:context=".elearning_page">

    <ImageButton
        android:id="@+id/mainpagee"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="15dp"
        android:layout_marginRight="15dp"
        android:background="@android:drawable/ic_dialog_dialer"
        app:layout_constraintBottom_toTopOf="@+id/constraintLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.532" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="64dp"
        android:layout_height="80dp"
        android:layout_marginStart="24dp"
        android:layout_marginBottom="76dp"
        android:layout_marginLeft="24dp"
        app:layout_constraintBottom_toTopOf="@+id/constraintLayout"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/logo" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/constraintLayout"
        android:layout_marginStart="36dp"
        android:layout_marginLeft="36dp"
        android:layout_marginEnd="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginBottom="39dp"
        android:layout_toStartOf="@+id/mainpagee"
        android:layout_toLeftOf="@+id/mainpagee"
        android:layout_toEndOf="@+id/imageView2"
        android:layout_toRightOf="@+id/imageView2"
        android:gravity="center"
        android:text="GAA e-Classroom"
        android:textColor="@android:color/secondary_text_light"
        android:textSize="24sp"
        app:fontFamily="casual" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="656dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="-6dp"
        android:background="@drawable/fafaffaf"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView">

        <ImageButton
            android:id="@+id/googleclick"
            style="@android:style/Widget.ImageButton"
            android:layout_width="81dp"
            android:layout_height="70dp"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:background="@drawable/google_classroom_png_4"

            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.046" />

        <ImageButton
            android:id="@+id/khanbutton"
            style="@android:style/Widget.ImageButton"
            android:layout_width="75dp"
            android:layout_height="67dp"
            android:background="@drawable/khan_academy"
            app:layout_constraintStart_toEndOf="@+id/elearnclick"
            app:layout_constraintTop_toTopOf="@+id/elearnclick"
            tools:targetApi="m" />

        <ImageButton
            android:id="@+id/elearnclick"
            style="@android:style/Widget.ImageButton"
            android:layout_width="79dp"
            android:layout_height="69dp"
            android:background="@drawable/e_learningfor_kids"
            app:layout_constraintStart_toEndOf="@+id/googleclick"
            app:layout_constraintTop_toTopOf="@+id/googleclick"
            tools:targetApi="m" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</RelativeLayout></code>```

答:
can you please show me the build.gradle file
you can first of all enter the required sdk version there. dont forget to change the target sdk version.

then go to tools. click on sdk manager. there you can install the required sdk version.

i recommend you to use sdk version greater than 28.

Body:
I am working on a app and i wanted to view what it looks like on different devices, but it seems like its only my current device definition it allows.
I have tried to inspect it and i found error concerning the implementation of my foreground drawable which it says will not be usable in API lower than version 23 which i made the required changes to them  but i just don't understand it
here is what it shows me:
enter image description here

please how can i fix this issue
hers is what my code looks like:

package com.polawa.glowingagesacademy;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;

public class elearning_page extends AppCompatActivity implements View.OnClickListener {
    private ImageButton mainpagee;
    private ImageButton googleclick;
    private ImageButton khanbutton;
    private ImageButton elearnclick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_elearning_page);

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_orange_light"
        tools:context=".elearning_page">

    <ImageButton
        android:id="@+id/mainpagee"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="15dp"
        android:layout_marginRight="15dp"
        android:background="@android:drawable/ic_dialog_dialer"
        app:layout_constraintBottom_toTopOf="@+id/constraintLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.532" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="64dp"
        android:layout_height="80dp"
        android:layout_marginStart="24dp"
        android:layout_marginBottom="76dp"
        android:layout_marginLeft="24dp"
        app:layout_constraintBottom_toTopOf="@+id/constraintLayout"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/logo" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/constraintLayout"
        android:layout_marginStart="36dp"
        android:layout_marginLeft="36dp"
        android:layout_marginEnd="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginBottom="39dp"
        android:layout_toStartOf="@+id/mainpagee"
        android:layout_toLeftOf="@+id/mainpagee"
        android:layout_toEndOf="@+id/imageView2"
        android:layout_toRightOf="@+id/imageView2"
        android:gravity="center"
        android:text="GAA e-Classroom"
        android:textColor="@android:color/secondary_text_light"
        android:textSize="24sp"
        app:fontFamily="casual" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="656dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="-6dp"
        android:background="@drawable/fafaffaf"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView">

        <ImageButton
            android:id="@+id/googleclick"
            style="@android:style/Widget.ImageButton"
            android:layout_width="81dp"
            android:layout_height="70dp"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:background="@drawable/google_classroom_png_4"

            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.046" />

        <ImageButton
            android:id="@+id/khanbutton"
            style="@android:style/Widget.ImageButton"
            android:layout_width="75dp"
            android:layout_height="67dp"
            android:background="@drawable/khan_academy"
            app:layout_constraintStart_toEndOf="@+id/elearnclick"
            app:layout_constraintTop_toTopOf="@+id/elearnclick"
            tools:targetApi="m" />

        <ImageButton
            android:id="@+id/elearnclick"
            style="@android:style/Widget.ImageButton"
            android:layout_width="79dp"
            android:layout_height="69dp"
            android:background="@drawable/e_learningfor_kids"
            app:layout_constraintStart_toEndOf="@+id/googleclick"
            app:layout_constraintTop_toTopOf="@+id/googleclick"
            tools:targetApi="m" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</RelativeLayout>


来源: stackexchange

问:
What is "validation set" and why is 0 and I try to write the formula for RMS and I get the error "ZeroDivisionError"
rms=np.sqrt(np.mean(np.power((np.array(valid['price'])-preds),2)))

print('\n RMSE value on validation set:')

print(rms)

ZeroDividedError

set validation set (0,232)

And the dataset is in following image
dataset

答: Your "mean" argument size is zero, check arrays shapes. </p>

ContentLicense: CC BY-SA 4.0


问:
How to serve Google Big Query output to a client web
I have exported Firestore collections to Google Big Query to make data analysis and aggregation.
What is the best practice (using Google Cloud Products) to serve Big Query outputs to a client web application? </p>

答:
Google provides seven client libraries for BigQuery. You can take any library and write a webserver that will serve requests from client web application. The webserver can use a GCP service account to access BigQuery on behalf of its clients.

One such sample is this project. It's written in TypeScript. Uses NodeJS library on the server and React for the client app. I'm the author.


问:
Count the cells with same color in google spreadsheet
I'm trying count the number of cells with the same background color and put the result in other cell with a script in google apps script, but I can't do it. I have the next script but not work and I don't know which is the problem:</p>

```<code>function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var range_input = book.getRange("B3:B4");
 var range_output = book.getRange("B6");
 var cell_colors = range_input.getBackgroundColors()[0];
 var color = "#58FA58";
 var count = 0;

 for( var i in cell_colors )
  if( cell_colors[i] == color ){
    range_output.setValue(++count);
  }
  else {
    return count;
  }
 }
</code>```

答:
The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells.
You can find a detailed description here: Google Script count coloured with reference, but the code is below:</p>

```<code>function countColoured(reference) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
  try {
    if (args.length == 1) {
      var range = sheet.getRange(args[0]);
    }
    else {
      sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
      range = sheet.getRange(args[1]);
    }
  }
  catch(e) {
    throw new Error(args.join('!') + ' is not a valid range');
  }
  var c = 0;
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
    }
  }
  return c > 0 ? c : "" ;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying count the number of cells with the same background color and put the result in other cell with a script in google apps script, but I can't do it. I have the next script but not work and I don't know which is the problem:

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var range_input = book.getRange("B3:B4");
 var range_output = book.getRange("B6");
 var cell_colors = range_input.getBackgroundColors()[0];
 var color = "#58FA58";
 var count = 0;

 for( var i in cell_colors )
  if( cell_colors[i] == color ){
    range_output.setValue(++count);
  }
  else {
    return count;
  }
 }

Body:
The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells.
You can find a detailed description here: Google Script count coloured with reference, but the code is below:

function countColoured(reference) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
  try {
    if (args.length == 1) {
      var range = sheet.getRange(args[0]);
    }
    else {
      sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
      range = sheet.getRange(args[1]);
    }
  }
  catch(e) {
    throw new Error(args.join('!') + ' is not a valid range');
  }
  var c = 0;
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
    }
  }
  return c > 0 ? c : "" ;
}


问:
Why does singleton class survive Activity exit?
I have a Singleton class which I use with the one of the activities of my application.

When I exit the activity - which brings me back to the menu activity - and then reopen the activity I find that when I try to access the singleton it is still the same.
Surely it should have been destroyed with the Activity?

I saw the question here: living singleton, when activity end
but could not quite follow what they mean.

When I press the return button on my device (or use finish within the Activity itself) is the Activity kept alive for future use? If so, then that would explain it.

答:
Surely it should have been destroyed with the Activity?

No.

When I press the return button on my device (or use finish within the Activity itself) is the Activity kept alive for future use?

The activity is not. The process is. Singletons are part of the virtual machine and will live as long as the process does. Exiting the last activity does not immediately terminate the process, so the singleton lives on... at least for a while.

Android will eventually terminate that process to free up memory for other apps. How quickly it will do that depends on what the user is doing, what apps are installed, phase of the moon, etc.


问:
Noob Question How would I update a print a function's output without creating a new line in my term in python3?
I'm not exactly sure how to word this to be honest, but here's a simplified version of my current code.

```<code>for idx in range(0,11):
    print('Failed:',idx)
</code>```

This outputs:

```<code>Failed: 0
Failed: 1
Failed: 2
Failed: 3
Failed: 4
Failed: 5
Failed: 6
Failed: 7
Failed: 8
Failed: 9
Failed: 10
</code>```

I'm trying to replace the original int with the next int in the range instead of spamming my terminal with a new line for every int in the range.

How could I update "Failed: 1" to "Failed: 2" without creating a new line for "Failed: 2"?

Sorry if this is poorly worded, if you're willing to help me but like me to elaborate further please say so and I will try my best.

答:
whoops let's  try again...

Your only option is to clear the whole console between prints. there are two ways of going about this.

option 1: You could try and use ANSI escape sequence but might be a little flakey

```<code>print(chr(27)+'[2j')
print('\033c')
print('\x1bc')
</code>```

Option 2: use the os module

```<code>from os import system, name
# Only on Unix
system('cls')
# Only on windows
system('clear')
</code>```

Body:
I'm not exactly sure how to word this to be honest, but here's a simplified version of my current code.

for idx in range(0,11):
    print('Failed:',idx)

This outputs:

Failed: 0
Failed: 1
Failed: 2
Failed: 3
Failed: 4
Failed: 5
Failed: 6
Failed: 7
Failed: 8
Failed: 9
Failed: 10

I'm trying to replace the original int with the next int in the range instead of spamming my terminal with a new line for every int in the range.

How could I update "Failed: 1" to "Failed: 2" without creating a new line for "Failed: 2"?

Sorry if this is poorly worded, if you're willing to help me but like me to elaborate further please say so and I will try my best.

Body:
whoops let's  try again...

Your only option is to clear the whole console between prints. there are two ways of going about this.

option 1: You could try and use ANSI escape sequence but might be a little flakey

print(chr(27)+'[2j')
print('\033c')
print('\x1bc')

Option 2: use the os module

from os import system, name
# Only on Unix
system('cls')
# Only on windows
system('clear')


问:
Randomized Autoclicker C++ using one key for on/off
I have been attempting to write a cpp autoclicker using header <windows.h> but it isn't working the best. The code works fine and all, but its extremely annoying to turn off as it requires a millisecond click, nothing longer, if I hold that shortcut for too long, it turns back on again. Any suggestions for improvements?

```<code>#include <iostream>
#include <Windows.h>
#include <random>
using namespace std;
int counti;
void menu()
{
    cout << "Press 'Ctrl + Tab' to enable and Press 'Ctrl + Tab' to disable randomised autoclicker\n";
}

void clicker()
{
    bool click = false; //sets click to false
    int n;

    while (true)
    {
        while (1) {
            n = rand() % 125;
            if (n > 75)break;
        }
        if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(VK_TAB)) //if Ctrl + Tab is pressed
        {
            counti++;
            if (counti % 2 == 1)click = true; //Shortcut pressed once and it activates
            else if (counti % 2 == 0)click = false; //Shortcut pressed again and it deactivates
        }
        if (click == true) // if click = true it will press the mouse button down and up really fast
        {
            mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
            cout << n << endl;
            Sleep(n); //random speed here
        }
    }
}

int main()
{
    menu();
    clicker();
    return 0;
}
</code>```

Thank you!!

答: Don't use the same hotkey to turn on and off. Use a different key.</p>

Body:
I have been attempting to write a cpp autoclicker using header <windows.h> but it isn't working the best. The code works fine and all, but its extremely annoying to turn off as it requires a millisecond click, nothing longer, if I hold that shortcut for too long, it turns back on again. Any suggestions for improvements?

#include <iostream>
#include <Windows.h>
#include <random>
using namespace std;
int counti;
void menu()
{
    cout << "Press 'Ctrl + Tab' to enable and Press 'Ctrl + Tab' to disable randomised autoclicker\n";
}

void clicker()
{
    bool click = false; //sets click to false
    int n;

    while (true)
    {
        while (1) {
            n = rand() % 125;
            if (n > 75)break;
        }
        if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(VK_TAB)) //if Ctrl + Tab is pressed
        {
            counti++;
            if (counti % 2 == 1)click = true; //Shortcut pressed once and it activates
            else if (counti % 2 == 0)click = false; //Shortcut pressed again and it deactivates
        }
        if (click == true) // if click = true it will press the mouse button down and up really fast
        {
            mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
            cout << n << endl;
            Sleep(n); //random speed here
        }
    }
}

int main()
{
    menu();
    clicker();
    return 0;
}

Thank you!!


问:
Node JS Mongo $near not working with nested field
I've been working on a simple search using the $near operator but have recently changed my data so the 2dsphere location index is now in the nested field properties.location instead of just location. I am using the Node JS mongo driver and the search worked fine when the index was not nested inside the properties object using the following query, but returns nothing now:

Previous working query:

```<code>dbObject.collection("scrapedTimes").find({
            location: {
                $near: {
                    $geometry: {
                        type: "Point" ,
                        coordinates: [lngBound, latBound]
                    },
                    $minDistance: 0,
                    $maxDistance: 100000
                }
            }

})
</code>```

Current query that returns nothing:

```<code>dbObject.collection("scrapedTimes").find({
            "properties.location": {
                $near: {
                    $geometry: {
                        type: "Point" ,
                        coordinates: [lngBound, latBound]
                    },
                    $minDistance: 0,
                    $maxDistance: 100000
                }
            }

})
</code>```

I have executed this same nested query in Mongo Compass and it seems to work fine so I think it might be a problem with the Node JS driver? I'm quite new to Mongo so there might be something obvious I'm missing here but I just can't get Node to return any results...

Thanks for your time and suggestions,

Josh

答:
Change $near to $nearSphere, there's a difference between the two which mainly relates to calculations using spherical geometry. $near will use flat geometry and won't work because of the 2dSphere index on the nested document.

Check this out for the difference between the two...

In Mongo what is the difference between $near and $nearSphere?

Body:
I've been working on a simple search using the $near operator but have recently changed my data so the 2dsphere location index is now in the nested field properties.location instead of just location. I am using the Node JS mongo driver and the search worked fine when the index was not nested inside the properties object using the following query, but returns nothing now:

Previous working query:

dbObject.collection("scrapedTimes").find({
            location: {
                $near: {
                    $geometry: {
                        type: "Point" ,
                        coordinates: [lngBound, latBound]
                    },
                    $minDistance: 0,
                    $maxDistance: 100000
                }
            }

})

Current query that returns nothing:

dbObject.collection("scrapedTimes").find({
            "properties.location": {
                $near: {
                    $geometry: {
                        type: "Point" ,
                        coordinates: [lngBound, latBound]
                    },
                    $minDistance: 0,
                    $maxDistance: 100000
                }
            }

})

I have executed this same nested query in Mongo Compass and it seems to work fine so I think it might be a problem with the Node JS driver? I'm quite new to Mongo so there might be something obvious I'm missing here but I just can't get Node to return any results...

Thanks for your time and suggestions,

Josh


问:
Google BigQuery: grant service account permissions to create jobs in only some specific datasets
Problem: I have a project in BigQuery where all my data is stored. Within this project I created multiple datasets containing different views. Now I want to use different service accounts to query the different datasets containing different views via grafana (if that matters). These users should only be able to query the views (and therefore a specific dataset) meant for them.

What I tried: I granted BigQuery User, Viewer or Editor permissions (I tried all of them) at a dataset level (and also BigQuery Meatadata Viewer at a project level). When I query a view, I receive the error:

User does not have bigquery.jobs.create permission in project xy.

Questions: It is not clear to me if granting bigquery.jobs.create permission on project level, will allow the user to query all datasets instead of only the one I want him to access to.

Is there any way to allow the user to create jobs only on a single dataset?

答:
You can grant bigquery.user role to a specific dataset as indicated in this guide. The bigquery.user role contains the bigquery.jobs.create permission as well as other basic permissions related to querying datasets. You can check the full list of permissions for this role in this list.

As suggested above, you can also create custom roles having only the exact permissions you want by following this piece of documentation.


问:
R marmap getNOAA.bathy Error in if (ncol(x) == 3 & !exists("bathy", inherits = FALSE)) { : argument is of length zero
I've been trying to get bathymetry lines from marmap and recently got the following error message when getNOAA.bathy function is called

```<code>Querying NOAA database ...This may take seconds to minutes, depending on grid size
Error in if (ncol(x) == 3 & !exists("bathy", inherits = FALSE)) { : argument is of length zero
</code>```

This happens even with something as simple as

```<code>map <- getNOAA.bathy(lon1=10,lon2=19,lat1=67,lat2=71,resolution=10, keep=TRUE)
</code>```

I updated the package to the latest version (1.0.4) as I read that there could be issues related to server access. I've also tried running the above script in R rather than RStudio, but the error persists...
The function works fine if I use previously downloaded data, but now I needed use use another set of coordinates for a new map.

Any help is much appreciated!

答: You need to (re)install both rgdal and raster packages. This is already documented here on the GitHub Issue pages of the marmap package.

Body:
I've been trying to get bathymetry lines from marmap and recently got the following error message when getNOAA.bathy function is called

Querying NOAA database ...This may take seconds to minutes, depending on grid size
Error in if (ncol(x) == 3 & !exists("bathy", inherits = FALSE)) { : argument is of length zero

This happens even with something as simple as

map <- getNOAA.bathy(lon1=10,lon2=19,lat1=67,lat2=71,resolution=10, keep=TRUE)

I updated the package to the latest version (1.0.4) as I read that there could be issues related to server access. I've also tried running the above script in R rather than RStudio, but the error persists...
The function works fine if I use previously downloaded data, but now I needed use use another set of coordinates for a new map.

Any help is much appreciated!


问:
Regular Expression to trim number at the end of a string
I have a file which consists of string. The file also contains date.
I want to remove number at the end of the string.
For example-

```<code>Str = 'part-at-1234'
</code>```

New string should be str= 'part-at'

I have written the following regex

```<code>(-\d+)
</code>```

My regex also matches the date.
I want to write a regular expression that only matches the string not include date.
Thank you in advance

答:
Try this regular expressions:

.+\D+(?=\d+)

Or you could always select the numbers at the end with this, and then replace it with and empty string:

\d+$

Body:
I have a file which consists of string. The file also contains date.
I want to remove number at the end of the string.
For example-

Str = 'part-at-1234'

New string should be str= 'part-at'

I have written the following regex

(-\d+)

My regex also matches the date.
I want to write a regular expression that only matches the string not include date.
Thank you in advance


问:
Android App Not Open black screen problem
I made a simple app of android webview a few days ago and it runs fine but the problem is happening now that after some time the app is not open, that screen is going black and reinstall After doing it, it is going right, for some time it is going right, then the same problem is coming, if someone helps, it will be very kind.

Mi redmi note 6 Pro
Android V 9 PIE

Source Code

manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.musicwala.djaman" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:usesCleartextTraffic="true"
        android:icon="@drawable/main"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:resizeableActivity="true">
        <activity

            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".web_main">
        </activity>
        <activity
            android:name=".setting">
        </activity>
        <activity
            android:name=".about"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
        </activity>
        <activity
            android:name=".update">

        </activity>
        <activity
            android:name=".download">

        </activity>
        <activity android:name=".play_ui"
            android:theme="@style/Theme.AppCompat.Light">

        </activity>
    </application>

</manifest>
</code>```

build.gradle

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

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.musicwala.djaman"
        minSdkVersion 14
        targetSdkVersion 29
        versionCode 3
        versionName "3.1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile ('android.arch.core:runtime:+') {
       force = true
}

    compile 'com.android.support:appcompat-v7:27.+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
</code>```

MainActivity.java

```<code>package com.musicwala.djaman;

import android.app.*;
import android.os.*;
import android.view.Window;
import android.widget.AbsoluteLayout.LayoutParams;
import android.view.WindowManager;
import android.content.Intent;
import android.util.Log;
import android.net.NetworkInfo;
import android.net.ConnectivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.provider.Settings;
import android.widget.Toast;

public class MainActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
      //  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            // WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        if(isNetworkConnectionAvailable() == true)
        {
            final Handler h = new Handler();

            h.postDelayed(new Runnable() {

                    @Override

                    public void run() {

                        //Do something after 1s

                        Intent intent = new Intent(MainActivity.this,web_main.class);
                        startActivity(intent);
                        finish();
                    }

                }, 1000);

        }

    }
    public void checkNetworkConnection(){
        AlertDialog.Builder builder =new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("No internet Connection");
        builder.setMessage("Please turn on internet connection to continue!");
        builder.setPositiveButton("Turn On", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            }).show();

        builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finishAffinity();
                }
            }).show();

        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    public boolean isNetworkConnectionAvailable(){
        ConnectivityManager cm =
            (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnected();
        if(isConnected) {
            Log.d("Network", "Connected");
            return true;
        }
        else{
            checkNetworkConnection();
            Log.d("Network","Not Connected");
            return false;
        }
    }

}
</code>```

And is working fine in my other device

Android v8.0 Oreo

答: Clear your phone cache ,data and restart your phone!</p>

Body:
I made a simple app of android webview a few days ago and it runs fine but the problem is happening now that after some time the app is not open, that screen is going black and reinstall After doing it, it is going right, for some time it is going right, then the same problem is coming, if someone helps, it will be very kind.

Mi redmi note 6 Pro
Android V 9 PIE

Source Code

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.musicwala.djaman" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:usesCleartextTraffic="true"
        android:icon="@drawable/main"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:resizeableActivity="true">
        <activity

            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".web_main">
        </activity>
        <activity
            android:name=".setting">
        </activity>
        <activity
            android:name=".about"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
        </activity>
        <activity
            android:name=".update">

        </activity>
        <activity
            android:name=".download">

        </activity>
        <activity android:name=".play_ui"
            android:theme="@style/Theme.AppCompat.Light">

        </activity>
    </application>

</manifest>

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.musicwala.djaman"
        minSdkVersion 14
        targetSdkVersion 29
        versionCode 3
        versionName "3.1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile ('android.arch.core:runtime:+') {
       force = true
}

    compile 'com.android.support:appcompat-v7:27.+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

MainActivity.java

package com.musicwala.djaman;

import android.app.*;
import android.os.*;
import android.view.Window;
import android.widget.AbsoluteLayout.LayoutParams;
import android.view.WindowManager;
import android.content.Intent;
import android.util.Log;
import android.net.NetworkInfo;
import android.net.ConnectivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.provider.Settings;
import android.widget.Toast;

public class MainActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
      //  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            // WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        if(isNetworkConnectionAvailable() == true)
        {
            final Handler h = new Handler();

            h.postDelayed(new Runnable() {

                    @Override

                    public void run() {

                        //Do something after 1s

                        Intent intent = new Intent(MainActivity.this,web_main.class);
                        startActivity(intent);
                        finish();
                    }

                }, 1000);

        }

    }
    public void checkNetworkConnection(){
        AlertDialog.Builder builder =new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("No internet Connection");
        builder.setMessage("Please turn on internet connection to continue!");
        builder.setPositiveButton("Turn On", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            }).show();

        builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finishAffinity();
                }
            }).show();

        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    public boolean isNetworkConnectionAvailable(){
        ConnectivityManager cm =
            (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnected();
        if(isConnected) {
            Log.d("Network", "Connected");
            return true;
        }
        else{
            checkNetworkConnection();
            Log.d("Network","Not Connected");
            return false;
        }
    }

}

And is working fine in my other device

Android v8.0 Oreo


问:
How to make such a scroll of content?
Please help me to style the scrolling of content using react and scss like this:

So that when the scrolling elements overlap each other, they have something like a parallax style.

答:
a simpler solution would be something along the lines of:

.contentDivContainer {
  position: absolute;
  left: 100px;
  width: 200px;
  height: 200px;
}

.contentDivs {
  background-color: lightpink;
  font-size: 18px;
  margin: 20px;
}

.contentDivs:nth-child(2n) {
  background-color: lightblue;
}

.windowDivs {
  position: fixed;
  width: 200px;
  height: 200px;
  left: 100px;
}

.windowDivs2 {
  top: 300px;
}

.windowDivsBlank {
  top: 0px;
  z-index: 2;
  background: white;
  height: 50px;
}

.windowDivsBlank2 {
  top: 250px;
  z-index: 2;
  background: white;
  height: 50px;
}

.windowDivsBlank3 {
  top: 500px;
  z-index: 2;
  background: white;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='windowDivs'></div>
<div class='windowDivs windowDivsBlank'></div>
<div class='windowDivs windowDivs2'></div>
<div class='windowDivs windowDivsBlank2'></div>
<div class='windowDivs windowDivsBlank3'></div>

<div class="contentDivContainer">
  <div class='contentDivs'>
    ONE - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>

  <div class='contentDivs'>
    TWO - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>

  <div class='contentDivs'>
    THREE - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling.lue Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>

  <div class='contentDivs'>
    FOUR - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>
</div></code>```

Title: How to make such a scroll of content?

Body:
a simpler solution would be something along the lines of:

.contentDivContainer {
  position: absolute;
  left: 100px;
  width: 200px;
  height: 200px;
}

.contentDivs {
  background-color: lightpink;
  font-size: 18px;
  margin: 20px;
}

.contentDivs:nth-child(2n) {
  background-color: lightblue;
}

.windowDivs {
  position: fixed;
  width: 200px;
  height: 200px;
  left: 100px;
}

.windowDivs2 {
  top: 300px;
}

.windowDivsBlank {
  top: 0px;
  z-index: 2;
  background: white;
  height: 50px;
}

.windowDivsBlank2 {
  top: 250px;
  z-index: 2;
  background: white;
  height: 50px;
}

.windowDivsBlank3 {
  top: 500px;
  z-index: 2;
  background: white;
  height: 50px;
}

<div class='windowDivs'></div>
<div class='windowDivs windowDivsBlank'></div>
<div class='windowDivs windowDivs2'></div>
<div class='windowDivs windowDivsBlank2'></div>
<div class='windowDivs windowDivsBlank3'></div>

<div class="contentDivContainer">
  <div class='contentDivs'>
    ONE - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>

  <div class='contentDivs'>
    TWO - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>

  <div class='contentDivs'>
    THREE - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling.lue Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>

  <div class='contentDivs'>
    FOUR - Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
  </div>
</div>


问:
Xamarin Persistent color chooser
I make a button and Color picker to xamarin.forms app, but I want to make it when I choose one color (ex. red) and close app, when i reopen it to see this red color automatic picked. I try to use this code but Preferences not working with Color:

```<code>public Color ColorPicker
{
    get => Preferences.Get(nameof(ColorPicker), color.Red);
    set
    {
        Preferences.Set(nameof(ColorPicker), value);
        OnPropertyChanged(nameof(ColorPicker));
    }
}
</code>```

Can someone help me?

答:
The Color.FromHex(string value) method needs a string type parameter. Try to convert the value to string type in the custom class.

Check the code:

Custom Converter class

```<code>public class StringToColorConverter : IValueConverter, INotifyPropertyChanged
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var color = Color.FromHex(value as string);
        return color;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

Page.xaml

```<code><ContentPage.Resources>
    <local:StringToColorConverter x:Key="myConverter" />
</ContentPage.Resources>

<ContentPage.Content>
    <StackLayout BackgroundColor="{Binding Color_string, Converter={StaticResource myConverter}}">
        ...
    </StackLayout>
</ContentPage.Content>
</code>```

Title: Xamarin Persistent color chooser

Body:
I make a button and Color picker to xamarin.forms app, but I want to make it when I choose one color (ex. red) and close app, when i reopen it to see this red color automatic picked. I try to use this code but Preferences not working with Color:

public Color ColorPicker
{
    get => Preferences.Get(nameof(ColorPicker), color.Red);
    set
    {
        Preferences.Set(nameof(ColorPicker), value);
        OnPropertyChanged(nameof(ColorPicker));
    }
}

Can someone help me?

Body:
The Color.FromHex(string value) method needs a string type parameter. Try to convert the value to string type in the custom class.

Check the code:

Custom Converter class

public class StringToColorConverter : IValueConverter, INotifyPropertyChanged
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var color = Color.FromHex(value as string);
        return color;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Page.xaml

<ContentPage.Resources>
    <local:StringToColorConverter x:Key="myConverter" />
</ContentPage.Resources>

<ContentPage.Content>
    <StackLayout BackgroundColor="{Binding Color_string, Converter={StaticResource myConverter}}">
        ...
    </StackLayout>
</ContentPage.Content>


问:
Cannot update zope.schema in Plone
Very new to setting up Plone 4 and trying to integrate Solgema.fullcalendar but when running buildout I get an error saying it needs zope.schema 3.6.0 and I have 3.5.4. I cannot for the life of me work out how to update it. I assume I am missing something fundamental here but it is doing my head in as I imagine as I will encounter this kind of issue again and again as I progress.

"  Installing instance.
Error: There is a version conflict.
We already have: zope.schema 3.5.4
but z3c.form 2.4.2 requires 'zope.schema>=3.6.0'."

Looked around and noticed that putting zope.schema>=3.6.0 in eggs might work but that didn't actually trigger an update just caused a bad install error.

If anyone has any ideas or needs something more to go on please let me know!

Thanks
Chris

答:
See Hanno's answer.  I will add that I cannot think of a good reason anymore to use '>=' (or '<=' or '==') to specify minimum, maximum or exact versions anywhere in a buildout config.  Version specifications should only be in a [versions] section.  It has been a while since I last used a buildout config that used the comparison operators, but I remember it could lead to problems, especially when upgrading; the only way out would at times be to remove the '.installed.cfg' file to make bin/buildout run in a fresh state.

(Note that '>=' in a setup.py is perfectly fine.)

Title: Cannot update zope.schema in Plone


问:
How can I create an expandable grid of Swing buttons?
I am trying to make an A* Pathfinding Visualizer but right now I am stuck on creating the grid. What is the best way of creating a grid like what is seen below? For instance, should I just use a bunch of JButton components or is there some other way?

答:
Put JButton components in a GridLayout, using removeAll() on the panel before setting a new grid layout to change the number of columns and/or rows. Lastly pack() the top level container (in this case a JFrame) to fit the number of rows and columns.

```<code>import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.EmptyBorder;

public class ChangableButtonGrid {

    private JComponent ui = null;
    JPanel gridArea = new JPanel();

    public static final int SIZE = 600;
    JToolBar tools = new JToolBar("Tools");
    SpinnerNumberModel colModel = new SpinnerNumberModel(20, 5, 50, 1);
    SpinnerNumberModel rowModel = new SpinnerNumberModel(5, 5, 50, 1);
    ChangeListener changeListener = (ChangeEvent e) -> {
        refresh();
    };

    public ChangableButtonGrid() {
        initUI();
    }

    public final void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        ui.add(gridArea);

        ui.add(tools,BorderLayout.PAGE_START);
        tools.setLayout(new FlowLayout(FlowLayout.LEADING));
        addModelToToolbar("Cols", colModel);
        addModelToToolbar("Rows", rowModel);

        ui.add(gridArea);
    }

    private void refresh() {
        int cols = colModel.getNumber().intValue();
        int rows = rowModel.getNumber().intValue();
        gridArea.removeAll();
        gridArea.setLayout(new GridLayout(rows, cols));
        for (int rr=0; rr<rows; rr++) {
            for (int cc=0; cc<cols; cc++) {
                JButton b = new JButton(cc + "," + rr);
                gridArea.add(b);
            }
        }
        Container c = gridArea.getTopLevelAncestor();
        JFrame f = (JFrame)c;
        f.pack();
    }

    private void addModelToToolbar(String label, SpinnerNumberModel model) {
        tools.add(new JLabel(label));
        JSpinner spinner = new JSpinner(model);
        spinner.addChangeListener(changeListener);
        tools.add(spinner);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            ChangableButtonGrid o = new ChangableButtonGrid();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            o.refresh();

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}
</code>```

Body:
Put JButton components in a GridLayout, using removeAll() on the panel before setting a new grid layout to change the number of columns and/or rows. Lastly pack() the top level container (in this case a JFrame) to fit the number of rows and columns.

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.EmptyBorder;

public class ChangableButtonGrid {

    private JComponent ui = null;
    JPanel gridArea = new JPanel();

    public static final int SIZE = 600;
    JToolBar tools = new JToolBar("Tools");
    SpinnerNumberModel colModel = new SpinnerNumberModel(20, 5, 50, 1);
    SpinnerNumberModel rowModel = new SpinnerNumberModel(5, 5, 50, 1);
    ChangeListener changeListener = (ChangeEvent e) -> {
        refresh();
    };

    public ChangableButtonGrid() {
        initUI();
    }

    public final void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        ui.add(gridArea);

        ui.add(tools,BorderLayout.PAGE_START);
        tools.setLayout(new FlowLayout(FlowLayout.LEADING));
        addModelToToolbar("Cols", colModel);
        addModelToToolbar("Rows", rowModel);

        ui.add(gridArea);
    }

    private void refresh() {
        int cols = colModel.getNumber().intValue();
        int rows = rowModel.getNumber().intValue();
        gridArea.removeAll();
        gridArea.setLayout(new GridLayout(rows, cols));
        for (int rr=0; rr<rows; rr++) {
            for (int cc=0; cc<cols; cc++) {
                JButton b = new JButton(cc + "," + rr);
                gridArea.add(b);
            }
        }
        Container c = gridArea.getTopLevelAncestor();
        JFrame f = (JFrame)c;
        f.pack();
    }

    private void addModelToToolbar(String label, SpinnerNumberModel model) {
        tools.add(new JLabel(label));
        JSpinner spinner = new JSpinner(model);
        spinner.addChangeListener(changeListener);
        tools.add(spinner);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            ChangableButtonGrid o = new ChangableButtonGrid();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            o.refresh();

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}


问:
Selecting if count for different value is 1 or more
I have the following table data,

```<code>Number              Code
   1                 430
   1                 430
   2                 430
   2                 430
   3                 420
   3                 340
   3                 430
   1                 420
</code>```

Given the above data, I am trying to get records which have different code exist on them to make it clear following is the output I am expecting.

```<code>Number              Code
  1                 430
  1                 420
  3                 420
  3                 340
  3                 430
</code>```

If you see I am only selecting a number where different code exists if the number doesn't have different code on them I don't want to select that number.

I have tried with group by with having and then filtering out the matching codes but I am still not able to figure it out and messing with my output. I can't add having count(*) > 1 because same number can have multiple rows with same code.

Any help or pointers would be great.

答:
You need to distinctly count the code grouped by Number, and distinctly show in the main query :

```<code>WITH t AS
(
SELECT Number
  FROM tab
 GROUP BY Number
 HAVING COUNT(DISTINCT Code) > 1 )
SELECT DISTINCT t2.*
  FROM tab t2
  JOIN t
    ON t2.Number = t.Number
 ORDER BY t2.Number
</code>```

Demo

Body:
I have the following table data,

Number              Code
   1                 430
   1                 430
   2                 430
   2                 430
   3                 420
   3                 340
   3                 430
   1                 420

Given the above data, I am trying to get records which have different code exist on them to make it clear following is the output I am expecting.

Number              Code
  1                 430
  1                 420
  3                 420
  3                 340
  3                 430

If you see I am only selecting a number where different code exists if the number doesn't have different code on them I don't want to select that number.

I have tried with group by with having and then filtering out the matching codes but I am still not able to figure it out and messing with my output. I can't add having count(*) > 1 because same number can have multiple rows with same code.

Any help or pointers would be great.

Body:
You need to distinctly count the code grouped by Number, and distinctly show in the main query :

WITH t AS
(
SELECT Number
  FROM tab
 GROUP BY Number
 HAVING COUNT(DISTINCT Code) > 1 )
SELECT DISTINCT t2.*
  FROM tab t2
  JOIN t
    ON t2.Number = t.Number
 ORDER BY t2.Number

Demo


问:
Correlation not functionining
I've got this code:

```<code>#Datenblaetter einlesen und benennen
Faking <- read.csv2("Z:/Forschungsprojekte DiffDia/(2011-2016) Interpersonal Abilities/(2013-2015) Deception/Faking Ability/Study 6 - Faking Good and Faking Bad (Students)/3 - Data and Analysis/output/personality_faking_final.csv")
FB_Int <- cbind(Faking$vpcode,Faking[,names(Faking)[grepl("FBI_",names(Faking))]])

#Werte anpassen, um gleiche Skalenrange zu erhalten
FB_Int$FBI_01_S <- (FB_Int$FBI_01_S + 2)/3
FB_Int$FBI_02_S <- (FB_Int$FBI_02_S + 2)/3
FB_Int$FBI_03_A <- (FB_Int$FBI_03_A + 2)/3
FB_Int$FBI_04_E <- (FB_Int$FBI_04_E + 2)/3
FB_Int$FBI_05_R <- (FB_Int$FBI_05_R + 2)/3
FB_Int$FBI_06_I <- (FB_Int$FBI_06_I + 2)/3
FB_Int$FBI_07_C <- (FB_Int$FBI_07_C + 2)/3
FB_Int$FBI_08_R <- (FB_Int$FBI_08_R + 2)/3
FB_Int$FBI_09_I <- (FB_Int$FBI_09_I + 2)/3
FB_Int$FBI_10_R <- (FB_Int$FBI_10_R + 2)/3
FB_Int$FBI_11_A <- (FB_Int$FBI_11_A + 2)/3
FB_Int$FBI_12_S <- (FB_Int$FBI_12_S + 2)/3
FB_Int$FBI_13_C <- (FB_Int$FBI_13_C + 2)/3
FB_Int$FBI_14_C <- (FB_Int$FBI_14_C + 2)/3
FB_Int$FBI_15_R <- (FB_Int$FBI_15_R + 2)/3
FB_Int$FBI_16_E <- (FB_Int$FBI_16_E + 2)/3
FB_Int$FBI_17_I <- (FB_Int$FBI_17_I + 2)/3
FB_Int$FBI_18_A <- (FB_Int$FBI_18_A + 2)/3
FB_Int$FBI_19_I <- (FB_Int$FBI_19_I + 2)/3
FB_Int$FBI_20_E <- (FB_Int$FBI_20_E + 2)/3
FB_Int$FBI_21_C <- (FB_Int$FBI_21_C + 2)/3
FB_Int$FBI_22_S <- (FB_Int$FBI_22_S + 2)/3
FB_Int$FBI_23_A <- (FB_Int$FBI_23_A + 2)/3
FB_Int$FBI_24_I <- (FB_Int$FBI_24_I + 2)/3
FB_Int$FBI_25_R <- (FB_Int$FBI_25_R + 2)/3
FB_Int$FBI_26_A <- (FB_Int$FBI_26_A + 2)/3
FB_Int$FBI_27_S <- (FB_Int$FBI_27_S + 2)/3
FB_Int$FBI_28_E <- (FB_Int$FBI_28_E + 2)/3
FB_Int$FBI_29_E <- (FB_Int$FBI_29_E + 2)/3
FB_Int$FBI_30_C <- (FB_Int$FBI_30_C + 2)/3

#Mittelwerte der einzelnen RIASEC-Bereiche berechnen
FB_Int$m_FB_Int_R <- rowMeans(FB_Int[,names(FB_Int)[grepl("_R",names(FB_Int))]])
FB_Int$m_FB_Int_I <- rowMeans(FB_Int[,names(FB_Int)[grepl("_I",names(FB_Int))]])
FB_Int$m_FB_Int_A <- rowMeans(FB_Int[,names(FB_Int)[grepl("_A",names(FB_Int))]])
FB_Int$m_FB_Int_S <- rowMeans(FB_Int[,names(FB_Int)[grepl("_S",names(FB_Int))]])
FB_Int$m_FB_Int_E <- rowMeans(FB_Int[,names(FB_Int)[grepl("_E",names(FB_Int))]])
FB_Int$m_FB_Int_C <- rowMeans(FB_Int[,names(FB_Int)[grepl("_C",names(FB_Int))]])

#####################################
############SCORING##################
#####################################

#1. Scoring über Entfernung vom Ideal-Profil nach einzelnen Bereichen
FB_Int$E_Einzeln_R <- abs(FB_Int$m_FB_Int_R - 2.67)
FB_Int$E_Einzeln_I <- abs(FB_Int$m_FB_Int_I - 1)
FB_Int$E_Einzeln_A <- abs(FB_Int$m_FB_Int_A - 1.33)
FB_Int$E_Einzeln_S <- abs(FB_Int$m_FB_Int_S - 2.67)
FB_Int$E_Einzeln_E <- abs(FB_Int$m_FB_Int_E - 4.33)
FB_Int$E_Einzeln_C <- abs(FB_Int$m_FB_Int_C - 6.67)

FB_Int$Score_FB_Int <- rowMeans(FB_Int[,names(FB_Int)[grepl("E_",names(FB_Int))]])

#3. Korrelation zwischen Profilen
FB_Int$p_FB_Int.r <- apply(FB_Int[,names(FB_Int)[grepl("m_",names(FB_Int))]],1,function(x) cor(x, c(2.67,1,1.33,2.67,4.33,6.67)))

##Korrelation zwischen Score_FB_Int und p_FB_Int.r
###############
cor(FB_Int$Score_FB_Int,FB_Int$p_FB_Int.r)
</code>```

My problem is that the cor function at the end is not working. The Output is "Na". There is one row with Na's in the dataset, is this possibly the reason?

I would be very glad if somebody could help me out.

I created a link with my data:
https://wetransfer.com/downloads/d2f34918ec228bee87459d261227cba720200529074627/cc130a

I hope that is alright like that.

All the best!

答:
FB_Int$Score_FB_Int is all NAs. I think you need FB_Int$Score_FB_Int <- rowMeans(FB_Int[,names(FB_Int)[grepl("_E",names(FB_Int))]], na.rm = TRUE) and not FB_Int$Score_FB_Int <- rowMeans(FB_Int[,names(FB_Int)[grepl("E_",names(FB_Int))]], na.rm = TRUE) (so _E and not E_). And you also need to use cor like this cor(FB_Int$Score_FB_Int,FB_Int$p_FB_Int.r, use = "pairwise.complete.obs") because you have some NAs in FB_Int$p_FB_Int.r. Then it worked for me.

```<code>> cor(FB_Int$Score_FB_Int,FB_Int$p_FB_Int.r, use = "pairwise.complete.obs")
[1] 0.379014
</code>```

Title: Correlation not functionining

Body:
I've got this code:

#Datenblaetter einlesen und benennen
Faking <- read.csv2("Z:/Forschungsprojekte DiffDia/(2011-2016) Interpersonal Abilities/(2013-2015) Deception/Faking Ability/Study 6 - Faking Good and Faking Bad (Students)/3 - Data and Analysis/output/personality_faking_final.csv")
FB_Int <- cbind(Faking$vpcode,Faking[,names(Faking)[grepl("FBI_",names(Faking))]])

#Werte anpassen, um gleiche Skalenrange zu erhalten
FB_Int$FBI_01_S <- (FB_Int$FBI_01_S + 2)/3
FB_Int$FBI_02_S <- (FB_Int$FBI_02_S + 2)/3
FB_Int$FBI_03_A <- (FB_Int$FBI_03_A + 2)/3
FB_Int$FBI_04_E <- (FB_Int$FBI_04_E + 2)/3
FB_Int$FBI_05_R <- (FB_Int$FBI_05_R + 2)/3
FB_Int$FBI_06_I <- (FB_Int$FBI_06_I + 2)/3
FB_Int$FBI_07_C <- (FB_Int$FBI_07_C + 2)/3
FB_Int$FBI_08_R <- (FB_Int$FBI_08_R + 2)/3
FB_Int$FBI_09_I <- (FB_Int$FBI_09_I + 2)/3
FB_Int$FBI_10_R <- (FB_Int$FBI_10_R + 2)/3
FB_Int$FBI_11_A <- (FB_Int$FBI_11_A + 2)/3
FB_Int$FBI_12_S <- (FB_Int$FBI_12_S + 2)/3
FB_Int$FBI_13_C <- (FB_Int$FBI_13_C + 2)/3
FB_Int$FBI_14_C <- (FB_Int$FBI_14_C + 2)/3
FB_Int$FBI_15_R <- (FB_Int$FBI_15_R + 2)/3
FB_Int$FBI_16_E <- (FB_Int$FBI_16_E + 2)/3
FB_Int$FBI_17_I <- (FB_Int$FBI_17_I + 2)/3
FB_Int$FBI_18_A <- (FB_Int$FBI_18_A + 2)/3
FB_Int$FBI_19_I <- (FB_Int$FBI_19_I + 2)/3
FB_Int$FBI_20_E <- (FB_Int$FBI_20_E + 2)/3
FB_Int$FBI_21_C <- (FB_Int$FBI_21_C + 2)/3
FB_Int$FBI_22_S <- (FB_Int$FBI_22_S + 2)/3
FB_Int$FBI_23_A <- (FB_Int$FBI_23_A + 2)/3
FB_Int$FBI_24_I <- (FB_Int$FBI_24_I + 2)/3
FB_Int$FBI_25_R <- (FB_Int$FBI_25_R + 2)/3
FB_Int$FBI_26_A <- (FB_Int$FBI_26_A + 2)/3
FB_Int$FBI_27_S <- (FB_Int$FBI_27_S + 2)/3
FB_Int$FBI_28_E <- (FB_Int$FBI_28_E + 2)/3
FB_Int$FBI_29_E <- (FB_Int$FBI_29_E + 2)/3
FB_Int$FBI_30_C <- (FB_Int$FBI_30_C + 2)/3

#Mittelwerte der einzelnen RIASEC-Bereiche berechnen
FB_Int$m_FB_Int_R <- rowMeans(FB_Int[,names(FB_Int)[grepl("_R",names(FB_Int))]])
FB_Int$m_FB_Int_I <- rowMeans(FB_Int[,names(FB_Int)[grepl("_I",names(FB_Int))]])
FB_Int$m_FB_Int_A <- rowMeans(FB_Int[,names(FB_Int)[grepl("_A",names(FB_Int))]])
FB_Int$m_FB_Int_S <- rowMeans(FB_Int[,names(FB_Int)[grepl("_S",names(FB_Int))]])
FB_Int$m_FB_Int_E <- rowMeans(FB_Int[,names(FB_Int)[grepl("_E",names(FB_Int))]])
FB_Int$m_FB_Int_C <- rowMeans(FB_Int[,names(FB_Int)[grepl("_C",names(FB_Int))]])

#####################################
############SCORING##################
#####################################

#1. Scoring über Entfernung vom Ideal-Profil nach einzelnen Bereichen
FB_Int$E_Einzeln_R <- abs(FB_Int$m_FB_Int_R - 2.67)
FB_Int$E_Einzeln_I <- abs(FB_Int$m_FB_Int_I - 1)
FB_Int$E_Einzeln_A <- abs(FB_Int$m_FB_Int_A - 1.33)
FB_Int$E_Einzeln_S <- abs(FB_Int$m_FB_Int_S - 2.67)
FB_Int$E_Einzeln_E <- abs(FB_Int$m_FB_Int_E - 4.33)
FB_Int$E_Einzeln_C <- abs(FB_Int$m_FB_Int_C - 6.67)

FB_Int$Score_FB_Int <- rowMeans(FB_Int[,names(FB_Int)[grepl("E_",names(FB_Int))]])

#3. Korrelation zwischen Profilen
FB_Int$p_FB_Int.r <- apply(FB_Int[,names(FB_Int)[grepl("m_",names(FB_Int))]],1,function(x) cor(x, c(2.67,1,1.33,2.67,4.33,6.67)))

##Korrelation zwischen Score_FB_Int und p_FB_Int.r
###############
cor(FB_Int$Score_FB_Int,FB_Int$p_FB_Int.r)

My problem is that the cor function at the end is not working. The Output is "Na". There is one row with Na's in the dataset, is this possibly the reason?

I would be very glad if somebody could help me out.

I created a link with my data:
https://wetransfer.com/downloads/d2f34918ec228bee87459d261227cba720200529074627/cc130a

I hope that is alright like that.

All the best!

Body:
FB_Int$Score_FB_Int is all NAs. I think you need FB_Int$Score_FB_Int <- rowMeans(FB_Int[,names(FB_Int)[grepl("_E",names(FB_Int))]], na.rm = TRUE) and not FB_Int$Score_FB_Int <- rowMeans(FB_Int[,names(FB_Int)[grepl("E_",names(FB_Int))]], na.rm = TRUE) (so _E and not E_). And you also need to use cor like this cor(FB_Int$Score_FB_Int,FB_Int$p_FB_Int.r, use = "pairwise.complete.obs") because you have some NAs in FB_Int$p_FB_Int.r. Then it worked for me.

> cor(FB_Int$Score_FB_Int,FB_Int$p_FB_Int.r, use = "pairwise.complete.obs")
[1] 0.379014


问:
Check for table existance before running sql with Symfony sfPropelMigrationsLightPlugin
I want to check for the existence of a table before running a create SQL statement in the up() method of a migrate.

I can run something like:

```<code>$count = $this->executeSQL("SELECT count(*) FROM information_schema.TABLES where TABLE_NAME = 'table_name';");

if($count == 0)
{
   $this->executeSQL("Create SQL ...");
}
</code>```

The problem is that this returns the following error:

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

Any ideas how to get around this?

答:
I'm dumb...

IF NOT EXISTS

```<code>$this->executeSQL("CREATE TABLE `foo` IF NOT EXISTS");
</code>```

Body:
I want to check for the existence of a table before running a create SQL statement in the up() method of a migrate.

I can run something like:

$count = $this->executeSQL("SELECT count(*) FROM information_schema.TABLES where TABLE_NAME = 'table_name';");

if($count == 0)
{
   $this->executeSQL("Create SQL ...");
}

The problem is that this returns the following error:

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

Any ideas how to get around this?

Body:
I'm dumb...

IF NOT EXISTS

$this->executeSQL("CREATE TABLE `foo` IF NOT EXISTS");


问:
Java patten draw within for loop
I am very new in the programming world and in Javaland too.
I am trying to learn for loop and solving pattern with it.

I want to draw this pattern using for loop :

```<code>*
**
***
****
*****
</code>```

I am using this code to achieve this:

```<code>public class PatterWithForLoop {

    public static void main(String args[]){
        for(int i = 0; i <= 5; i++){
            System.out.println("*" + "\n");
        }
    }
}

</code>```

But, I am only getting * in 15 lines, not in the pattern.
Please, anyone can help to solve this issue here?

Thanks in advance.

答:
Try this code :</p>

```<code>public class Main {
    public static void main(String[] args) {

        int i, j, n =5;
        for(i=0; i<n; i++) {
            for(j=0; j<=i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
</code>```

Title: Java patten draw within for loop

Body:
I am very new in the programming world and in Javaland too.
I am trying to learn for loop and solving pattern with it.

I want to draw this pattern using for loop :

*
**
***
****
*****

I am using this code to achieve this:

public class PatterWithForLoop {

    public static void main(String args[]){
        for(int i = 0; i <= 5; i++){
            System.out.println("*" + "\n");
        }
    }
}

But, I am only getting * in 15 lines, not in the pattern.
Please, anyone can help to solve this issue here?

Thanks in advance.

Body:
Try this code :

public class Main {
    public static void main(String[] args) {

        int i, j, n =5;
        for(i=0; i<n; i++) {
            for(j=0; j<=i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}


问:
Personalised views for a specific Rails controller
The goal is to generate views for given class that are personalised to a given user.
Model and Controller logic remain the same, but the layout and record presentation would be subject to user preferences.

Given the unicity of User.id it is readily available to create application_controller logic to use a layout with that id.

```<code>layout = @user.layout
</code>```

The layout would be able to invoke its personalised CSS.

But what of the views?  and the routing?  Given a class Product  how can the

```<code>resources :products
</code>```

invoke a subdirectory of app/views/products to use that of the user's id, say

```<code>app/views/products/10
</code>```

Thus leading to a structure of files

```<code>app/views/products/10/show.html.erb
app/views/products/10/edit.html.erb
app/views/products/10/index.html.erb
app/views/products/11/show.html.erb
app/views/products/11/edit.html.erb
app/views/products/11/index.html.erb
app/views/products/12/show.html.erb
app/views/products/12/edit.html.erb
app/views/products/12/index.html.erb
</code>```

答:
Answering your question you have call render in each method in the controller.

```<code>def show
  ...
  render "user/show/#{params[:id]}.html.erb"
end

</code>```

You have more info here: https://guides.rubyonrails.org/layouts_and_rendering.html#using-render

But, unless they are TOTALLY different it would be better using the same view for every record and keeping a field for each one with options to manipulate the view.

```<code>@user.layout = {header: true, footer: false, ...}
</code>```

And in the view:

```<code><% if @user.layout[:header] %>
   <div>....</div>
<% end %>
</code>```

Body:
The goal is to generate views for given class that are personalised to a given user.
Model and Controller logic remain the same, but the layout and record presentation would be subject to user preferences.

Given the unicity of User.id it is readily available to create application_controller logic to use a layout with that id.

layout = @user.layout

The layout would be able to invoke its personalised CSS.

But what of the views?  and the routing?  Given a class Product  how can the

resources :products

invoke a subdirectory of app/views/products to use that of the user's id, say

app/views/products/10

Thus leading to a structure of files

app/views/products/10/show.html.erb
app/views/products/10/edit.html.erb
app/views/products/10/index.html.erb
app/views/products/11/show.html.erb
app/views/products/11/edit.html.erb
app/views/products/11/index.html.erb
app/views/products/12/show.html.erb
app/views/products/12/edit.html.erb
app/views/products/12/index.html.erb

Body:
Answering your question you have call render in each method in the controller.

def show
  ...
  render "user/show/#{params[:id]}.html.erb"
end

You have more info here: https://guides.rubyonrails.org/layouts_and_rendering.html#using-render

But, unless they are TOTALLY different it would be better using the same view for every record and keeping a field for each one with options to manipulate the view.

@user.layout = {header: true, footer: false, ...}

And in the view:

<% if @user.layout[:header] %>
   <div>....</div>
<% end %>


答:
Your for-loop seems strange.

The loop should be read like this:

"For int i starting at 0, loop as long as i<5 and after every iteration, do i++"

```<code>for(int i = 0; i<5, i++){
   System.out.println("*" \n);
}
</code>```

This will print 5 rows:

```<code>*

*

*

*

*
</code>```

now in every row you want one more * and you might want to remove the \n which is already included in println
So instead of printing "*" you create a String before the loop and you add one new * to it every iteration:

```<code>String line ="";             // we start with an empty string
for(int i=0; i<5; i++){
   line= line+"*";           // before printing we add a new *
   System.out.println(line); // then we print it
}
</code>```

It should (haven't tested it) result in this:

```<code>*
**
***
****
*****
</code>```

Title: Java patten draw within for loop

Body:
Your for-loop seems strange.

The loop should be read like this:

"For int i starting at 0, loop as long as i<5 and after every iteration, do i++"

for(int i = 0; i<5, i++){
   System.out.println("*" \n);
}

This will print 5 rows:

*

*

*

*

*

now in every row you want one more * and you might want to remove the \n which is already included in println
So instead of printing "*" you create a String before the loop and you add one new * to it every iteration:

String line ="";             // we start with an empty string
for(int i=0; i<5; i++){
   line= line+"*";           // before printing we add a new *
   System.out.println(line); // then we print it
}

It should (haven't tested it) result in this:

*
**
***
****
*****


问:
How to remove a label from a kubernetes object just with "kubectl apply -f file.yaml"?
I'm playing around with GitOps and ArgoCD in Redhat Openshift. My goal is to switch a worker node to an infra node.

I want to do this with descriptive YAML Files, and NOT manually by using the command line (that's easy with kubectl label node ...)

In order to do make the node an infra node, I want to add a label "infra" and take the label "worker" from it. Before, the object looks like this (irrelevant labels omitted):

```<code>apiVersion: v1
kind: Node
metadata:
  labels:
    node-role.kubernetes.io/infra: ""
  name: node6.example.com
spec: {}
</code>```

After applying a YAML File, it's supposed to look like that:

```<code>apiVersion: v1
kind: Node
metadata:
  labels:
    node-role.kubernetes.io/worker: ""
  name: node6.example.com
spec: {}
</code>```

If I put the latter config in a file, and do "kubectl apply -f ", the node has both infra and worker labels. So adding a label or changing the value of a label is easy, but is there a way to remove a label in an objects metadata by applying a YAML file ?

答:
Try setting the worker label to false:

```<code>node-role.kubernetes.io/worker: "false"
</code>```

Worked for me on OpenShift 4.4.

Edit:
This doesn't work. What happened was:

Applied YML file containing node-role.kubernetes.io/worker: "false"

Automated process ran deleting the node-role.kubernetes.io/worker label from the node (due to it not being specified in the YML it would automatically apply)

What's funny is that the automated process would not delete the label if it was empty instead of set to false.

Body:
I'm playing around with GitOps and ArgoCD in Redhat Openshift. My goal is to switch a worker node to an infra node.

I want to do this with descriptive YAML Files, and NOT manually by using the command line (that's easy with kubectl label node ...)

In order to do make the node an infra node, I want to add a label "infra" and take the label "worker" from it. Before, the object looks like this (irrelevant labels omitted):

apiVersion: v1
kind: Node
metadata:
  labels:
    node-role.kubernetes.io/infra: ""
  name: node6.example.com
spec: {}

After applying a YAML File, it's supposed to look like that:

apiVersion: v1
kind: Node
metadata:
  labels:
    node-role.kubernetes.io/worker: ""
  name: node6.example.com
spec: {}

If I put the latter config in a file, and do "kubectl apply -f ", the node has both infra and worker labels. So adding a label or changing the value of a label is easy, but is there a way to remove a label in an objects metadata by applying a YAML file ?

Body:
Try setting the worker label to false:

node-role.kubernetes.io/worker: "false"

Worked for me on OpenShift 4.4.

Edit:
This doesn't work. What happened was:

Applied YML file containing node-role.kubernetes.io/worker: "false"

Automated process ran deleting the node-role.kubernetes.io/worker label from the node (due to it not being specified in the YML it would automatically apply)

What's funny is that the automated process would not delete the label if it was empty instead of set to false.


问:
How to add value in a public property of List<string> type in c#?
```<code>private List<string> _Baseline = new List<string>();

public List<string> Baseline
{
    get { return _Baseline; }
    set { _Baseline = value; }
}
</code>```

<p>How can I set this property?
It does not let me add using the add method; it throws an "object reference null" error. </p>

答:
There are 3 possibilities:

your list<string> is null

the object containing your list<string> is null

the item you are inserting is null

1 is addressed when you assign a new List to it

2 and 3 we can not ascertain from the code you post here.

if you do not intend to allow assignment of a new list object outside of your class, then you do not, as noted elsewhere, need a setter.  You can either remove it or declare it private or protected, like this....

```<code>public List<string> Baseline
{
    get { return _Baseline; }
    protected set { _Baseline = value; }
}
</code>```

OwnerDisplayName: Neil

ContentLicense: CC BY-SA 2.5

Body:
private List<string> _Baseline = new List<string>();

public List<string> Baseline
{
    get { return _Baseline; }
    set { _Baseline = value; }
}

How can I set this property?
It does not let me add using the add method; it throws an "object reference null" error.

LastEditorDisplayName: David Brown

Body:
There are 3 possibilities:

your list<string> is null

the object containing your list<string> is null

the item you are inserting is null

1 is addressed when you assign a new List to it

2 and 3 we can not ascertain from the code you post here.

if you do not intend to allow assignment of a new list object outside of your class, then you do not, as noted elsewhere, need a setter.  You can either remove it or declare it private or protected, like this....

public List<string> Baseline
{
    get { return _Baseline; }
    protected set { _Baseline = value; }
}

OwnerDisplayName: Chris


问:
Why is the web page show a scroll bar when `body` set to `min-height: 100vh`?
I already reset all the margin and padding to 0.
see the codepen: https://codepen.io/geeklog/pen/zYvVeOZ

hello

```

<pre class="lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  margin: 10px auto;
  background-color: orange;
}
</code>```

答:
because of your margin of .container

you have 2 options,

first, remove the margin of .container.

second, add overflow: hidden on body

I think the first option is better.

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

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  background-color: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">hello</div></code>```

Body:
I already reset all the margin and padding to 0.
see the codepen: https://codepen.io/geeklog/pen/zYvVeOZ

hello

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

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  margin: 10px auto;
  background-color: orange;
}

Body:
because of your margin of .container

you have 2 options,

first, remove the margin of .container.

second, add overflow: hidden on body

I think the first option is better.

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

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  background-color: orange;
}

<div class="container">hello</div>


问:
Optional spaces \s+? are not honoured in regular expression
I am expecting the following regex to allow 0-n spaces between operators, but it is forcing at least one. Can someone please correct the error of my ways?

```<code>((\d+\.?\d*|\d*\.?\d+\s+?[\+\-\/\*]\s+?)+)(\d+\.?\d*|\d*\.?\d+)
</code>```

Examples

```<code>24*3.2
24 * 3.2
</code>```

Only the 2nd example is allowed through.

I understood \s+? should be an optional number of spaces?

Playpen

答:
+? (or more generally ? following any other quantifier) is a non-greedy quantifier. It does not mean “make the preceding match optional”.

Use * instead of +?.

Body:
I am expecting the following regex to allow 0-n spaces between operators, but it is forcing at least one. Can someone please correct the error of my ways?

((\d+\.?\d*|\d*\.?\d+\s+?[\+\-\/\*]\s+?)+)(\d+\.?\d*|\d*\.?\d+)

Examples

24*3.2
24 * 3.2

Only the 2nd example is allowed through.

I understood \s+? should be an optional number of spaces?

Playpen


问:
Error: getting availability zones when trying to create EKS cluster
I'm trying to create an EKS cluster but I keep getting the following error. I think it's an issue of permissions, roles, etc but I have minimum experience with AWS stuff.

I found this thread but I have no idea how to implement all these things.

Any help is appreciated, thanks in advance.

```<code>$ eksctl create cluster
[ℹ]  eksctl version 0.13.0
[ℹ]  using region us-west-2
Error: getting availability zones: getting availability zones for us-west-2: UnauthorizedOperation: You are not authorized to perform this operation.
    status code: 403, request id: 724b0c02-fb51-43b2-98ab-746a3d2e45a0
</code>```

答: I have not been able to find the perfect solution but for now you can provide your user with AdministratorAccess policy and it works in IAM.

Body:
I'm trying to create an EKS cluster but I keep getting the following error. I think it's an issue of permissions, roles, etc but I have minimum experience with AWS stuff.

I found this thread but I have no idea how to implement all these things.

Any help is appreciated, thanks in advance.

$ eksctl create cluster
[ℹ]  eksctl version 0.13.0
[ℹ]  using region us-west-2
Error: getting availability zones: getting availability zones for us-west-2: UnauthorizedOperation: You are not authorized to perform this operation.
    status code: 403, request id: 724b0c02-fb51-43b2-98ab-746a3d2e45a0


问:
Angular CLI - different sets of dev and prod assets
I can't seem to find if and how it would be possible to use a different set of assets whenever I use the --prod switch of ng build.

The use case is that I have multiple projects with a common set of assets in a shared folder, so the configuration of each single project in angular.json is like this:

```<code>"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project1/src/assets/",
    "output": "/assets/"
  }
],
...
"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project2/src/assets/",
    "output": "/assets/"
  }
],

</code>```

When making production builds, I would like to remove the common src/assets path.

Is it possible?

答:
I think the answer was right under my nose: each configurations object allows a redefined assets property.

So my requirement's configuration is as simple as:

```<code>{
"configurations": {
  "production": {
     "assets": [
       {
         "glob": "**/*",
         "input": "projects/project1/src/assets/",
         "output": "/assets/"
       }
     ],
     ...
  }
}
</code>```

It works like a charm.

Body:
I can't seem to find if and how it would be possible to use a different set of assets whenever I use the --prod switch of ng build.

The use case is that I have multiple projects with a common set of assets in a shared folder, so the configuration of each single project in angular.json is like this:

"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project1/src/assets/",
    "output": "/assets/"
  }
],
...
"assets": [
  {
    "glob": "**/*",
    "input": "src/assets",
    "output": "/assets/"
  },
  {
    "glob": "**/*",
    "input": "projects/project2/src/assets/",
    "output": "/assets/"
  }
],

When making production builds, I would like to remove the common src/assets path.

Is it possible?

Body:
I think the answer was right under my nose: each configurations object allows a redefined assets property.

So my requirement's configuration is as simple as:

{
"configurations": {
  "production": {
     "assets": [
       {
         "glob": "**/*",
         "input": "projects/project1/src/assets/",
         "output": "/assets/"
       }
     ],
     ...
  }
}

It works like a charm.


问:
X509Certificate2.GetECDsaPrivateKey error keyHandle null value
I generated a pfx file with the following commands

```<code>openssl ec -in apple-private-key.pem -pubout -out apple-public-key.pem
openssl req -new -key apple-private-key.pem -x509 -nodes -subj "/CN=apple.my.com" -out certificat.pem
openssl pkcs12 -in certificat.pem -inkey apple-private-key.pem -export -out certificate.pfx
</code>```

and when I try to load it only with the flag X509KeyStorageFlags.MachineKeySet
this flag is necessary for me, for the execution on a windows server with IIS

```<code>// only if add MachineKeySet flag
var certificate = new X509Certificate2("apple-certificate.pfx", "password", X509KeyStorageFlags.MachineKeySet);
var ecDsa = certificate.GetECDsaPrivateKey(); // <<   Error keyHandle Null ?
var key = new ECDsaSecurityKey(ecDsa) { KeyId = _keyId };
var signingCredentials = new SigningCredentials(key, "ES256", _keyId);
</code>```

Error

```<code>System.ArgumentNullException
  HResult=0x80004003
  Message=La valeur ne peut pas être null.
Nom du paramètre : keyHandle
  Source=System.Core
  Arborescence des appels de procédure :
   à System.Security.Cryptography.CngKey.Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions)
   à System.Security.Cryptography.X509Certificates.ECDsaCertificateExtensions.GetECDsaPrivateKey(X509Certificate2 certificate)
</code>```

答:
It must run with a local administrator account, for this to work.

Thanks, Crypt32, jdweng

https://paulstovell.com/x509certificate2/

Body:
I generated a pfx file with the following commands

openssl ec -in apple-private-key.pem -pubout -out apple-public-key.pem
openssl req -new -key apple-private-key.pem -x509 -nodes -subj "/CN=apple.my.com" -out certificat.pem
openssl pkcs12 -in certificat.pem -inkey apple-private-key.pem -export -out certificate.pfx

and when I try to load it only with the flag X509KeyStorageFlags.MachineKeySet
this flag is necessary for me, for the execution on a windows server with IIS

// only if add MachineKeySet flag
var certificate = new X509Certificate2("apple-certificate.pfx", "password", X509KeyStorageFlags.MachineKeySet);
var ecDsa = certificate.GetECDsaPrivateKey(); // <<   Error keyHandle Null ?
var key = new ECDsaSecurityKey(ecDsa) { KeyId = _keyId };
var signingCredentials = new SigningCredentials(key, "ES256", _keyId);

Error

System.ArgumentNullException
  HResult=0x80004003
  Message=La valeur ne peut pas être null.
Nom du paramètre : keyHandle
  Source=System.Core
  Arborescence des appels de procédure :
   à System.Security.Cryptography.CngKey.Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions)
   à System.Security.Cryptography.X509Certificates.ECDsaCertificateExtensions.GetECDsaPrivateKey(X509Certificate2 certificate)


问:
Disassemble an OpenCL kernel?
I'm not sure if it's possible. I want to study OpenCL in-depth, so I was wondering if there is a tool to disassemble an compiled OpenCL kernel.

For normal x86 executable, I can use objdump to get a disassembly view. Is there a similar tool for OpenCL kernel, yet?

答:
The simplest solution, in my experience, is to use clangs OpenCL C compiler and emit SPIR.
It even works on Godbolt's compiler explorer:
https://godbolt.org/z/_JbXPb

Clang can also emit ptx (https://godbolt.org/z/4ARMqM) and amdhsa (https://godbolt.org/z/TduTZQ), but it may not correspond to the ptx and amdhsa assembly generated by the respective driver at runtime.

Title: Disassemble an OpenCL kernel?


问:
MongoDB how to create role on anydatabase, I need a restrited role to only showUsers Action on any databases
For known all databases (even with just users declared) I use with pymongo (pymongo==3.10.1 with mongodb 4.2)

```<code>db.command({'usersInfo': { 'forAllDBs': True },
           'showCredentials': True})
</code>```

this command need userAdminAnyDatabase builtin-role on client user.
But this role provide to much privileges. If someone crack the user password he can upgrade role to dbAdminAnyDatabases.
So I failed to create a any database role with authorization (role with only viewUser action on any databases) for userinfos previous command.

any  can help me for this role definition?

答:
Thank's i create role :

```<code>with pymongo.MongoClient('mongodb://localhost:27017/',
                     username='SuperAdmin',
                     password='XXXXXXXXXX',
                     authSource='admin',
                     authMechanism='SCRAM-SHA-256') as client:

        extendRole="showUsersAnyBase"
        crole=client['admin'].command('rolesInfo',extendRole)
        if reinit and extendRole  in [x['role'] for x in crole['roles']]:
            client['admin'].command('dropRole',extendRole)
        if reinit or extendRole not in [x['role'] for x in crole['roles']]:
            client['admin'].command({'createRole': extendRole,
                                              'privileges': [{'resource': { 'anyResource': True },
                                               'actions': [ "viewUser" ]}],
                                              'roles':[ ]
                                              })
</code>```

create connector user:

```<code>usersInfos=client['admin'].command({'usersInfo': [{'user' : 'connector','db': 'admin'}]})
        if reinitConnector and 'connector'  in [x['user'] for x in usersInfos['users']]:
            client['admin'].command('dropUser',"connector")
        if reinitConnector or 'connector' not in [x['user'] for x in usersInfos['users']]:
            client['admin'].command("createUser", "connector",
                                     pwd="XXXXXXXXXX",
                                     roles=[extendRole])
</code>```

use the connector user with for userInfos command:

```<code>with pymongo.MongoClient('mongodb://localhost:27017/',
                        username='connector',
                        password='XXXXXXXXXX',
                        authSource='admin',
                        authMechanism='SCRAM-SHA-256') as client2:

        usersInfos=client2['admin'].command({
                                             'usersInfo': { 'forAllDBs': True },
                                             'showCredentials': True
                                             })
        for user in usersInfos['users']:
            print("user:",user['user'],
                   "db:",user['db'],
                   "roles:",[x['db']+'->'+x['role'] for x in user['roles']])
</code>```

Works fine !!

and connector user can't grant role:

```<code>        client2['admin'].command('grantRolesToUser','connector',
                                  roles=['dbAdminAnyDatabase'])
</code>```

throw exception :

```<code>.....
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: not authorized on admin to execute command { grantRolesToUser: "connector", .....
</code>```

Body:
For known all databases (even with just users declared) I use with pymongo (pymongo==3.10.1 with mongodb 4.2)

db.command({'usersInfo': { 'forAllDBs': True },
           'showCredentials': True})

this command need userAdminAnyDatabase builtin-role on client user.
But this role provide to much privileges. If someone crack the user password he can upgrade role to dbAdminAnyDatabases.
So I failed to create a any database role with authorization (role with only viewUser action on any databases) for userinfos previous command.

any  can help me for this role definition?

Body:
Thank's i create role :

with pymongo.MongoClient('mongodb://localhost:27017/',
                     username='SuperAdmin',
                     password='XXXXXXXXXX',
                     authSource='admin',
                     authMechanism='SCRAM-SHA-256') as client:

        extendRole="showUsersAnyBase"
        crole=client['admin'].command('rolesInfo',extendRole)
        if reinit and extendRole  in [x['role'] for x in crole['roles']]:
            client['admin'].command('dropRole',extendRole)
        if reinit or extendRole not in [x['role'] for x in crole['roles']]:
            client['admin'].command({'createRole': extendRole,
                                              'privileges': [{'resource': { 'anyResource': True },
                                               'actions': [ "viewUser" ]}],
                                              'roles':[ ]
                                              })

create connector user:

usersInfos=client['admin'].command({'usersInfo': [{'user' : 'connector','db': 'admin'}]})
        if reinitConnector and 'connector'  in [x['user'] for x in usersInfos['users']]:
            client['admin'].command('dropUser',"connector")
        if reinitConnector or 'connector' not in [x['user'] for x in usersInfos['users']]:
            client['admin'].command("createUser", "connector",
                                     pwd="XXXXXXXXXX",
                                     roles=[extendRole])

use the connector user with for userInfos command:

with pymongo.MongoClient('mongodb://localhost:27017/',
                        username='connector',
                        password='XXXXXXXXXX',
                        authSource='admin',
                        authMechanism='SCRAM-SHA-256') as client2:

        usersInfos=client2['admin'].command({
                                             'usersInfo': { 'forAllDBs': True },
                                             'showCredentials': True
                                             })
        for user in usersInfos['users']:
            print("user:",user['user'],
                   "db:",user['db'],
                   "roles:",[x['db']+'->'+x['role'] for x in user['roles']])

Works fine !!

and connector user can't grant role:

        client2['admin'].command('grantRolesToUser','connector',
                                  roles=['dbAdminAnyDatabase'])

throw exception :

.....
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: not authorized on admin to execute command { grantRolesToUser: "connector", .....